From c9c24d9a8bfd24a0af0f51d0352aaf8663da2822 Mon Sep 17 00:00:00 2001 From: Neale Pickett Date: Fri, 10 Sep 2010 23:07:40 -0600 Subject: [PATCH] Create new fgrepx common function It's also slightly quicker. --- src/claim.cgi.c | 42 +++--------------------------------------- src/common.c | 38 ++++++++++++++++++++++++++++++++++++++ src/common.h | 1 + 3 files changed, 42 insertions(+), 39 deletions(-) diff --git a/src/claim.cgi.c b/src/claim.cgi.c index 82463e9..f079836 100644 --- a/src/claim.cgi.c +++ b/src/claim.cgi.c @@ -7,20 +7,6 @@ char const *tokenlog = "/var/lib/ctf/tokend/tokens.log"; char const *claimlog = "/var/lib/ctf/tokend/claim.log"; -int -mystrcmp(char *a, char *b) -{ - while (*a == *b) { - a += 1; - b += 1; - } - if (((*a == '\0') || (*a == '\n')) && - ((*b == '\0') || (*b == '\n'))) { - return 0; - } - return -1; -} - int main(int argc, char *argv[]) { @@ -75,31 +61,9 @@ main(int argc, char *argv[]) cgi_page("No such team", ""); } - /* Does the token exist? */ - { - FILE *f; - int valid = 0; - - f = fopen(claimlog, "r"); - if (f) { - while (1) { - char line[100]; - - if (NULL == fgets(line, sizeof(line), f)) { - break; - } - if (0 == mystrcmp(line, token)) { - valid = 1; - break; - } - } - fclose(f); - } - - if (! valid) { - cgi_page("Invalid token", - "

Sorry, that token's no good.

"); - } + if (! fgrepx(token, claimlog)) { + cgi_page("Invalid token", + "

Sorry, that token's no good.

"); } /* If the token's unclaimed, award points and log the claim */ diff --git a/src/common.c b/src/common.c index dea8a60..d5ec3cf 100644 --- a/src/common.c +++ b/src/common.c @@ -7,6 +7,44 @@ #include #include "common.h" +#define EOL(c) ((EOF == (c)) || (0 == (c)) || ('\n' == (c))) + +int +fgrepx(char const *needle, char const *filename) +{ + FILE *f; + int found = 0; + char const *p = needle; + + f = fopen(filename, "r"); + if (f) { + while (1) { + int c = fgetc(f); + + /* This list of cases would have looked so much nicer in OCaml. I + apologize. */ + if (EOL(c) && (0 == *p)) { + found = 1; + break; + } else if (EOF == c) { + break; + } else if ((0 == p) || (*p != c)) { + p = needle; + do { + c = fgetc(f); + } while (! EOL(c)); + } else if ('\n' == c) { + p = needle; + } else { + p += 1; + } + } + fclose(f); + } + + return found; +} + int team_exists(char *teamhash) { diff --git a/src/common.h b/src/common.h index 7dca329..51399db 100644 --- a/src/common.h +++ b/src/common.h @@ -6,5 +6,6 @@ int team_exists(char *teamhash); int award_points(char *teamhash, char *category, int point); +int fgrepx(char const *needle, char const *filename); #endif