From 65030ac5e572a6a3b8ef3d2a17c18fe985b7d1d8 Mon Sep 17 00:00:00 2001 From: Tobias Girstmair Date: Sat, 25 May 2024 15:47:37 +0200 Subject: [PATCH] deduplicate blocking for irc response during setup --- ircpipe.c | 44 +++++++++++++++++++++----------------------- 1 file changed, 21 insertions(+), 23 deletions(-) diff --git a/ircpipe.c b/ircpipe.c index ae71e50..3d9adb1 100644 --- a/ircpipe.c +++ b/ircpipe.c @@ -190,13 +190,28 @@ int irc_base64(char *buf, int n) { return l; } -int irc_setup(const sock_t sock, const int outfd, const char *nick, const char *pass, int pass_type, const char *chan) { - char buf[BUFSIZ]; +int irc_wait(const sock_t sock, const int outfd, int cmd, char* buf) { int n; struct pollfd fds[1]; fds[0].fd = sock.fd; fds[0].events = POLLIN; + for (;;) { /* note: reusing callee's buf */ + if (poll(fds, 1, POLL_TIMEOUT)) { + n = READ(sock, buf, BUFSIZ); buf[n] = '\0'; + if (n == 0) return -1; /* server closed connection */ + write(outfd, buf, n); + n = irc_answer(sock, buf, cmd); + if (n & cmd) return 0; + else if (n & ERRS) return -1; + } + } +} + +int irc_setup(const sock_t sock, const int outfd, const char *nick, const char *pass, int pass_type, const char *chan) { + char buf[BUFSIZ]; + int n; + if (pass_type == SASL_PLAIN_PASSWD) { n = snprintf(buf, BUFSIZ, "CAP REQ :sasl\r\n"); WRITE(sock, buf, n); @@ -226,33 +241,16 @@ int irc_setup(const sock_t sock, const int outfd, const char *nick, const char * } /* block until we get a RPL_WELCOME or an error: */ - for (;;) { - if (poll(fds, 1, POLL_TIMEOUT)) { - n = READ(sock, buf, BUFSIZ); buf[n] = '\0'; - if (n == 0) return -1; /* server closed connection */ - write(outfd, buf, n); - n = irc_answer(sock, buf, NICK); - if (n & NICK) break; - else if (n & ERRS) return -1; - } - } + n = irc_wait(sock, outfd, NICK, buf); + if (n < 0) return n; if (chan) { n = snprintf(buf, BUFSIZ, "JOIN %s\r\n", chan); WRITE(sock, buf, n); /* block until we get a JOIN response or an error: */ - /* todo: dedup this block with NICK/RPL_WELCOME */ - for (;;) { - if (poll(fds, 1, POLL_TIMEOUT)) { - n = READ(sock, buf, BUFSIZ); buf[n] = '\0'; - if (n == 0) return -1; /* server closed connection */ - write(outfd, buf, n); - n = irc_answer(sock, buf, JOIN); - if (n & JOIN) break; - else if (n & ERRS) return -1; - } - } + n = irc_wait(sock, outfd, JOIN, buf); + if (n < 0) return n; } return 0; -- 2.39.3