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 + (pattern[0]=='.'))==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(strlen(c->dom)<=2 || memchr(c->dom+1, '.', strlen(c->dom)-2) == 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 && strlen(dom)>strlen(c->dom)
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[1024];
979 ddom[sizeof(ddom)-1] = '\0';
980 strncpy(ddom+1, c->dom, sizeof(ddom)-2);
989 static char dpath[1024];
991 /* implicit path is "directory" of request-uri's path component */
992 dpath[sizeof(dpath)-1] = '\0';
993 strncpy(dpath, path, sizeof(dpath)-1);
994 if((t = strrchr(dpath, '/')) != nil)
998 c->netscapestyle = isns;
1014 typedef struct Aux Aux;
1028 MaxCtext = 16*1024*1024,
1038 switch((uintptr)r->fid->file->aux){
1041 a = emalloc9p(sizeof(Aux));
1043 a->inhttp = emalloc9p(AuxBuf);
1044 a->outhttp = emalloc9p(AuxBuf);
1049 a = emalloc9p(sizeof(Aux));
1051 if(r->ifcall.mode&OTRUNC){
1052 a->ctext = emalloc9p(1);
1055 sz = 256*jar->nc+1024; /* BUG should do better */
1056 a->ctext = emalloc9p(sz);
1060 for(i=0; i<jar->nc; i++)
1061 s = seprint(s, es, "%K\n", &jar->c[i]);
1074 switch((uintptr)r->fid->file->aux){
1076 if(a->state == NeedUrl){
1077 respond(r, "must write url before read");
1080 r->ifcall.offset = a->rdoff;
1081 readstr(r, a->outhttp);
1082 a->rdoff += r->ofcall.count;
1087 readstr(r, a->ctext);
1092 respond(r, "bug in webcookies");
1101 int i, sz, hlen, issecure;
1106 switch((uintptr)r->fid->file->aux){
1108 if(a->state == NeedUrl){
1109 if(r->ifcall.count >= sizeof buf){
1110 respond(r, "url too long");
1113 memmove(buf, r->ifcall.data, r->ifcall.count);
1114 buf[r->ifcall.count] = '\0';
1116 if(cistrncmp(buf, "http://", 7) == 0)
1118 else if(cistrncmp(buf, "https://", 8) == 0){
1122 respond(r, "url must begin http:// or https://");
1126 respond(r, "url without host name");
1129 p = strchr(buf+hlen, '/');
1131 a->path = estrdup9p("/");
1133 a->path = estrdup9p(p);
1136 if((p = strchr(a->path, '#')) != nil)
1138 if((p = strchr(a->path, '?')) != nil)
1141 a->dom = estrdup9p(buf+hlen);
1143 j = cookiesearch(jar, a->dom, a->path, issecure);
1145 fprint(2, "search %s %s got %p\n", a->dom, a->path, j);
1147 fprint(2, "%d cookies\n", j->nc);
1148 for(i=0; i<j->nc; i++)
1149 fprint(2, "%K\n", &j->c[i]);
1152 snprint(a->outhttp, AuxBuf, "%J", j);
1156 if(strlen(a->inhttp)+r->ifcall.count >= AuxBuf){
1157 respond(r, "http headers too large");
1160 memmove(a->inhttp+strlen(a->inhttp), r->ifcall.data, r->ifcall.count);
1162 r->ofcall.count = r->ifcall.count;
1167 sz = r->ifcall.count+r->ifcall.offset;
1168 if(sz > strlen(a->ctext)){
1170 respond(r, "cookie file too large");
1173 a->ctext = erealloc9p(a->ctext, sz+1);
1174 a->ctext[sz] = '\0';
1176 memmove(a->ctext+r->ifcall.offset, r->ifcall.data, r->ifcall.count);
1177 r->ofcall.count = r->ifcall.count;
1182 respond(r, "bug in webcookies");
1188 fsdestroyfid(Fid *fid)
1197 switch((uintptr)fid->file->aux){
1199 parsehttp(jar, a->inhttp, a->dom, a->path);
1202 for(i=0; i<jar->nc; i++)
1204 for(p=a->ctext; *p; p=nextp){
1205 if((nextp = strchr(p, '\n')) != nil)
1209 addtojar(jar, p, 0);
1211 for(i=0; i<jar->nc; i++)
1213 delcookie(jar, &jar->c[i]);
1237 .destroyfid= fsdestroyfid,
1244 fprint(2, "usage: webcookies [-f file] [-m mtpt] [-s service]\n");
1249 main(int argc, char **argv)
1251 char *file, *mtpt, *home, *srv;
1256 mtpt = "/mnt/webcookies";
1265 file = EARGF(usage());
1268 srv = EARGF(usage());
1271 mtpt = EARGF(usage());
1281 fmtinstall('J', jarfmt);
1282 fmtinstall('K', cookiefmt);
1285 home = getenv("home");
1287 sysfatal("no cookie file specified and no $home");
1288 file = emalloc9p(strlen(home)+30);
1290 strcat(file, "/lib/webcookies");
1292 if(access(file, AEXIST) < 0){
1293 if((fd = create(file, OWRITE, 0600)) < 0)
1294 sysfatal("create %s: %r", file);
1298 jar = readjar(file);
1300 sysfatal("readjar: %r");
1302 fs.tree = alloctree("cookie", "cookie", DMDIR|0555, nil);
1303 closefile(createfile(fs.tree->root, "http", "cookie", 0666, (void*)Xhttp));
1304 closefile(createfile(fs.tree->root, "cookies", "cookie", 0666, (void*)Xcookies));
1306 postmountsrv(&fs, srv, mtpt, MREPL);