gods

a simple blocklist for ssh
Log | Files | Refs | README | LICENSE

commit ba7e5a3e9562ba1df4047996c14c8f425d43ede5
parent ab58abffb9808ad1b65cc09e9656699e6fcececc
Author: Naveen Narayanan <zerous@nocebo.space>
Date:   Sat,  9 Oct 2021 18:57:45 +0200

Implement readline()

The function readline() uses read() to check if there
is new data; if it finds new data it returns the same
otherwise NULL is returned. main() uses this function
to process new data if found or usleep() otherwise.

Diffstat:
Mmain.c | 62++++++++++++++++++++++++++++++++++++++++++--------------------
1 file changed, 42 insertions(+), 20 deletions(-)

diff --git a/main.c b/main.c @@ -1,8 +1,10 @@ #include <err.h> #include <errno.h> +#include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <unistd.h> #include "attack.h" #include "config.h" @@ -10,7 +12,7 @@ #include "parser.h" #include "queue.h" -#define BUFSZ 256 +#define BUFSZ 512 static char buf[BUFSZ]; SLIST_HEAD(lhead, attacker) head = SLIST_HEAD_INITIALIZER(head); @@ -47,35 +49,55 @@ init(struct attacker *a) a->last = attack; } +/* + * XXX readline relies upon the assumption + * that a line can be atmost BUFSZ long + */ +char * +readline(int fd) +{ + static char *next; + static int rem; + int n; + + if (rem) + for (int i = 0; i < rem; ++i) + buf[i] = next[i]; + + if ((n = read(fd, buf+rem, BUFSZ-rem)) == -1) + err(1, "read failed"); + + rem += n; + for (int i = 0; i < rem; ++i) + if (buf[i] == '\n') { + buf[i] = '\0'; + rem -= i+1; + next = (rem == 0) ? NULL : &buf[i+1]; + return buf; + } + + return NULL; +} + int main(int argc, char **argv) { - FILE *fp; char *line; - int c, found; + int fd, found; struct attacker *a; - fp = fopen(sshlog, "r"); - if (!fp) - err(1, "fopen failed: %s", sshlog); + fd = open(sshlog, O_RDONLY); + if (fd == -1) + err(1, "open failed: %s", sshlog); - c = 0; for ( ; ; ) { - if (c == EOF) - break; - - line = buf; - memset(buf, 0, BUFSZ); - - while ((c = fgetc(fp)) != EOF) { - if (c == '\n') { - *line = '\0'; - break; - } - *line++ = c; + while ((line = readline(fd)) == NULL) { + usleep(500000); + continue; } - if (parse(buf) == -1) { + + if (parse(line) == -1) { fprintf(stderr, "parse failed\n"); continue; }