#include #include #include #include #include // Make sure that your cookie name is all letters #define COOKIENAME "deanscookie" // From RFC 2109 // av-pairs = av-pair *(";" av-pair) // av-pair = attr ["=" value] ; optional value // attr = token // value = word // word = token | quoted-string // // From RFC 2068 // quoted-string = ( <"> *(qdtext) <"> ) // qdtext = > int getCookie(char *allCookies, int &parsedCookie) { regex_t infoRE; regmatch_t matchRE[5] ; int errorRE, rv, p ; // Heck... This isn't perfect, but it's close enough // Also, don't try to get it perfect because the // browsers don't always do the right thing // and you'll only get heart break for trying // Maybe someday some student will look up regular expressions const char regPat[] = "^(([^;]|(\"[^\"]*\"))*;)*" "[ ]*" COOKIENAME "[ ]*=[ ]*([0-9][0-9][0-9][0-9][0-9][0-9])[ ]*" "(;([^;]|(\"[^\"]*\"))*)*$" ; errorRE = regcomp(&infoRE, regPat, REG_EXTENDED) ; if (errorRE) { // If you can't find the cookie, always return 0 parsedCookie = 0 ; return 0 ; } errorRE = regexec(&infoRE, allCookies, 5, matchRE, 0) ; if (errorRE || ( matchRE[4].rm_so == -1)) { return 1 ; } rv = 0 ; for (p = matchRE[4].rm_so; p < matchRE[4].rm_eo ; ++p) rv = 10*rv + (int) allCookies[p] - (int) '0' ; parsedCookie = rv ; return 0 ; } inline int read_number(char *q, int &p) { int n = 0 ; while (isdigit(q[p])) { n = 10*n + (int) q[p] - (int) '0' ; ++p ; } return n ; } inline void skip_blanks(char *q, int &p) { while (q[p] && q[p] == ' ') ++p ; } // returns 0 on success, 1 on failure int parseNumber(char *q, int &num) { int ret ; int p = 0 ; // Just doing it a very simple way // read in plus sign if (q[p] != '+') return 1 ; ++p ; // read in the number if (!isdigit(q[p])) return 1 ; ret = read_number(q, p) ; // be sure we're at the end if (q[p] != '\0') return 1 ; num = ret ; return 0 ; } void printErrorMessage(char *M) { cout << "Content-type: text/html" << endl << endl << "" << endl << "Unable to process request" << endl << "" << endl << "

Unable to process request

" << endl << "

Unable to process form because " << M << "

" << endl << "" << endl << "" << endl ; } void printSuccess(int cookie, int adden) { // You need to put in something here // Oh... You have to make sure that cookie is six digits long } void main(int argc, char *argv[]) { char *qs, *envCookie ; int cookie, n ; qs = getenv("QUERY_STRING") ; envCookie = getenv("HTTP_COOKIE") ; if (qs ==(char *)NULL) printErrorMessage("no query string") ; else if (parseNumber(qs, n)) printErrorMessage("bad query string") ; else if (envCookie == (char *)NULL) printSuccess(0, n) ; else if (getCookie(envCookie, cookie)) printErrorMessage("bad cookies") ; else printSuccess(cookie, n) ; }