14 typedef struct Cookie Cookie;
15 typedef struct Jar Jar;
22 char* dom; /* starts with . */
25 char* comment; /* optional, may be nil */
27 uint expire; /* time of expiration: ~0 means when webcookies dies */
29 int explicitdom; /* dom was explicitly set */
30 int explicitpath; /* path was explicitly set */
56 "domain", offsetof(Cookie, dom), 1,
57 "path", offsetof(Cookie, path), 1,
58 "name", offsetof(Cookie, name), 0,
59 "value", offsetof(Cookie, value), 0,
60 "comment", offsetof(Cookie, comment), 1,
61 "version", offsetof(Cookie, version), 1,
68 "expire", offsetof(Cookie, expire),
69 "secure", offsetof(Cookie, secure),
70 "explicitdomain", offsetof(Cookie, explicitdom),
71 "explicitpath", offsetof(Cookie, explicitpath),
72 "netscapestyle", offsetof(Cookie, netscapestyle),
75 #pragma varargck type "J" Jar*
76 #pragma varargck type "K" Cookie*
85 jar = va_arg(fp->args, Jar*);
87 if(jar == nil || jar->nc == 0)
90 fmtstrcpy(fp, "Cookie: ");
92 fmtprint(fp, "$Version=%s; ", jar->c[0].version);
93 for(i=0; i<jar->nc; i++)
94 fmtprint(fp, "%s%s=%s", i ? "; ": "", jar->c[i].name, jar->c[i].value);
95 fmtstrcpy(fp, "\r\n");
99 /* individual cookie */
107 c = va_arg(fp->args, Cookie*);
110 for(j=0; j<nelem(stab); j++){
111 t = *(char**)((uintptr)c+stab[j].offset);
118 fmtprint(fp, "%s=%q", stab[j].s, t);
120 for(j=0; j<nelem(itab); j++){
121 k = *(int*)((uintptr)c+itab[j].offset);
128 fmtprint(fp, "%s=%ud", itab[j].s, k);
137 * - longer paths first, then alpha by path (RFC2109 4.3.4)
140 cookiecmp(Cookie *a, Cookie *b)
144 if((i = strcmp(a->name, b->name)) != 0)
146 if((i = cistrcmp(a->dom, b->dom)) != 0)
148 if((i = strlen(b->path) - strlen(a->path)) != 0)
150 if((i = strcmp(a->path, b->path)) != 0)
156 exactcookiecmp(Cookie *a, Cookie *b)
160 if((i = cookiecmp(a, b)) != 0)
162 if((i = strcmp(a->value, b->value)) != 0)
164 if(a->version || b->version){
169 if((i = strcmp(a->version, b->version)) != 0)
172 if(a->comment || b->comment){
177 if((i = strcmp(a->comment, b->comment)) != 0)
180 if((i = b->expire - a->expire) != 0)
182 if((i = b->secure - a->secure) != 0)
184 if((i = b->explicitdom - a->explicitdom) != 0)
186 if((i = b->explicitpath - a->explicitpath) != 0)
188 if((i = b->netscapestyle - a->netscapestyle) != 0)
195 freecookie(Cookie *c)
199 for(i=0; i<nelem(stab); i++)
200 free(*(char**)((uintptr)c+stab[i].offset));
204 copycookie(Cookie *c)
209 for(i=0; i<nelem(stab); i++){
210 ps = (char**)((uintptr)c+stab[i].offset);
212 *ps = estrdup9p(*ps);
217 delcookie(Jar *j, Cookie *c)
223 if(i < 0 || i >= j->nc)
229 addcookie(Jar *j, Cookie *c)
233 if(!c->name || !c->value || !c->path || !c->dom){
234 fprint(2, "not adding incomplete cookie\n");
239 fprint(2, "add %K\n", c);
241 for(i=0; i<j->nc; i++)
242 if(cookiecmp(&j->c[i], c) == 0){
244 fprint(2, "cookie %K matches %K\n", &j->c[i], c);
245 if(exactcookiecmp(&j->c[i], c) == 0){
247 fprint(2, "\texactly\n");
251 delcookie(j, &j->c[i]);
257 j->c = erealloc9p(j->c, j->mc*sizeof(Cookie));
260 copycookie(&j->c[j->nc]);
269 for(i=j->nc-1; i>=0; i--){
272 freecookie(&j->c[i]);
274 j->c[i] = j->c[j->nc];
279 addtojar(Jar *jar, char *line, int ondisk)
283 char *f[20], *attr, *val, **pstr;
285 memset(&c, 0, sizeof c);
288 nf = tokenize(line, f, nelem(f));
291 if((val = strchr(attr, '=')) != nil)
295 /* string attributes */
296 for(j=0; j<nelem(stab); j++){
297 if(strcmp(stab[j].s, attr) == 0){
298 pstr = (char**)((uintptr)&c+stab[j].offset);
302 /* integer attributes */
303 for(j=0; j<nelem(itab); j++){
304 if(strcmp(itab[j].s, attr) == 0){
305 pint = (int*)((uintptr)&c+itab[j].offset);
309 *pint = strtoul(val, 0, 0);
313 if(c.name==nil || c.value==nil || c.dom==nil || c.path==nil){
315 fprint(2, "ignoring fractional cookie %K\n", &c);
326 jar = emalloc9p(sizeof(Jar));
331 expirejar(Jar *jar, int exiting)
338 for(i=0; i<jar->nc; i++){
339 if(jar->c[i].expire < now || (exiting && jar->c[i].expire==~0)){
340 delcookie(jar, &jar->c[i]);
348 dumpjar(Jar *jar, char *desc)
355 print("\tin memory:\n");
357 for(i=0; i<jar->nc; i++)
358 print("\t%K%s%s%s\n", &jar->c[i],
359 jar->c[i].ondisk ? " ondisk" : "",
360 jar->c[i].deleted ? " deleted" : "",
361 jar->c[i].mark ? " mark" : "");
362 print("\n\ton disk:\n");
363 if((b = Bopen(jar->file, OREAD)) == nil){
364 print("\tno file\n");
366 while((s = Brdstr(b, '\n', 1)) != nil){
387 memset(&q, 0, sizeof q);
388 if((d = dirstat(jar->file)) != nil){
390 if(d->qid.path != jar->qid.path || d->qid.vers != jar->qid.vers)
400 if((fd = create(jar->lockfile, OWRITE, DMEXCL|0666)) < 0){
408 fprint(2, "open %s: %r", jar->lockfile);
409 werrstr("cannot acquire jar lock: %r");
413 for(i=0; i<jar->nc; i++) /* mark is cleared by addcookie */
414 jar->c[i].mark = jar->c[i].ondisk;
416 if((b = Bopen(jar->file, OREAD)) == nil){
418 fprint(2, "Bopen %s: %r", jar->file);
419 werrstr("cannot read cookie file %s: %r", jar->file);
423 for(; (line = Brdstr(b, '\n', 1)) != nil; free(line)){
426 addtojar(jar, line, 1);
430 for(i=0; i<jar->nc; i++)
431 if(jar->c[i].mark && jar->c[i].expire != ~0)
432 delcookie(jar, &jar->c[i]);
436 b = Bopen(jar->file, OWRITE);
439 fprint(2, "Bopen write %s: %r", jar->file);
443 Bprint(b, "# webcookies cookie jar\n");
444 Bprint(b, "# comments and non-standard fields will be lost\n");
445 for(i=0; i<jar->nc; i++){
446 if(jar->c[i].expire == ~0)
448 Bprint(b, "%K\n", &jar->c[i]);
449 jar->c[i].ondisk = 1;
455 if((d = dirstat(jar->file)) != nil){
469 lock = emalloc9p(strlen(file)+10);
471 if((p = strrchr(lock, '/')) != nil)
475 memmove(p+2, p, strlen(p)+1);
478 jar->lockfile = lock;
482 if(syncjar(jar) < 0){
500 fprint(2, "warning: cannot rewrite cookie jar: %r\n");
502 for(i=0; i<jar->nc; i++)
503 freecookie(&jar->c[i]);
510 * Domain name matching is per RFC2109, section 2:
512 * Hosts names can be specified either as an IP address or a FQHN
513 * string. Sometimes we compare one host name with another. Host A's
514 * name domain-matches host B's if
516 * * both host names are IP addresses and their host name strings match
519 * * both host names are FQDN strings and their host name strings match
522 * * A is a FQDN string and has the form NB, where N is a non-empty name
523 * string, B has the form .B', and B' is a FQDN string. (So, x.y.com
524 * domain-matches .y.com but not y.com.)
526 * Note that domain-match is not a commutative operation: a.b.c.com
527 * domain-matches .c.com, but not the reverse.
529 * (This does not verify that IP addresses and FQDN's are well-formed.)
532 isdomainmatch(char *name, char *pattern)
536 if(cistrcmp(name, pattern)==0)
539 if(strcmp(ipattr(name), "dom")==0 && pattern[0]=='.'){
540 lname = strlen(name);
541 lpattern = strlen(pattern);
542 /* e.g., name: www.google.com && pattern: .google.com */
543 if(lname >= lpattern && cistrcmp(name+lname-lpattern, pattern)==0)
545 /* e.g., name: google.com && pattern: .google.com */
546 if(lpattern > lname &&
547 cistrcmp(pattern+lpattern-lname, name) == 0)
555 * - domain must match
556 * - path in cookie must be a prefix of request path
557 * - cookie must not have expired
560 iscookiematch(Cookie *c, char *dom, char *path, uint now)
562 return isdomainmatch(dom, c->dom)
563 && strncmp(c->path, path, strlen(c->path))==0
564 && (c->expire == 0 || c->expire >= now);
568 * Produce a subjar of matching cookies.
569 * Secure cookies are only included if secure is set.
572 cookiesearch(Jar *jar, char *dom, char *path, int issecure)
579 fprint(2, "cookiesearch %s %s %d\n", dom, path, issecure);
582 for(i=0; i<jar->nc; i++){
584 fprint(2, "\ttry %s %s %d %s\n", jar->c[i].dom,
585 jar->c[i].path, jar->c[i].secure,
587 if((issecure || !jar->c[i].secure) &&
588 iscookiematch(&jar->c[i], dom, path, now)){
590 fprint(2, "\tmatched\n");
591 addcookie(j, &jar->c[i]);
596 werrstr("no cookies found");
599 qsort(j->c, j->nc, sizeof(j->c[0]), (int(*)(void*, void*))cookiecmp);
604 * RFC2109 4.3.2 security checks
607 isbadcookie(Cookie *c, char *dom, char *path)
611 if(strncmp(c->path, path, strlen(c->path)) != 0)
612 return "cookie path is not a prefix of the request path";
615 * fgb says omitting this test is necessary to get some sites to work,
616 * but it seems dubious.
618 if(c->explicitdom && c->dom[0] != '.')
619 return "cookie domain doesn't start with dot";
621 lcdom = strlen(c->dom);
622 if(memchr(c->dom+1, '.', lcdom-1-1) == nil)
623 return "cookie domain doesn't have embedded dots";
625 if(!isdomainmatch(dom, c->dom))
626 return "request host does not match cookie domain";
629 if(strcmp(ipattr(dom), "dom")==0 && lcdom > ldom &&
630 memchr(dom, '.', lcdom - ldom) != nil)
631 return "request host contains dots before cookie domain";
637 * Sunday, 25-Jan-2002 12:24:36 GMT
638 * Sunday, 25 Jan 2002 12:24:36 GMT
639 * Sun, 25 Jan 02 12:24:36 GMT
644 return year%4==0 && (year%100!=0 || year%400==0);
654 static int mday[2][12] = {
655 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
656 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
658 static char *wday[] = {
659 "Sunday", "Monday", "Tuesday", "Wednesday",
660 "Thursday", "Friday", "Saturday",
662 static char *mon[] = {
663 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
664 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
669 for(i=0; i<nelem(wday); i++){
670 if(cistrncmp(s, wday[i], strlen(wday[i])) == 0){
671 s += strlen(wday[i]);
674 if(cistrncmp(s, wday[i], 3) == 0){
681 fprint(2, "bad wday (%s)\n", os);
684 if(*s++ != ',' || *s++ != ' '){
686 fprint(2, "bad wday separator (%s)\n", os);
691 if(!isdigit(s[0]) || !isdigit(s[1]) || (s[2]!='-' && s[2]!=' ')){
693 fprint(2, "bad day of month (%s)\n", os);
696 tm.mday = strtol(s, 0, 10);
700 for(i=0; i<nelem(mon); i++)
701 if(cistrncmp(s, mon[i], 3) == 0){
708 fprint(2, "bad month (%s)\n", os);
711 if(s[0] != '-' && s[0] != ' '){
713 fprint(2, "bad month separator (%s)\n", os);
719 if(!isdigit(s[0]) || !isdigit(s[1])){
721 fprint(2, "bad year (%s)\n", os);
724 tm.year = strtol(s, 0, 10);
726 if(isdigit(s[0]) && isdigit(s[1]))
734 if(tm.mday==0 || tm.mday > mday[isleap(tm.year)][tm.mon]){
736 fprint(2, "invalid day of month (%s)\n", os);
742 fprint(2, "bad year separator (%s)\n", os);
746 if(!isdigit(s[0]) || !isdigit(s[1]) || s[2]!=':'
747 || !isdigit(s[3]) || !isdigit(s[4]) || s[5]!=':'
748 || !isdigit(s[6]) || !isdigit(s[7]) || s[8]!=' '){
750 fprint(2, "bad time (%s)\n", os);
757 if(tm.hour >= 24 || tm.min >= 60 || tm.sec >= 60){
759 fprint(2, "invalid time (%s)\n", os);
764 if(cistrcmp(s, "GMT") != 0){
766 fprint(2, "time zone not GMT (%s)\n", os);
769 strcpy(tm.zone, "GMT");
775 * skip linear whitespace. we're a bit more lenient than RFC2616 2.2.
780 while(*s=='\r' || *s=='\n' || *s==' ' || *s=='\t')
786 * Try to identify old netscape headers.
788 * - didn't allow spaces around the '='
789 * - used an 'Expires' attribute
790 * - had no 'Version' attribute
792 * - allowed whitespace in values
793 * - apparently separated attr/value pairs with ';' exclusively
796 isnetscape(char *hdr)
800 for(s=hdr; (s=strchr(s, '=')) != nil; s++){
801 if(isspace(s[1]) || (s > hdr && isspace(s[-1])))
806 if(cistrstr(hdr, "version="))
812 * Parse HTTP response headers, adding cookies to jar.
813 * Overwrites the headers. May overwrite path.
815 static char* parsecookie(Cookie*, char*, char**, int, char*, char*);
817 parsehttp(Jar *jar, char *hdr, char *dom, char *path)
819 static char setcookie[] = "Set-Cookie:";
824 isns = isnetscape(hdr);
826 for(p=hdr; p; p=nextp){
830 nextp = strchr(p, '\n');
833 if(cistrncmp(p, setcookie, strlen(setcookie)) != 0)
836 fprint(2, "%s\n", p);
837 p = skipspace(p+strlen(setcookie));
838 for(; *p; p=skipspace(p)){
839 if((e = parsecookie(&c, p, &p, isns, dom, path)) != nil){
841 fprint(2, "parse cookie: %s\n", e);
844 if((e = isbadcookie(&c, dom, path)) != nil){
846 fprint(2, "reject cookie; %s\n", e);
860 * Sec 2.2 of RFC2616 defines a "quoted-string" as:
862 * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
863 * qdtext = <any TEXT except <">>
864 * quoted-pair = "\" CHAR
866 * TEXT is any octet except CTLs, but including LWS;
867 * LWS is [CR LF] 1*(SP | HT);
868 * CHARs are ASCII octets 0-127; (NOTE: we reject 0's)
869 * CTLs are octets 0-31 and 127;
874 for(s++; 32 <= *s && *s < 127 && *s != '"'; s++)
875 if(*s == '\\' && *(s+1) != '\0')
884 * Sec 2.2 of RFC2616 defines a "token" as
885 * 1*<any CHAR except CTLs or separators>;
886 * CHARs are ASCII octets 0-127;
887 * CTLs are octets 0-31 and 127;
888 * separators are "()<>@,;:\/[]?={}", double-quote, SP (32), and HT (9)
890 while(32 <= *s && *s < 127 && strchr("()<>@,;:[]?={}\" \t\\", *s)==nil)
897 skipvalue(char *s, int isns)
902 * An RFC2109 value is an HTTP token or an HTTP quoted string.
903 * Netscape servers ignore the spec and rely on semicolons, apparently.
906 if((t = strchr(s, ';')) == nil)
911 return skipquoted(s);
916 * RMID=80b186bb64c03c65fab767f8; expires=Monday, 10-Feb-2003 04:44:39 GMT;
917 * path=/; domain=.nytimes.com
920 parsecookie(Cookie *c, char *p, char **e, int isns, char *dom, char *path)
923 char *t, *u, *attr, *val;
926 memset(c, 0, sizeof *c);
934 return "malformed cookie: no NAME=VALUE";
938 t = skipvalue(p, isns);
943 if(c->name[0]=='\0' || c->value[0]=='\0')
947 for(; *p && !done; p=skipspace(p)){
963 val = skipspace(u+1);
964 p = skipvalue(val, isns);
980 fprint(2, "syntax: %s\n", p);
981 return "syntax error";
983 for(i=0; i<nelem(stab); i++)
984 if(stab[i].ishttp && cistrcmp(stab[i].s, attr)==0)
985 *(char**)((uintptr)c+stab[i].offset) = val;
986 if(cistrcmp(attr, "expires") == 0){
988 return "non-netscape cookie has Expires tag";
990 return "bad expires tag";
991 c->expire = strtotime(val);
993 return "cannot parse netscape expires tag";
995 if(cistrcmp(attr, "max-age") == 0)
996 c->expire = time(0)+atoi(val);
997 if(cistrcmp(attr, "secure") == 0)
1006 c->explicitpath = 1;
1009 if((t = strchr(c->path, '?')) != 0)
1011 if((t = strrchr(c->path, '/')) != 0)
1014 c->netscapestyle = isns;
1022 typedef struct Aux Aux;
1035 MaxCtext = 16*1024*1024,
1046 a = emalloc9p(sizeof(Aux));
1048 if(r->ifcall.mode&OTRUNC){
1049 a->ctext = emalloc9p(1);
1052 sz = 256*jar->nc+1024; /* BUG should do better */
1053 a->ctext = emalloc9p(sz);
1057 for(i=0; i<jar->nc; i++)
1058 s = seprint(s, es, "%K\n", &jar->c[i]);
1069 readstr(r, a->ctext);
1080 sz = r->ifcall.count+r->ifcall.offset;
1081 if(sz > strlen(a->ctext)){
1083 respond(r, "cookie file too large");
1086 a->ctext = erealloc9p(a->ctext, sz+1);
1087 a->ctext[sz] = '\0';
1089 memmove(a->ctext+r->ifcall.offset, r->ifcall.data, r->ifcall.count);
1090 r->ofcall.count = r->ifcall.count;
1095 cookieclunk(Fid *fid)
1104 for(i=0; i<jar->nc; i++)
1106 for(p=a->ctext; *p; p=nextp){
1107 if((nextp = strchr(p, '\n')) != nil)
1111 addtojar(jar, p, 0);
1113 for(i=0; i<jar->nc; i++)
1115 delcookie(jar, &jar->c[i]);
1132 initcookies(char *file)
1136 fmtinstall('J', jarfmt);
1137 fmtinstall('K', cookiefmt);
1140 home = getenv("home");
1142 sysfatal("no cookie file specified and no $home");
1143 file = emalloc9p(strlen(home)+30);
1145 strcat(file, "/lib/webcookies");
1147 jar = readjar(file);
1149 sysfatal("readjar: %r");
1153 httpsetcookie(char *hdr, char *dom, char *path)
1158 parsehttp(jar, hdr, dom, path);
1163 httpcookies(char *dom, char *path, int issecure)
1169 j = cookiesearch(jar, dom, path, issecure);
1170 snprint(buf, sizeof buf, "%J", j);
1172 return estrdup(buf);