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]);
352 int i, fd, doread, dowrite;
362 dowrite = jar->dirty;
365 if((d = dirstat(jar->file)) == nil)
368 if(q.path != d->qid.path || q.vers != d->qid.vers){
375 if(!doread && !dowrite)
380 if((fd = create(jar->lockfile, OWRITE, DMEXCL|0600)) < 0){
388 fprint(2, "open %s: %r", jar->lockfile);
389 werrstr("cannot acquire jar lock: %r");
394 for(i=0; i<jar->nc; i++) /* mark is cleared by addcookie */
395 jar->c[i].mark = jar->c[i].ondisk;
397 if((b = Bopen(jar->file, OREAD)) == nil){
399 fprint(2, "Bopen %s: %r", jar->file);
400 werrstr("cannot read cookie file %s: %r", jar->file);
404 for(; (line = Brdstr(b, '\n', 1)) != nil; free(line)){
407 addtojar(jar, line, 1);
411 for(i=0; i<jar->nc; i++)
413 delcookie(jar, &jar->c[i]);
419 i = create(jar->file, OWRITE, 0600);
420 if(i < 0 || (b = Bfdopen(i, OWRITE)) == nil){
422 fprint(2, "Bopen write %s: %r", jar->file);
428 Bprint(b, "# webcookies cookie jar\n");
429 Bprint(b, "# comments and non-standard fields will be lost\n");
430 for(i=0; i<jar->nc; i++){
431 if(jar->c[i].expire == ~0)
433 Bprint(b, "%K\n", &jar->c[i]);
434 jar->c[i].ondisk = 1;
437 if((d = dirfstat(Bfildes(b))) != nil){
461 fprint(2, "warning: cannot rewrite cookie jar: %r\n");
463 for(i=0; i<jar->nc; i++)
464 freecookie(&jar->c[i]);
479 file = estrdup9p(file);
480 lock = emalloc9p(strlen(file)+10);
482 if((p = strrchr(lock, '/')) != nil)
486 memmove(p+2, p, strlen(p)+1);
489 jar->lockfile = lock;
493 if(syncjar(jar) < 0){
502 * Domain name matching is per RFC2109, section 2:
504 * Hosts names can be specified either as an IP address or a FQHN
505 * string. Sometimes we compare one host name with another. Host A's
506 * name domain-matches host B's if
508 * * both host names are IP addresses and their host name strings match
511 * * both host names are FQDN strings and their host name strings match
514 * * A is a FQDN string and has the form NB, where N is a non-empty name
515 * string, B has the form .B', and B' is a FQDN string. (So, x.y.com
516 * domain-matches .y.com but not y.com.)
518 * Note that domain-match is not a commutative operation: a.b.c.com
519 * domain-matches .c.com, but not the reverse.
521 * (This does not verify that IP addresses and FQDN's are well-formed.)
524 isdomainmatch(char *name, char *pattern)
528 if(cistrcmp(name, pattern + (pattern[0]=='.'))==0)
531 if(strcmp(ipattr(name), "dom")==0 && pattern[0]=='.'){
532 lname = strlen(name);
533 lpattern = strlen(pattern);
534 if(lname >= lpattern && cistrcmp(name+lname-lpattern, pattern)==0)
543 * - domain must match
544 * - path in cookie must be a prefix of request path
545 * - cookie must not have expired
548 iscookiematch(Cookie *c, char *dom, char *path, uint now)
550 return isdomainmatch(dom, c->dom)
551 && strncmp(c->path, path, strlen(c->path))==0
556 * Produce a subjar of matching cookies.
557 * Secure cookies are only included if secure is set.
560 cookiesearch(Jar *jar, char *dom, char *path, int issecure)
569 for(i=0; i<jar->nc; i++){
571 if(!c->deleted && (issecure || !c->secure) && iscookiematch(c, dom, path, now))
576 werrstr("no cookies found");
579 qsort(j->c, j->nc, sizeof(j->c[0]), (int(*)(const void*, const void*))cookiecmp);
584 * RFC2109 4.3.2 security checks
587 isbadcookie(Cookie *c, char *dom, char *path)
589 if(strncmp(c->path, path, strlen(c->path)) != 0)
590 return "cookie path is not a prefix of the request path";
592 if(c->explicitdom && c->dom[0] != '.')
593 return "cookie domain doesn't start with dot";
595 if(strlen(c->dom)<=2 || memchr(c->dom+1, '.', strlen(c->dom)-2) == nil)
596 return "cookie domain doesn't have embedded dots";
598 if(!isdomainmatch(dom, c->dom))
599 return "request host does not match cookie domain";
601 if(strcmp(ipattr(dom), "dom")==0 && strlen(dom)>strlen(c->dom)
602 && memchr(dom, '.', strlen(dom)-strlen(c->dom)) != nil)
603 return "request host contains dots before cookie domain";
609 * Parse a date in one of these formats:
610 * Sunday, 25-Jan-2002 12:24:36 GMT
611 * Sunday, 25 Jan 2002 12:24:36 GMT
612 * Sun, 25 Jan 02 12:24:36 GMT
617 char **f, *fmts[] = {
618 "?WW, ?DD-?MM-?YYYY hh:mm:ss ?Z",
619 "?WW, ?DD ?MM ?YYYY hh:mm:ss ?Z",
624 for(f = fmts; *f != nil; f++)
625 if(tmparse(&tm, *f, s, nil, nil) != nil)
631 * skip linear whitespace. we're a bit more lenient than RFC2616 2.2.
636 while(*s=='\r' || *s=='\n' || *s==' ' || *s=='\t')
642 * Try to identify old netscape headers.
644 * - didn't allow spaces around the '='
645 * - used an 'Expires' attribute
646 * - had no 'Version' attribute
648 * - allowed whitespace in values
649 * - apparently separated attr/value pairs with ';' exclusively
652 isnetscape(char *hdr)
656 for(s=hdr; (s=strchr(s, '=')) != nil; s++){
657 if(isspace(s[1]) || (s > hdr && isspace(s[-1])))
662 if(cistrstr(hdr, "version="))
668 * Parse HTTP response headers, adding cookies to jar.
669 * Overwrites the headers. May overwrite path.
671 char* parsecookie(Cookie*, char*, char**, int, char*, char*);
673 parsehttp(Jar *jar, char *hdr, char *dom, char *path)
675 static char setcookie[] = "Set-Cookie:";
680 isns = isnetscape(hdr);
682 for(p=hdr; p; p=nextp){
686 nextp = strchr(p, '\n');
690 fprint(2, "?%s\n", p);
691 if(cistrncmp(p, setcookie, strlen(setcookie)) != 0)
694 fprint(2, "%s\n", p);
695 p = skipspace(p+strlen(setcookie));
696 for(; *p; p=skipspace(p)){
697 if((e = parsecookie(&c, p, &p, isns, dom, path)) != nil){
699 fprint(2, "parse cookie: %s\n", e);
702 if((e = isbadcookie(&c, dom, path)) != nil){
704 fprint(2, "reject cookie; %s\n", e);
718 * Sec 2.2 of RFC2616 defines a "quoted-string" as:
720 * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
721 * qdtext = <any TEXT except <">>
722 * quoted-pair = "\" CHAR
724 * TEXT is any octet except CTLs, but including LWS;
725 * LWS is [CR LF] 1*(SP | HT);
726 * CHARs are ASCII octets 0-127; (NOTE: we reject 0's)
727 * CTLs are octets 0-31 and 127;
732 for(s++; 32 <= *s && *s < 127 && *s != '"'; s++)
733 if(*s == '\\' && *(s+1) != '\0')
742 * Sec 2.2 of RFC2616 defines a "token" as
743 * 1*<any CHAR except CTLs or separators>;
744 * CHARs are ASCII octets 0-127;
745 * CTLs are octets 0-31 and 127;
746 * separators are "()<>@,;:\/[]?={}", double-quote, SP (32), and HT (9)
748 while(32 <= *s && *s < 127 && strchr("()<>@,;:[]?={}\" \t\\", *s)==nil)
755 skipvalue(char *s, int isns)
760 * An RFC2109 value is an HTTP token or an HTTP quoted string.
761 * Netscape servers ignore the spec and rely on semicolons, apparently.
764 if((t = strchr(s, ';')) == nil)
769 return skipquoted(s);
774 * RMID=80b186bb64c03c65fab767f8; expires=Monday, 10-Feb-2003 04:44:39 GMT;
775 * path=/; domain=.nytimes.com
778 parsecookie(Cookie *c, char *p, char **e, int isns, char *dom, char *path)
781 char *t, *u, *attr, *val;
783 memset(c, 0, sizeof *c);
792 return "malformed cookie: no NAME=VALUE";
796 t = skipvalue(p, isns);
801 if(c->name[0]=='\0' || c->value[0]=='\0')
805 for(; *p && !done; p=skipspace(p)){
821 val = skipspace(u+1);
822 p = skipvalue(val, isns);
838 fprint(2, "syntax: %s\n", p);
839 return "syntax error";
841 for(i=0; i<nelem(stab); i++)
842 if(stab[i].ishttp && cistrcmp(stab[i].s, attr)==0)
843 *(char**)((char*)c+stab[i].offset) = val;
844 if(cistrcmp(attr, "expires") == 0){
846 return "non-netscape cookie has Expires tag";
848 return "bad expires tag";
849 c->expire = strtotime(val);
851 return "cannot parse netscape expires tag";
853 if(cistrcmp(attr, "max-age") == 0)
854 c->expire = time(0)+atoi(val);
855 if(cistrcmp(attr, "secure") == 0)
861 /* add leading dot for explicit domain */
862 if(c->dom[0] != '.' && strcmp(ipattr(c->dom), "dom") == 0){
863 static char ddom[1024];
866 ddom[sizeof(ddom)-1] = '\0';
867 strncpy(ddom+1, c->dom, sizeof(ddom)-2);
876 static char dpath[1024];
878 /* implicit path is "directory" of request-uri's path component */
879 dpath[sizeof(dpath)-1] = '\0';
880 strncpy(dpath, path, sizeof(dpath)-1);
881 if((t = strrchr(dpath, '/')) != nil)
885 c->netscapestyle = isns;
901 typedef struct Aux Aux;
915 MaxCtext = 16*1024*1024,
925 switch((uintptr)r->fid->file->aux){
928 a = emalloc9p(sizeof(Aux));
930 a->inhttp = emalloc9p(AuxBuf);
931 a->outhttp = emalloc9p(AuxBuf);
936 a = emalloc9p(sizeof(Aux));
938 if(r->ifcall.mode&OTRUNC){
939 a->ctext = emalloc9p(1);
942 sz = 256*jar->nc+1024; /* BUG should do better */
943 a->ctext = emalloc9p(sz);
947 for(i=0; i<jar->nc; i++)
948 s = seprint(s, es, "%K\n", &jar->c[i]);
961 switch((uintptr)r->fid->file->aux){
963 if(a->state == NeedUrl){
964 respond(r, "must write url before read");
967 r->ifcall.offset = a->rdoff;
968 readstr(r, a->outhttp);
969 a->rdoff += r->ofcall.count;
974 readstr(r, a->ctext);
979 respond(r, "bug in webcookies");
988 int i, sz, hlen, issecure;
993 switch((uintptr)r->fid->file->aux){
995 if(a->state == NeedUrl){
996 if(r->ifcall.count >= sizeof buf){
997 respond(r, "url too long");
1000 memmove(buf, r->ifcall.data, r->ifcall.count);
1001 buf[r->ifcall.count] = '\0';
1003 if(cistrncmp(buf, "http://", 7) == 0)
1005 else if(cistrncmp(buf, "https://", 8) == 0){
1009 respond(r, "url must begin http:// or https://");
1013 respond(r, "url without host name");
1016 p = strchr(buf+hlen, '/');
1018 a->path = estrdup9p("/");
1020 a->path = estrdup9p(p);
1023 if((p = strchr(a->path, '#')) != nil)
1025 if((p = strchr(a->path, '?')) != nil)
1028 a->dom = estrdup9p(buf+hlen);
1030 j = cookiesearch(jar, a->dom, a->path, issecure);
1032 fprint(2, "search %s %s got %p\n", a->dom, a->path, j);
1034 fprint(2, "%d cookies\n", j->nc);
1035 for(i=0; i<j->nc; i++)
1036 fprint(2, "%K\n", &j->c[i]);
1039 snprint(a->outhttp, AuxBuf, "%J", j);
1042 if(strlen(a->inhttp)+r->ifcall.count >= AuxBuf){
1043 respond(r, "http headers too large");
1046 memmove(a->inhttp+strlen(a->inhttp), r->ifcall.data, r->ifcall.count);
1048 r->ofcall.count = r->ifcall.count;
1053 sz = r->ifcall.count+r->ifcall.offset;
1054 if(sz > strlen(a->ctext)){
1056 respond(r, "cookie file too large");
1059 a->ctext = erealloc9p(a->ctext, sz+1);
1060 a->ctext[sz] = '\0';
1062 memmove(a->ctext+r->ifcall.offset, r->ifcall.data, r->ifcall.count);
1063 r->ofcall.count = r->ifcall.count;
1068 respond(r, "bug in webcookies");
1074 fsdestroyfid(Fid *fid)
1083 switch((uintptr)fid->file->aux){
1085 parsehttp(jar, a->inhttp, a->dom, a->path);
1088 for(i=0; i<jar->nc; i++)
1090 for(p=a->ctext; *p; p=nextp){
1091 if((nextp = strchr(p, '\n')) != nil)
1095 addtojar(jar, p, 0);
1097 for(i=0; i<jar->nc; i++)
1099 delcookie(jar, &jar->c[i]);
1123 .destroyfid= fsdestroyfid,
1130 fprint(2, "usage: webcookies [-f file] [-m mtpt] [-s service]\n");
1135 main(int argc, char **argv)
1137 char *file, *mtpt, *home, *srv;
1141 mtpt = "/mnt/webcookies";
1150 file = EARGF(usage());
1153 srv = EARGF(usage());
1156 mtpt = EARGF(usage());
1166 fmtinstall('J', jarfmt);
1167 fmtinstall('K', cookiefmt);
1170 home = getenv("home");
1172 sysfatal("no cookie file specified and no $home");
1173 file = emalloc9p(strlen(home)+30);
1175 strcat(file, "/lib/webcookies");
1178 jar = readjar(file);
1180 sysfatal("readjar: %r");
1182 fs.tree = alloctree("cookie", "cookie", DMDIR|0555, nil);
1183 closefile(createfile(fs.tree->root, "http", "cookie", 0666, (void*)Xhttp));
1184 closefile(createfile(fs.tree->root, "cookies", "cookie", 0666, (void*)Xcookies));
1186 postmountsrv(&fs, srv, mtpt, MREPL);