2 * Cookie file system. Allows hget and multiple webfs's to collaborate.
3 * Conventionally mounted on /mnt/webcookies.
17 typedef struct Cookie Cookie;
18 typedef struct Jar Jar;
25 char* dom; /* starts with . */
28 char* comment; /* optional, may be nil */
30 uint expire; /* time of expiration: ~0 means when webcookies dies */
32 int explicitdom; /* dom was explicitly set */
33 int explicitpath; /* path was explicitly set */
59 "domain", offsetof(Cookie, dom), 1,
60 "path", offsetof(Cookie, path), 1,
61 "name", offsetof(Cookie, name), 0,
62 "value", offsetof(Cookie, value), 0,
63 "comment", offsetof(Cookie, comment), 1,
64 "version", offsetof(Cookie, version), 1,
71 "expire", offsetof(Cookie, expire),
72 "secure", offsetof(Cookie, secure),
73 "explicitdomain", offsetof(Cookie, explicitdom),
74 "explicitpath", offsetof(Cookie, explicitpath),
75 "netscapestyle", offsetof(Cookie, netscapestyle),
78 #pragma varargck type "J" Jar*
79 #pragma varargck type "K" Cookie*
88 jar = va_arg(fmt->args, Jar*);
89 if(jar == nil || jar->nc == 0)
90 return fmtstrcpy(fmt, "");
92 fmtprint(fmt, "Cookie: ");
94 fmtprint(fmt, "$Version=%s; ", jar->c[0].version);
95 for(i=0; i<jar->nc; i++)
96 fmtprint(fmt, "%s%s=%s", i ? "; ":"", jar->c[i].name, jar->c[i].value);
97 fmtprint(fmt, "\r\n");
101 /* individual cookie */
109 c = va_arg(fmt->args, Cookie*);
112 for(j=0; j<nelem(stab); j++){
113 t = *(char**)((char*)c+stab[j].offset);
120 fmtprint(fmt, "%s=%q", stab[j].s, t);
122 for(j=0; j<nelem(itab); j++){
123 k = *(int*)((char*)c+itab[j].offset);
130 fmtprint(fmt, "%s=%ud", itab[j].s, k);
139 * - longer paths first, then alpha by path (RFC2109 4.3.4)
142 cookiecmp(Cookie *a, Cookie *b)
146 if((i = strcmp(a->name, b->name)) != 0)
148 if((i = cistrcmp(a->dom, b->dom)) != 0)
150 if((i = strlen(b->path) - strlen(a->path)) != 0)
152 if((i = strcmp(a->path, b->path)) != 0)
158 exactcookiecmp(Cookie *a, Cookie *b)
162 if((i = cookiecmp(a, b)) != 0)
164 if((i = strcmp(a->value, b->value)) != 0)
166 if(a->version || b->version){
171 if((i = strcmp(a->version, b->version)) != 0)
174 if(a->comment || b->comment){
179 if((i = strcmp(a->comment, b->comment)) != 0)
182 if((i = b->expire - a->expire) != 0)
184 if((i = b->secure - a->secure) != 0)
186 if((i = b->explicitdom - a->explicitdom) != 0)
188 if((i = b->explicitpath - a->explicitpath) != 0)
190 if((i = b->netscapestyle - a->netscapestyle) != 0)
197 freecookie(Cookie *c)
201 for(i=0; i<nelem(stab); i++)
202 free(*(char**)((char*)c+stab[i].offset));
206 copycookie(Cookie *c)
211 for(i=0; i<nelem(stab); i++){
212 ps = (char**)((char*)c+stab[i].offset);
214 *ps = estrdup9p(*ps);
219 delcookie(Jar *j, Cookie *c)
225 if(i < 0 || i >= j->nc)
231 addcookie(Jar *j, Cookie *c)
235 if(!c->name || !c->value || !c->path || !c->dom){
236 fprint(2, "not adding incomplete cookie\n");
241 fprint(2, "add %K\n", c);
243 for(i=0; i<j->nc; i++)
244 if(cookiecmp(&j->c[i], c) == 0){
246 fprint(2, "cookie %K matches %K\n", &j->c[i], c);
247 if(exactcookiecmp(&j->c[i], c) == 0){
249 fprint(2, "\texactly\n");
253 delcookie(j, &j->c[i]);
259 j->c = erealloc9p(j->c, j->mc*sizeof(Cookie));
262 copycookie(&j->c[j->nc]);
271 for(i=j->nc-1; i>=0; i--){
274 freecookie(&j->c[i]);
276 j->c[i] = j->c[j->nc];
281 addtojar(Jar *jar, char *line, int ondisk)
285 char *f[20], *attr, *val, **pstr;
287 memset(&c, 0, sizeof c);
290 nf = tokenize(line, f, nelem(f));
293 if((val = strchr(attr, '=')) != nil)
297 /* string attributes */
298 for(j=0; j<nelem(stab); j++){
299 if(strcmp(stab[j].s, attr) == 0){
300 pstr = (char**)((char*)&c+stab[j].offset);
304 /* integer attributes */
305 for(j=0; j<nelem(itab); j++){
306 if(strcmp(itab[j].s, attr) == 0){
307 pint = (int*)((char*)&c+itab[j].offset);
311 *pint = strtoul(val, 0, 0);
315 if(c.name==nil || c.value==nil || c.dom==nil || c.path==nil){
317 fprint(2, "ignoring fractional cookie %K\n", &c);
328 jar = emalloc9p(sizeof(Jar));
333 expirejar(Jar *jar, int exiting)
340 for(i=0; i<jar->nc; i++){
341 if(jar->c[i].expire < now || (exiting && jar->c[i].expire==~0)){
342 delcookie(jar, &jar->c[i]);
361 memset(&q, 0, sizeof q);
362 if((d = dirstat(jar->file)) != nil){
364 if(d->qid.path != jar->qid.path || d->qid.vers != jar->qid.vers)
374 if((fd = create(jar->lockfile, OWRITE, DMEXCL|0666)) < 0){
382 fprint(2, "open %s: %r", jar->lockfile);
383 werrstr("cannot acquire jar lock: %r");
387 for(i=0; i<jar->nc; i++) /* mark is cleared by addcookie */
388 jar->c[i].mark = jar->c[i].ondisk;
390 if((b = Bopen(jar->file, OREAD)) == nil){
392 fprint(2, "Bopen %s: %r", jar->file);
393 werrstr("cannot read cookie file %s: %r", jar->file);
397 for(; (line = Brdstr(b, '\n', 1)) != nil; free(line)){
400 addtojar(jar, line, 1);
404 for(i=0; i<jar->nc; i++)
406 delcookie(jar, &jar->c[i]);
410 b = Bopen(jar->file, OTRUNC|OWRITE);
413 fprint(2, "Bopen write %s: %r", jar->file);
417 Bprint(b, "# webcookies cookie jar\n");
418 Bprint(b, "# comments and non-standard fields will be lost\n");
419 for(i=0; i<jar->nc; i++){
420 if(jar->c[i].expire == ~0)
422 Bprint(b, "%K\n", &jar->c[i]);
423 jar->c[i].ondisk = 1;
429 if((d = dirstat(jar->file)) != nil){
443 lock = emalloc9p(strlen(file)+10);
445 if((p = strrchr(lock, '/')) != nil)
449 memmove(p+2, p, strlen(p)+1);
452 jar->lockfile = lock;
456 if(syncjar(jar) < 0){
474 fprint(2, "warning: cannot rewrite cookie jar: %r\n");
476 for(i=0; i<jar->nc; i++)
477 freecookie(&jar->c[i]);
485 * Domain name matching is per RFC2109, section 2:
487 * Hosts names can be specified either as an IP address or a FQHN
488 * string. Sometimes we compare one host name with another. Host A's
489 * name domain-matches host B's if
491 * * both host names are IP addresses and their host name strings match
494 * * both host names are FQDN strings and their host name strings match
497 * * A is a FQDN string and has the form NB, where N is a non-empty name
498 * string, B has the form .B', and B' is a FQDN string. (So, x.y.com
499 * domain-matches .y.com but not y.com.)
501 * Note that domain-match is not a commutative operation: a.b.c.com
502 * domain-matches .c.com, but not the reverse.
504 * (This does not verify that IP addresses and FQDN's are well-formed.)
507 isdomainmatch(char *name, char *pattern)
511 if(cistrcmp(name, pattern)==0)
514 if(strcmp(ipattr(name), "dom")==0 && pattern[0]=='.'){
515 lname = strlen(name);
516 lpattern = strlen(pattern);
517 if(lname >= lpattern && cistrcmp(name+lname-lpattern, pattern)==0)
526 * - domain must match
527 * - path in cookie must be a prefix of request path
528 * - cookie must not have expired
531 iscookiematch(Cookie *c, char *dom, char *path, uint now)
533 return isdomainmatch(dom, c->dom)
534 && strncmp(c->path, path, strlen(c->path))==0
539 * Produce a subjar of matching cookies.
540 * Secure cookies are only included if secure is set.
543 cookiesearch(Jar *jar, char *dom, char *path, int issecure)
551 for(i=0; i<jar->nc; i++)
552 if((issecure || !jar->c[i].secure) && iscookiematch(&jar->c[i], dom, path, now))
553 addcookie(j, &jar->c[i]);
556 werrstr("no cookies found");
559 qsort(j->c, j->nc, sizeof(j->c[0]), (int(*)(const void*, const void*))cookiecmp);
564 * RFC2109 4.3.2 security checks
567 isbadcookie(Cookie *c, char *dom, char *path)
569 if(strncmp(c->path, path, strlen(c->path)) != 0)
570 return "cookie path is not a prefix of the request path";
572 if(c->explicitdom && c->dom[0] != '.')
573 return "cookie domain doesn't start with dot";
575 if(memchr(c->dom+1, '.', strlen(c->dom)-1-1) == nil)
576 return "cookie domain doesn't have embedded dots";
578 if(!isdomainmatch(dom, c->dom))
579 return "request host does not match cookie domain";
581 if(strcmp(ipattr(dom), "dom")==0
582 && memchr(dom, '.', strlen(dom)-strlen(c->dom)) != nil)
583 return "request host contains dots before cookie domain";
589 * Sunday, 25-Jan-2002 12:24:36 GMT
590 * Sunday, 25 Jan 2002 12:24:36 GMT
591 * Sun, 25 Jan 02 12:24:36 GMT
596 return year%4==0 && (year%100!=0 || year%400==0);
606 static int mday[2][12] = {
607 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
608 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
610 static char *wday[] = {
611 "Sunday", "Monday", "Tuesday", "Wednesday",
612 "Thursday", "Friday", "Saturday",
614 static char *mon[] = {
615 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
616 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
621 for(i=0; i<nelem(wday); i++){
622 if(cistrncmp(s, wday[i], strlen(wday[i])) == 0){
623 s += strlen(wday[i]);
626 if(cistrncmp(s, wday[i], 3) == 0){
633 fprint(2, "bad wday (%s)\n", os);
636 if(*s++ != ',' || *s++ != ' '){
638 fprint(2, "bad wday separator (%s)\n", os);
643 if(!isdigit(s[0]) || !isdigit(s[1]) || (s[2]!='-' && s[2]!=' ')){
645 fprint(2, "bad day of month (%s)\n", os);
648 tm.mday = strtol(s, 0, 10);
652 for(i=0; i<nelem(mon); i++)
653 if(cistrncmp(s, mon[i], 3) == 0){
660 fprint(2, "bad month (%s)\n", os);
663 if(s[0] != '-' && s[0] != ' '){
665 fprint(2, "bad month separator (%s)\n", os);
671 if(!isdigit(s[0]) || !isdigit(s[1])){
673 fprint(2, "bad year (%s)\n", os);
676 tm.year = strtol(s, 0, 10);
678 if(isdigit(s[0]) && isdigit(s[1]))
686 if(tm.mday==0 || tm.mday > mday[isleap(tm.year)][tm.mon]){
688 fprint(2, "invalid day of month (%s)\n", os);
694 fprint(2, "bad year separator (%s)\n", os);
698 if(!isdigit(s[0]) || !isdigit(s[1]) || s[2]!=':'
699 || !isdigit(s[3]) || !isdigit(s[4]) || s[5]!=':'
700 || !isdigit(s[6]) || !isdigit(s[7]) || s[8]!=' '){
702 fprint(2, "bad time (%s)\n", os);
709 if(tm.hour >= 24 || tm.min >= 60 || tm.sec >= 60){
711 fprint(2, "invalid time (%s)\n", os);
716 if(cistrcmp(s, "GMT") != 0){
718 fprint(2, "time zone not GMT (%s)\n", os);
721 strcpy(tm.zone, "GMT");
727 * skip linear whitespace. we're a bit more lenient than RFC2616 2.2.
732 while(*s=='\r' || *s=='\n' || *s==' ' || *s=='\t')
738 * Try to identify old netscape headers.
740 * - didn't allow spaces around the '='
741 * - used an 'Expires' attribute
742 * - had no 'Version' attribute
744 * - allowed whitespace in values
745 * - apparently separated attr/value pairs with ';' exclusively
748 isnetscape(char *hdr)
752 for(s=hdr; (s=strchr(s, '=')) != nil; s++){
753 if(isspace(s[1]) || (s > hdr && isspace(s[-1])))
758 if(cistrstr(hdr, "version="))
764 * Parse HTTP response headers, adding cookies to jar.
765 * Overwrites the headers. May overwrite path.
767 char* parsecookie(Cookie*, char*, char**, int, char*, char*);
769 parsehttp(Jar *jar, char *hdr, char *dom, char *path)
771 static char setcookie[] = "Set-Cookie:";
776 isns = isnetscape(hdr);
778 for(p=hdr; p; p=nextp){
782 nextp = strchr(p, '\n');
786 fprint(2, "?%s\n", p);
787 if(cistrncmp(p, setcookie, strlen(setcookie)) != 0)
790 fprint(2, "%s\n", p);
791 p = skipspace(p+strlen(setcookie));
792 for(; *p; p=skipspace(p)){
793 if((e = parsecookie(&c, p, &p, isns, dom, path)) != nil){
795 fprint(2, "parse cookie: %s\n", e);
798 if((e = isbadcookie(&c, dom, path)) != nil){
800 fprint(2, "reject cookie; %s\n", e);
814 * Sec 2.2 of RFC2616 defines a "quoted-string" as:
816 * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
817 * qdtext = <any TEXT except <">>
818 * quoted-pair = "\" CHAR
820 * TEXT is any octet except CTLs, but including LWS;
821 * LWS is [CR LF] 1*(SP | HT);
822 * CHARs are ASCII octets 0-127; (NOTE: we reject 0's)
823 * CTLs are octets 0-31 and 127;
828 for(s++; 32 <= *s && *s < 127 && *s != '"'; s++)
829 if(*s == '\\' && *(s+1) != '\0')
838 * Sec 2.2 of RFC2616 defines a "token" as
839 * 1*<any CHAR except CTLs or separators>;
840 * CHARs are ASCII octets 0-127;
841 * CTLs are octets 0-31 and 127;
842 * separators are "()<>@,;:\/[]?={}", double-quote, SP (32), and HT (9)
844 while(32 <= *s && *s < 127 && strchr("()<>@,;:[]?={}\" \t\\", *s)==nil)
851 skipvalue(char *s, int isns)
856 * An RFC2109 value is an HTTP token or an HTTP quoted string.
857 * Netscape servers ignore the spec and rely on semicolons, apparently.
860 if((t = strchr(s, ';')) == nil)
865 return skipquoted(s);
870 * RMID=80b186bb64c03c65fab767f8; expires=Monday, 10-Feb-2003 04:44:39 GMT;
871 * path=/; domain=.nytimes.com
874 parsecookie(Cookie *c, char *p, char **e, int isns, char *dom, char *path)
877 char *t, *u, *attr, *val;
879 memset(c, 0, sizeof *c);
888 return "malformed cookie: no NAME=VALUE";
892 t = skipvalue(p, isns);
897 if(c->name[0]=='\0' || c->value[0]=='\0')
901 for(; *p && !done; p=skipspace(p)){
917 val = skipspace(u+1);
918 p = skipvalue(val, isns);
934 fprint(2, "syntax: %s\n", p);
935 return "syntax error";
937 for(i=0; i<nelem(stab); i++)
938 if(stab[i].ishttp && cistrcmp(stab[i].s, attr)==0)
939 *(char**)((char*)c+stab[i].offset) = val;
940 if(cistrcmp(attr, "expires") == 0){
942 return "non-netscape cookie has Expires tag";
944 return "bad expires tag";
945 c->expire = strtotime(val);
947 return "cannot parse netscape expires tag";
949 if(cistrcmp(attr, "max-age") == 0)
950 c->expire = time(0)+atoi(val);
951 if(cistrcmp(attr, "secure") == 0)
964 if((t = strchr(c->path, '#')) != 0)
966 if((t = strchr(c->path, '?')) != 0)
968 if((t = strrchr(c->path, '/')) != 0)
971 c->netscapestyle = isns;
987 typedef struct Aux Aux;
1001 MaxCtext = 16*1024*1024,
1011 switch((uintptr)r->fid->file->aux){
1014 a = emalloc9p(sizeof(Aux));
1016 a->inhttp = emalloc9p(AuxBuf);
1017 a->outhttp = emalloc9p(AuxBuf);
1022 a = emalloc9p(sizeof(Aux));
1024 if(r->ifcall.mode&OTRUNC){
1025 a->ctext = emalloc9p(1);
1028 sz = 256*jar->nc+1024; /* BUG should do better */
1029 a->ctext = emalloc9p(sz);
1033 for(i=0; i<jar->nc; i++)
1034 s = seprint(s, es, "%K\n", &jar->c[i]);
1047 switch((uintptr)r->fid->file->aux){
1049 if(a->state == NeedUrl){
1050 respond(r, "must write url before read");
1053 r->ifcall.offset = a->rdoff;
1054 readstr(r, a->outhttp);
1055 a->rdoff += r->ofcall.count;
1060 readstr(r, a->ctext);
1065 respond(r, "bug in webcookies");
1074 int i, sz, hlen, issecure;
1079 switch((uintptr)r->fid->file->aux){
1081 if(a->state == NeedUrl){
1082 if(r->ifcall.count >= sizeof buf){
1083 respond(r, "url too long");
1086 memmove(buf, r->ifcall.data, r->ifcall.count);
1087 buf[r->ifcall.count] = '\0';
1089 if(cistrncmp(buf, "http://", 7) == 0)
1091 else if(cistrncmp(buf, "https://", 8) == 0){
1095 respond(r, "url must begin http:// or https://");
1099 respond(r, "url without host name");
1102 p = strchr(buf+hlen, '/');
1104 a->path = estrdup9p("/");
1106 a->path = estrdup9p(p);
1109 a->dom = estrdup9p(buf+hlen);
1111 j = cookiesearch(jar, a->dom, a->path, issecure);
1113 fprint(2, "search %s %s got %p\n", a->dom, a->path, j);
1115 fprint(2, "%d cookies\n", j->nc);
1116 for(i=0; i<j->nc; i++)
1117 fprint(2, "%K\n", &j->c[i]);
1120 snprint(a->outhttp, AuxBuf, "%J", j);
1124 if(strlen(a->inhttp)+r->ifcall.count >= AuxBuf){
1125 respond(r, "http headers too large");
1128 memmove(a->inhttp+strlen(a->inhttp), r->ifcall.data, r->ifcall.count);
1130 r->ofcall.count = r->ifcall.count;
1135 sz = r->ifcall.count+r->ifcall.offset;
1136 if(sz > strlen(a->ctext)){
1138 respond(r, "cookie file too large");
1141 a->ctext = erealloc9p(a->ctext, sz+1);
1142 a->ctext[sz] = '\0';
1144 memmove(a->ctext+r->ifcall.offset, r->ifcall.data, r->ifcall.count);
1145 r->ofcall.count = r->ifcall.count;
1150 respond(r, "bug in webcookies");
1156 fsdestroyfid(Fid *fid)
1165 switch((uintptr)fid->file->aux){
1167 parsehttp(jar, a->inhttp, a->dom, a->path);
1170 for(i=0; i<jar->nc; i++)
1172 for(p=a->ctext; *p; p=nextp){
1173 if((nextp = strchr(p, '\n')) != nil)
1177 addtojar(jar, p, 0);
1179 for(i=0; i<jar->nc; i++)
1181 delcookie(jar, &jar->c[i]);
1204 .destroyfid= fsdestroyfid,
1211 fprint(2, "usage: webcookies [-f file] [-m mtpt] [-s service]\n");
1216 main(int argc, char **argv)
1218 char *file, *mtpt, *home, *srv;
1222 mtpt = "/mnt/webcookies";
1231 file = EARGF(usage());
1234 srv = EARGF(usage());
1237 mtpt = EARGF(usage());
1247 fmtinstall('J', jarfmt);
1248 fmtinstall('K', cookiefmt);
1251 home = getenv("home");
1253 sysfatal("no cookie file specified and no $home");
1254 file = emalloc9p(strlen(home)+30);
1256 strcat(file, "/lib/webcookies");
1258 if(access(file, AEXIST) < 0)
1259 close(create(file, OWRITE, 0666));
1261 jar = readjar(file);
1263 sysfatal("readjar: %r");
1265 fs.tree = alloctree("cookie", "cookie", DMDIR|0555, nil);
1266 closefile(createfile(fs.tree->root, "http", "cookie", 0666, (void*)Xhttp));
1267 closefile(createfile(fs.tree->root, "cookies", "cookie", 0666, (void*)Xcookies));
1269 postmountsrv(&fs, srv, mtpt, MREPL);