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){
458 lock = emalloc9p(strlen(file)+10);
460 if((p = strrchr(lock, '/')) != nil)
464 memmove(p+2, p, strlen(p)+1);
467 jar->lockfile = lock;
471 if(syncjar(jar) < 0){
490 fprint(2, "warning: cannot rewrite cookie jar: %r\n");
492 for(i=0; i<jar->nc; i++)
493 freecookie(&jar->c[i]);
501 * Domain name matching is per RFC2109, section 2:
503 * Hosts names can be specified either as an IP address or a FQHN
504 * string. Sometimes we compare one host name with another. Host A's
505 * name domain-matches host B's if
507 * * both host names are IP addresses and their host name strings match
510 * * both host names are FQDN strings and their host name strings match
513 * * A is a FQDN string and has the form NB, where N is a non-empty name
514 * string, B has the form .B', and B' is a FQDN string. (So, x.y.com
515 * domain-matches .y.com but not y.com.)
517 * Note that domain-match is not a commutative operation: a.b.c.com
518 * domain-matches .c.com, but not the reverse.
520 * (This does not verify that IP addresses and FQDN's are well-formed.)
523 isdomainmatch(char *name, char *pattern)
527 if(cistrcmp(name, pattern + (pattern[0]=='.'))==0)
530 if(strcmp(ipattr(name), "dom")==0 && pattern[0]=='.'){
531 lname = strlen(name);
532 lpattern = strlen(pattern);
533 if(lname >= lpattern && cistrcmp(name+lname-lpattern, pattern)==0)
542 * - domain must match
543 * - path in cookie must be a prefix of request path
544 * - cookie must not have expired
547 iscookiematch(Cookie *c, char *dom, char *path, uint now)
549 return isdomainmatch(dom, c->dom)
550 && strncmp(c->path, path, strlen(c->path))==0
555 * Produce a subjar of matching cookies.
556 * Secure cookies are only included if secure is set.
559 cookiesearch(Jar *jar, char *dom, char *path, int issecure)
568 for(i=0; i<jar->nc; i++){
570 if(!c->deleted && (issecure || !c->secure) && iscookiematch(c, dom, path, now))
575 werrstr("no cookies found");
578 qsort(j->c, j->nc, sizeof(j->c[0]), (int(*)(const void*, const void*))cookiecmp);
583 * RFC2109 4.3.2 security checks
586 isbadcookie(Cookie *c, char *dom, char *path)
588 if(strncmp(c->path, path, strlen(c->path)) != 0)
589 return "cookie path is not a prefix of the request path";
591 if(c->explicitdom && c->dom[0] != '.')
592 return "cookie domain doesn't start with dot";
594 if(strlen(c->dom)<=2 || memchr(c->dom+1, '.', strlen(c->dom)-2) == nil)
595 return "cookie domain doesn't have embedded dots";
597 if(!isdomainmatch(dom, c->dom))
598 return "request host does not match cookie domain";
600 if(strcmp(ipattr(dom), "dom")==0 && strlen(dom)>strlen(c->dom)
601 && memchr(dom, '.', strlen(dom)-strlen(c->dom)) != nil)
602 return "request host contains dots before cookie domain";
608 * Sunday, 25-Jan-2002 12:24:36 GMT
609 * Sunday, 25 Jan 2002 12:24:36 GMT
610 * Sun, 25 Jan 02 12:24:36 GMT
615 return year%4==0 && (year%100!=0 || year%400==0);
625 static int mday[2][12] = {
626 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
627 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
629 static char *wday[] = {
630 "Sunday", "Monday", "Tuesday", "Wednesday",
631 "Thursday", "Friday", "Saturday",
633 static char *mon[] = {
634 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
635 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
640 for(i=0; i<nelem(wday); i++){
641 if(cistrncmp(s, wday[i], strlen(wday[i])) == 0){
642 s += strlen(wday[i]);
645 if(cistrncmp(s, wday[i], 3) == 0){
652 fprint(2, "bad wday (%s)\n", os);
655 if(*s++ != ',' || *s++ != ' '){
657 fprint(2, "bad wday separator (%s)\n", os);
662 if(!isdigit(s[0]) || !isdigit(s[1]) || (s[2]!='-' && s[2]!=' ')){
664 fprint(2, "bad day of month (%s)\n", os);
667 tm.mday = strtol(s, 0, 10);
671 for(i=0; i<nelem(mon); i++)
672 if(cistrncmp(s, mon[i], 3) == 0){
679 fprint(2, "bad month (%s)\n", os);
682 if(s[0] != '-' && s[0] != ' '){
684 fprint(2, "bad month separator (%s)\n", os);
690 if(!isdigit(s[0]) || !isdigit(s[1])){
692 fprint(2, "bad year (%s)\n", os);
695 tm.year = strtol(s, 0, 10);
697 if(isdigit(s[0]) && isdigit(s[1]))
705 if(tm.mday==0 || tm.mday > mday[isleap(tm.year)][tm.mon]){
707 fprint(2, "invalid day of month (%s)\n", os);
713 fprint(2, "bad year separator (%s)\n", os);
717 if(!isdigit(s[0]) || !isdigit(s[1]) || s[2]!=':'
718 || !isdigit(s[3]) || !isdigit(s[4]) || s[5]!=':'
719 || !isdigit(s[6]) || !isdigit(s[7]) || s[8]!=' '){
721 fprint(2, "bad time (%s)\n", os);
728 if(tm.hour >= 24 || tm.min >= 60 || tm.sec >= 60){
730 fprint(2, "invalid time (%s)\n", os);
735 if(cistrcmp(s, "GMT") != 0){
737 fprint(2, "time zone not GMT (%s)\n", os);
740 strcpy(tm.zone, "GMT");
746 * skip linear whitespace. we're a bit more lenient than RFC2616 2.2.
751 while(*s=='\r' || *s=='\n' || *s==' ' || *s=='\t')
757 * Try to identify old netscape headers.
759 * - didn't allow spaces around the '='
760 * - used an 'Expires' attribute
761 * - had no 'Version' attribute
763 * - allowed whitespace in values
764 * - apparently separated attr/value pairs with ';' exclusively
767 isnetscape(char *hdr)
771 for(s=hdr; (s=strchr(s, '=')) != nil; s++){
772 if(isspace(s[1]) || (s > hdr && isspace(s[-1])))
777 if(cistrstr(hdr, "version="))
783 * Parse HTTP response headers, adding cookies to jar.
784 * Overwrites the headers. May overwrite path.
786 char* parsecookie(Cookie*, char*, char**, int, char*, char*);
788 parsehttp(Jar *jar, char *hdr, char *dom, char *path)
790 static char setcookie[] = "Set-Cookie:";
795 isns = isnetscape(hdr);
797 for(p=hdr; p; p=nextp){
801 nextp = strchr(p, '\n');
805 fprint(2, "?%s\n", p);
806 if(cistrncmp(p, setcookie, strlen(setcookie)) != 0)
809 fprint(2, "%s\n", p);
810 p = skipspace(p+strlen(setcookie));
811 for(; *p; p=skipspace(p)){
812 if((e = parsecookie(&c, p, &p, isns, dom, path)) != nil){
814 fprint(2, "parse cookie: %s\n", e);
817 if((e = isbadcookie(&c, dom, path)) != nil){
819 fprint(2, "reject cookie; %s\n", e);
833 * Sec 2.2 of RFC2616 defines a "quoted-string" as:
835 * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
836 * qdtext = <any TEXT except <">>
837 * quoted-pair = "\" CHAR
839 * TEXT is any octet except CTLs, but including LWS;
840 * LWS is [CR LF] 1*(SP | HT);
841 * CHARs are ASCII octets 0-127; (NOTE: we reject 0's)
842 * CTLs are octets 0-31 and 127;
847 for(s++; 32 <= *s && *s < 127 && *s != '"'; s++)
848 if(*s == '\\' && *(s+1) != '\0')
857 * Sec 2.2 of RFC2616 defines a "token" as
858 * 1*<any CHAR except CTLs or separators>;
859 * CHARs are ASCII octets 0-127;
860 * CTLs are octets 0-31 and 127;
861 * separators are "()<>@,;:\/[]?={}", double-quote, SP (32), and HT (9)
863 while(32 <= *s && *s < 127 && strchr("()<>@,;:[]?={}\" \t\\", *s)==nil)
870 skipvalue(char *s, int isns)
875 * An RFC2109 value is an HTTP token or an HTTP quoted string.
876 * Netscape servers ignore the spec and rely on semicolons, apparently.
879 if((t = strchr(s, ';')) == nil)
884 return skipquoted(s);
889 * RMID=80b186bb64c03c65fab767f8; expires=Monday, 10-Feb-2003 04:44:39 GMT;
890 * path=/; domain=.nytimes.com
893 parsecookie(Cookie *c, char *p, char **e, int isns, char *dom, char *path)
896 char *t, *u, *attr, *val;
898 memset(c, 0, sizeof *c);
907 return "malformed cookie: no NAME=VALUE";
911 t = skipvalue(p, isns);
916 if(c->name[0]=='\0' || c->value[0]=='\0')
920 for(; *p && !done; p=skipspace(p)){
936 val = skipspace(u+1);
937 p = skipvalue(val, isns);
953 fprint(2, "syntax: %s\n", p);
954 return "syntax error";
956 for(i=0; i<nelem(stab); i++)
957 if(stab[i].ishttp && cistrcmp(stab[i].s, attr)==0)
958 *(char**)((char*)c+stab[i].offset) = val;
959 if(cistrcmp(attr, "expires") == 0){
961 return "non-netscape cookie has Expires tag";
963 return "bad expires tag";
964 c->expire = strtotime(val);
966 return "cannot parse netscape expires tag";
968 if(cistrcmp(attr, "max-age") == 0)
969 c->expire = time(0)+atoi(val);
970 if(cistrcmp(attr, "secure") == 0)
976 /* add leading dot for explicit domain */
977 if(c->dom[0] != '.' && strcmp(ipattr(c->dom), "dom") == 0){
978 static char ddom[1024];
981 ddom[sizeof(ddom)-1] = '\0';
982 strncpy(ddom+1, c->dom, sizeof(ddom)-2);
991 static char dpath[1024];
993 /* implicit path is "directory" of request-uri's path component */
994 dpath[sizeof(dpath)-1] = '\0';
995 strncpy(dpath, path, sizeof(dpath)-1);
996 if((t = strrchr(dpath, '/')) != nil)
1000 c->netscapestyle = isns;
1016 typedef struct Aux Aux;
1030 MaxCtext = 16*1024*1024,
1040 switch((uintptr)r->fid->file->aux){
1043 a = emalloc9p(sizeof(Aux));
1045 a->inhttp = emalloc9p(AuxBuf);
1046 a->outhttp = emalloc9p(AuxBuf);
1051 a = emalloc9p(sizeof(Aux));
1053 if(r->ifcall.mode&OTRUNC){
1054 a->ctext = emalloc9p(1);
1057 sz = 256*jar->nc+1024; /* BUG should do better */
1058 a->ctext = emalloc9p(sz);
1062 for(i=0; i<jar->nc; i++)
1063 s = seprint(s, es, "%K\n", &jar->c[i]);
1076 switch((uintptr)r->fid->file->aux){
1078 if(a->state == NeedUrl){
1079 respond(r, "must write url before read");
1082 r->ifcall.offset = a->rdoff;
1083 readstr(r, a->outhttp);
1084 a->rdoff += r->ofcall.count;
1089 readstr(r, a->ctext);
1094 respond(r, "bug in webcookies");
1103 int i, sz, hlen, issecure;
1108 switch((uintptr)r->fid->file->aux){
1110 if(a->state == NeedUrl){
1111 if(r->ifcall.count >= sizeof buf){
1112 respond(r, "url too long");
1115 memmove(buf, r->ifcall.data, r->ifcall.count);
1116 buf[r->ifcall.count] = '\0';
1118 if(cistrncmp(buf, "http://", 7) == 0)
1120 else if(cistrncmp(buf, "https://", 8) == 0){
1124 respond(r, "url must begin http:// or https://");
1128 respond(r, "url without host name");
1131 p = strchr(buf+hlen, '/');
1133 a->path = estrdup9p("/");
1135 a->path = estrdup9p(p);
1138 if((p = strchr(a->path, '#')) != nil)
1140 if((p = strchr(a->path, '?')) != nil)
1143 a->dom = estrdup9p(buf+hlen);
1145 j = cookiesearch(jar, a->dom, a->path, issecure);
1147 fprint(2, "search %s %s got %p\n", a->dom, a->path, j);
1149 fprint(2, "%d cookies\n", j->nc);
1150 for(i=0; i<j->nc; i++)
1151 fprint(2, "%K\n", &j->c[i]);
1154 snprint(a->outhttp, AuxBuf, "%J", j);
1158 if(strlen(a->inhttp)+r->ifcall.count >= AuxBuf){
1159 respond(r, "http headers too large");
1162 memmove(a->inhttp+strlen(a->inhttp), r->ifcall.data, r->ifcall.count);
1164 r->ofcall.count = r->ifcall.count;
1169 sz = r->ifcall.count+r->ifcall.offset;
1170 if(sz > strlen(a->ctext)){
1172 respond(r, "cookie file too large");
1175 a->ctext = erealloc9p(a->ctext, sz+1);
1176 a->ctext[sz] = '\0';
1178 memmove(a->ctext+r->ifcall.offset, r->ifcall.data, r->ifcall.count);
1179 r->ofcall.count = r->ifcall.count;
1184 respond(r, "bug in webcookies");
1190 fsdestroyfid(Fid *fid)
1199 switch((uintptr)fid->file->aux){
1201 parsehttp(jar, a->inhttp, a->dom, a->path);
1204 for(i=0; i<jar->nc; i++)
1206 for(p=a->ctext; *p; p=nextp){
1207 if((nextp = strchr(p, '\n')) != nil)
1211 addtojar(jar, p, 0);
1213 for(i=0; i<jar->nc; i++)
1215 delcookie(jar, &jar->c[i]);
1239 .destroyfid= fsdestroyfid,
1246 fprint(2, "usage: webcookies [-f file] [-m mtpt] [-s service]\n");
1251 main(int argc, char **argv)
1253 char *file, *mtpt, *home, *srv;
1257 mtpt = "/mnt/webcookies";
1266 file = EARGF(usage());
1269 srv = EARGF(usage());
1272 mtpt = EARGF(usage());
1282 fmtinstall('J', jarfmt);
1283 fmtinstall('K', cookiefmt);
1286 home = getenv("home");
1288 sysfatal("no cookie file specified and no $home");
1289 file = emalloc9p(strlen(home)+30);
1291 strcat(file, "/lib/webcookies");
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);