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|0666)) < 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 b = Bopen(jar->file, OTRUNC|OWRITE);
422 fprint(2, "Bopen write %s: %r", jar->file);
426 Bprint(b, "# webcookies cookie jar\n");
427 Bprint(b, "# comments and non-standard fields will be lost\n");
428 for(i=0; i<jar->nc; i++){
429 if(jar->c[i].expire == ~0)
431 Bprint(b, "%K\n", &jar->c[i]);
432 jar->c[i].ondisk = 1;
435 if((d = dirfstat(Bfildes(b))) != nil){
456 lock = emalloc9p(strlen(file)+10);
458 if((p = strrchr(lock, '/')) != nil)
462 memmove(p+2, p, strlen(p)+1);
465 jar->lockfile = lock;
469 if(syncjar(jar) < 0){
488 fprint(2, "warning: cannot rewrite cookie jar: %r\n");
490 for(i=0; i<jar->nc; i++)
491 freecookie(&jar->c[i]);
499 * Domain name matching is per RFC2109, section 2:
501 * Hosts names can be specified either as an IP address or a FQHN
502 * string. Sometimes we compare one host name with another. Host A's
503 * name domain-matches host B's if
505 * * both host names are IP addresses and their host name strings match
508 * * both host names are FQDN strings and their host name strings match
511 * * A is a FQDN string and has the form NB, where N is a non-empty name
512 * string, B has the form .B', and B' is a FQDN string. (So, x.y.com
513 * domain-matches .y.com but not y.com.)
515 * Note that domain-match is not a commutative operation: a.b.c.com
516 * domain-matches .c.com, but not the reverse.
518 * (This does not verify that IP addresses and FQDN's are well-formed.)
521 isdomainmatch(char *name, char *pattern)
525 if(cistrcmp(name, pattern)==0)
528 if(strcmp(ipattr(name), "dom")==0 && pattern[0]=='.'){
529 lname = strlen(name);
530 lpattern = strlen(pattern);
531 if(lname >= lpattern && cistrcmp(name+lname-lpattern, pattern)==0)
540 * - domain must match
541 * - path in cookie must be a prefix of request path
542 * - cookie must not have expired
545 iscookiematch(Cookie *c, char *dom, char *path, uint now)
547 return isdomainmatch(dom, c->dom)
548 && strncmp(c->path, path, strlen(c->path))==0
553 * Produce a subjar of matching cookies.
554 * Secure cookies are only included if secure is set.
557 cookiesearch(Jar *jar, char *dom, char *path, int issecure)
566 for(i=0; i<jar->nc; i++){
568 if(!c->deleted && (issecure || !c->secure) && iscookiematch(c, dom, path, now))
573 werrstr("no cookies found");
576 qsort(j->c, j->nc, sizeof(j->c[0]), (int(*)(const void*, const void*))cookiecmp);
581 * RFC2109 4.3.2 security checks
584 isbadcookie(Cookie *c, char *dom, char *path)
586 if(strncmp(c->path, path, strlen(c->path)) != 0)
587 return "cookie path is not a prefix of the request path";
589 if(c->explicitdom && c->dom[0] != '.')
590 return "cookie domain doesn't start with dot";
592 if(memchr(c->dom+1, '.', strlen(c->dom)-1-1) == nil)
593 return "cookie domain doesn't have embedded dots";
595 if(!isdomainmatch(dom, c->dom))
596 return "request host does not match cookie domain";
598 if(strcmp(ipattr(dom), "dom")==0
599 && memchr(dom, '.', strlen(dom)-strlen(c->dom)) != nil)
600 return "request host contains dots before cookie domain";
606 * Sunday, 25-Jan-2002 12:24:36 GMT
607 * Sunday, 25 Jan 2002 12:24:36 GMT
608 * Sun, 25 Jan 02 12:24:36 GMT
613 return year%4==0 && (year%100!=0 || year%400==0);
623 static int mday[2][12] = {
624 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
625 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
627 static char *wday[] = {
628 "Sunday", "Monday", "Tuesday", "Wednesday",
629 "Thursday", "Friday", "Saturday",
631 static char *mon[] = {
632 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
633 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
638 for(i=0; i<nelem(wday); i++){
639 if(cistrncmp(s, wday[i], strlen(wday[i])) == 0){
640 s += strlen(wday[i]);
643 if(cistrncmp(s, wday[i], 3) == 0){
650 fprint(2, "bad wday (%s)\n", os);
653 if(*s++ != ',' || *s++ != ' '){
655 fprint(2, "bad wday separator (%s)\n", os);
660 if(!isdigit(s[0]) || !isdigit(s[1]) || (s[2]!='-' && s[2]!=' ')){
662 fprint(2, "bad day of month (%s)\n", os);
665 tm.mday = strtol(s, 0, 10);
669 for(i=0; i<nelem(mon); i++)
670 if(cistrncmp(s, mon[i], 3) == 0){
677 fprint(2, "bad month (%s)\n", os);
680 if(s[0] != '-' && s[0] != ' '){
682 fprint(2, "bad month separator (%s)\n", os);
688 if(!isdigit(s[0]) || !isdigit(s[1])){
690 fprint(2, "bad year (%s)\n", os);
693 tm.year = strtol(s, 0, 10);
695 if(isdigit(s[0]) && isdigit(s[1]))
703 if(tm.mday==0 || tm.mday > mday[isleap(tm.year)][tm.mon]){
705 fprint(2, "invalid day of month (%s)\n", os);
711 fprint(2, "bad year separator (%s)\n", os);
715 if(!isdigit(s[0]) || !isdigit(s[1]) || s[2]!=':'
716 || !isdigit(s[3]) || !isdigit(s[4]) || s[5]!=':'
717 || !isdigit(s[6]) || !isdigit(s[7]) || s[8]!=' '){
719 fprint(2, "bad time (%s)\n", os);
726 if(tm.hour >= 24 || tm.min >= 60 || tm.sec >= 60){
728 fprint(2, "invalid time (%s)\n", os);
733 if(cistrcmp(s, "GMT") != 0){
735 fprint(2, "time zone not GMT (%s)\n", os);
738 strcpy(tm.zone, "GMT");
744 * skip linear whitespace. we're a bit more lenient than RFC2616 2.2.
749 while(*s=='\r' || *s=='\n' || *s==' ' || *s=='\t')
755 * Try to identify old netscape headers.
757 * - didn't allow spaces around the '='
758 * - used an 'Expires' attribute
759 * - had no 'Version' attribute
761 * - allowed whitespace in values
762 * - apparently separated attr/value pairs with ';' exclusively
765 isnetscape(char *hdr)
769 for(s=hdr; (s=strchr(s, '=')) != nil; s++){
770 if(isspace(s[1]) || (s > hdr && isspace(s[-1])))
775 if(cistrstr(hdr, "version="))
781 * Parse HTTP response headers, adding cookies to jar.
782 * Overwrites the headers. May overwrite path.
784 char* parsecookie(Cookie*, char*, char**, int, char*, char*);
786 parsehttp(Jar *jar, char *hdr, char *dom, char *path)
788 static char setcookie[] = "Set-Cookie:";
793 isns = isnetscape(hdr);
795 for(p=hdr; p; p=nextp){
799 nextp = strchr(p, '\n');
803 fprint(2, "?%s\n", p);
804 if(cistrncmp(p, setcookie, strlen(setcookie)) != 0)
807 fprint(2, "%s\n", p);
808 p = skipspace(p+strlen(setcookie));
809 for(; *p; p=skipspace(p)){
810 if((e = parsecookie(&c, p, &p, isns, dom, path)) != nil){
812 fprint(2, "parse cookie: %s\n", e);
815 if((e = isbadcookie(&c, dom, path)) != nil){
817 fprint(2, "reject cookie; %s\n", e);
831 * Sec 2.2 of RFC2616 defines a "quoted-string" as:
833 * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
834 * qdtext = <any TEXT except <">>
835 * quoted-pair = "\" CHAR
837 * TEXT is any octet except CTLs, but including LWS;
838 * LWS is [CR LF] 1*(SP | HT);
839 * CHARs are ASCII octets 0-127; (NOTE: we reject 0's)
840 * CTLs are octets 0-31 and 127;
845 for(s++; 32 <= *s && *s < 127 && *s != '"'; s++)
846 if(*s == '\\' && *(s+1) != '\0')
855 * Sec 2.2 of RFC2616 defines a "token" as
856 * 1*<any CHAR except CTLs or separators>;
857 * CHARs are ASCII octets 0-127;
858 * CTLs are octets 0-31 and 127;
859 * separators are "()<>@,;:\/[]?={}", double-quote, SP (32), and HT (9)
861 while(32 <= *s && *s < 127 && strchr("()<>@,;:[]?={}\" \t\\", *s)==nil)
868 skipvalue(char *s, int isns)
873 * An RFC2109 value is an HTTP token or an HTTP quoted string.
874 * Netscape servers ignore the spec and rely on semicolons, apparently.
877 if((t = strchr(s, ';')) == nil)
882 return skipquoted(s);
887 * RMID=80b186bb64c03c65fab767f8; expires=Monday, 10-Feb-2003 04:44:39 GMT;
888 * path=/; domain=.nytimes.com
891 parsecookie(Cookie *c, char *p, char **e, int isns, char *dom, char *path)
894 char *t, *u, *attr, *val;
896 memset(c, 0, sizeof *c);
905 return "malformed cookie: no NAME=VALUE";
909 t = skipvalue(p, isns);
914 if(c->name[0]=='\0' || c->value[0]=='\0')
918 for(; *p && !done; p=skipspace(p)){
934 val = skipspace(u+1);
935 p = skipvalue(val, isns);
951 fprint(2, "syntax: %s\n", p);
952 return "syntax error";
954 for(i=0; i<nelem(stab); i++)
955 if(stab[i].ishttp && cistrcmp(stab[i].s, attr)==0)
956 *(char**)((char*)c+stab[i].offset) = val;
957 if(cistrcmp(attr, "expires") == 0){
959 return "non-netscape cookie has Expires tag";
961 return "bad expires tag";
962 c->expire = strtotime(val);
964 return "cannot parse netscape expires tag";
966 if(cistrcmp(attr, "max-age") == 0)
967 c->expire = time(0)+atoi(val);
968 if(cistrcmp(attr, "secure") == 0)
974 /* add leading dot for explicit domain */
975 if(c->dom[0] != '.' && strcmp(ipattr(c->dom), "dom") == 0){
976 static char *ddom = nil;
978 ddom = realloc(ddom, strlen(c->dom)+2);
981 strcpy(ddom+1, c->dom);
992 if((t = strchr(c->path, '#')) != 0)
994 if((t = strchr(c->path, '?')) != 0)
996 if((t = strrchr(c->path, '/')) != 0)
999 c->netscapestyle = isns;
1015 typedef struct Aux Aux;
1029 MaxCtext = 16*1024*1024,
1039 switch((uintptr)r->fid->file->aux){
1042 a = emalloc9p(sizeof(Aux));
1044 a->inhttp = emalloc9p(AuxBuf);
1045 a->outhttp = emalloc9p(AuxBuf);
1050 a = emalloc9p(sizeof(Aux));
1052 if(r->ifcall.mode&OTRUNC){
1053 a->ctext = emalloc9p(1);
1056 sz = 256*jar->nc+1024; /* BUG should do better */
1057 a->ctext = emalloc9p(sz);
1061 for(i=0; i<jar->nc; i++)
1062 s = seprint(s, es, "%K\n", &jar->c[i]);
1075 switch((uintptr)r->fid->file->aux){
1077 if(a->state == NeedUrl){
1078 respond(r, "must write url before read");
1081 r->ifcall.offset = a->rdoff;
1082 readstr(r, a->outhttp);
1083 a->rdoff += r->ofcall.count;
1088 readstr(r, a->ctext);
1093 respond(r, "bug in webcookies");
1102 int i, sz, hlen, issecure;
1107 switch((uintptr)r->fid->file->aux){
1109 if(a->state == NeedUrl){
1110 if(r->ifcall.count >= sizeof buf){
1111 respond(r, "url too long");
1114 memmove(buf, r->ifcall.data, r->ifcall.count);
1115 buf[r->ifcall.count] = '\0';
1117 if(cistrncmp(buf, "http://", 7) == 0)
1119 else if(cistrncmp(buf, "https://", 8) == 0){
1123 respond(r, "url must begin http:// or https://");
1127 respond(r, "url without host name");
1130 p = strchr(buf+hlen, '/');
1132 a->path = estrdup9p("/");
1134 a->path = estrdup9p(p);
1137 a->dom = estrdup9p(buf+hlen);
1139 j = cookiesearch(jar, a->dom, a->path, issecure);
1141 fprint(2, "search %s %s got %p\n", a->dom, a->path, j);
1143 fprint(2, "%d cookies\n", j->nc);
1144 for(i=0; i<j->nc; i++)
1145 fprint(2, "%K\n", &j->c[i]);
1148 snprint(a->outhttp, AuxBuf, "%J", j);
1152 if(strlen(a->inhttp)+r->ifcall.count >= AuxBuf){
1153 respond(r, "http headers too large");
1156 memmove(a->inhttp+strlen(a->inhttp), r->ifcall.data, r->ifcall.count);
1158 r->ofcall.count = r->ifcall.count;
1163 sz = r->ifcall.count+r->ifcall.offset;
1164 if(sz > strlen(a->ctext)){
1166 respond(r, "cookie file too large");
1169 a->ctext = erealloc9p(a->ctext, sz+1);
1170 a->ctext[sz] = '\0';
1172 memmove(a->ctext+r->ifcall.offset, r->ifcall.data, r->ifcall.count);
1173 r->ofcall.count = r->ifcall.count;
1178 respond(r, "bug in webcookies");
1184 fsdestroyfid(Fid *fid)
1193 switch((uintptr)fid->file->aux){
1195 parsehttp(jar, a->inhttp, a->dom, a->path);
1198 for(i=0; i<jar->nc; i++)
1200 for(p=a->ctext; *p; p=nextp){
1201 if((nextp = strchr(p, '\n')) != nil)
1205 addtojar(jar, p, 0);
1207 for(i=0; i<jar->nc; i++)
1209 delcookie(jar, &jar->c[i]);
1233 .destroyfid= fsdestroyfid,
1240 fprint(2, "usage: webcookies [-f file] [-m mtpt] [-s service]\n");
1245 main(int argc, char **argv)
1247 char *file, *mtpt, *home, *srv;
1252 mtpt = "/mnt/webcookies";
1261 file = EARGF(usage());
1264 srv = EARGF(usage());
1267 mtpt = EARGF(usage());
1277 fmtinstall('J', jarfmt);
1278 fmtinstall('K', cookiefmt);
1281 home = getenv("home");
1283 sysfatal("no cookie file specified and no $home");
1284 file = emalloc9p(strlen(home)+30);
1286 strcat(file, "/lib/webcookies");
1288 if(access(file, AEXIST) < 0){
1289 if((fd = create(file, OWRITE, 0600)) < 0)
1290 sysfatal("create %s: %r", file);
1294 jar = readjar(file);
1296 sysfatal("readjar: %r");
1298 fs.tree = alloctree("cookie", "cookie", DMDIR|0555, nil);
1299 closefile(createfile(fs.tree->root, "http", "cookie", 0666, (void*)Xhttp));
1300 closefile(createfile(fs.tree->root, "cookies", "cookie", 0666, (void*)Xcookies));
1302 postmountsrv(&fs, srv, mtpt, MREPL);