]> git.lizzy.rs Git - plan9front.git/blob - sys/src/cmd/webcookies.c
webcookies: only sync the jar when dirty on clunk
[plan9front.git] / sys / src / cmd / webcookies.c
1 /*
2  * Cookie file system.  Allows hget and multiple webfs's to collaborate.
3  * Conventionally mounted on /mnt/webcookies.
4  */
5
6 #include <u.h>
7 #include <libc.h>
8 #include <bio.h>
9 #include <ndb.h>
10 #include <fcall.h>
11 #include <thread.h>
12 #include <9p.h>
13 #include <ctype.h>
14
15 int debug = 0;
16
17 typedef struct Cookie Cookie;
18 typedef struct Jar Jar;
19
20 struct Cookie
21 {
22         /* external info */
23         char*   name;
24         char*   value;
25         char*   dom;            /* starts with . */
26         char*   path;
27         char*   version;
28         char*   comment;        /* optional, may be nil */
29
30         uint    expire;         /* time of expiration: ~0 means when webcookies dies */
31         int     secure;
32         int     explicitdom;    /* dom was explicitly set */
33         int     explicitpath;   /* path was explicitly set */
34         int     netscapestyle;
35
36         /* internal info */
37         int     deleted;
38         int     mark;
39         int     ondisk;
40 };
41
42 struct Jar
43 {
44         Cookie  *c;
45         int     nc;
46         int     mc;
47
48         Qid     qid;
49         int     dirty;
50         char    *file;
51         char    *lockfile;
52 };
53
54 struct {
55         char    *s;
56         int     offset;
57         int     ishttp;
58 } stab[] = {
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,
65 };
66
67 struct {
68         char *s;
69         int     offset;
70 } itab[] = {
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),
76 };
77
78 #pragma varargck type "J"       Jar*
79 #pragma varargck type "K"       Cookie*
80
81 /* HTTP format */
82 int
83 jarfmt(Fmt *fmt)
84 {
85         int i;
86         Jar *jar;
87
88         jar = va_arg(fmt->args, Jar*);
89         if(jar == nil || jar->nc == 0)
90                 return fmtstrcpy(fmt, "");
91
92         fmtprint(fmt, "Cookie: ");
93         if(jar->c[0].version)
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");
98         return 0;
99 }
100
101 /* individual cookie */
102 int
103 cookiefmt(Fmt *fmt)
104 {
105         int j, k, first;
106         char *t;
107         Cookie *c;
108
109         c = va_arg(fmt->args, Cookie*);
110
111         first = 1;
112         for(j=0; j<nelem(stab); j++){
113                 t = *(char**)((char*)c+stab[j].offset);
114                 if(t == nil)
115                         continue;
116                 if(first)
117                         first = 0;
118                 else
119                         fmtprint(fmt, " ");
120                 fmtprint(fmt, "%s=%q", stab[j].s, t);
121         }
122         for(j=0; j<nelem(itab); j++){
123                 k = *(int*)((char*)c+itab[j].offset);
124                 if(k == 0)
125                         continue;
126                 if(first)
127                         first = 0;
128                 else
129                         fmtprint(fmt, " ");
130                 fmtprint(fmt, "%s=%ud", itab[j].s, k);
131         }
132         return 0;
133 }
134
135 /*
136  * sort cookies:
137  *      - alpha by name
138  *      - alpha by domain
139  *      - longer paths first, then alpha by path (RFC2109 4.3.4)
140  */
141 int
142 cookiecmp(Cookie *a, Cookie *b)
143 {
144         int i;
145
146         if((i = strcmp(a->name, b->name)) != 0)
147                 return i;
148         if((i = cistrcmp(a->dom, b->dom)) != 0)
149                 return i;
150         if((i = strlen(b->path) - strlen(a->path)) != 0)
151                 return i;
152         if((i = strcmp(a->path, b->path)) != 0)
153                 return i;
154         return 0;
155 }
156
157 int
158 exactcookiecmp(Cookie *a, Cookie *b)
159 {
160         int i;
161
162         if((i = cookiecmp(a, b)) != 0)
163                 return i;
164         if((i = strcmp(a->value, b->value)) != 0)
165                 return i;
166         if(a->version || b->version){
167                 if(!a->version)
168                         return -1;
169                 if(!b->version)
170                         return 1;
171                 if((i = strcmp(a->version, b->version)) != 0)
172                         return i;
173         }
174         if(a->comment || b->comment){
175                 if(!a->comment)
176                         return -1;
177                 if(!b->comment)
178                         return 1;
179                 if((i = strcmp(a->comment, b->comment)) != 0)
180                         return i;
181         }
182         if((i = b->expire - a->expire) != 0)
183                 return i;
184         if((i = b->secure - a->secure) != 0)
185                 return i;
186         if((i = b->explicitdom - a->explicitdom) != 0)
187                 return i;
188         if((i = b->explicitpath - a->explicitpath) != 0)
189                 return i;
190         if((i = b->netscapestyle - a->netscapestyle) != 0)
191                 return i;
192
193         return 0;
194 }
195
196 void
197 freecookie(Cookie *c)
198 {
199         int i;
200
201         for(i=0; i<nelem(stab); i++)
202                 free(*(char**)((char*)c+stab[i].offset));
203 }
204
205 void
206 copycookie(Cookie *c)
207 {
208         int i;
209         char **ps;
210
211         for(i=0; i<nelem(stab); i++){
212                 ps = (char**)((char*)c+stab[i].offset);
213                 if(*ps)
214                         *ps = estrdup9p(*ps);
215         }
216 }
217
218 void
219 delcookie(Jar *j, Cookie *c)
220 {
221         int i;
222
223         j->dirty = 1;
224         i = c - j->c;
225         if(i < 0 || i >= j->nc)
226                 abort();
227         c->deleted = 1;
228 }
229
230 void
231 addcookie(Jar *j, Cookie *c)
232 {
233         int i;
234
235         if(!c->name || !c->value || !c->path || !c->dom){
236                 fprint(2, "not adding incomplete cookie\n");
237                 return;
238         }
239
240         if(debug)
241                 fprint(2, "add %K\n", c);
242
243         for(i=0; i<j->nc; i++)
244                 if(cookiecmp(&j->c[i], c) == 0){
245                         if(debug)
246                                 fprint(2, "cookie %K matches %K\n", &j->c[i], c);
247                         if(exactcookiecmp(&j->c[i], c) == 0){
248                                 if(debug)
249                                         fprint(2, "\texactly\n");
250                                 j->c[i].mark = 0;
251                                 return;
252                         }
253                         delcookie(j, &j->c[i]);
254                 }
255
256         j->dirty = 1;
257         if(j->nc == j->mc){
258                 j->mc += 16;
259                 j->c = erealloc9p(j->c, j->mc*sizeof(Cookie));
260         }
261         j->c[j->nc] = *c;
262         copycookie(&j->c[j->nc]);
263         j->nc++;
264 }
265
266 void
267 purgejar(Jar *j)
268 {
269         int i;
270
271         for(i=j->nc-1; i>=0; i--){
272                 if(!j->c[i].deleted)
273                         continue;
274                 freecookie(&j->c[i]);
275                 --j->nc;
276                 j->c[i] = j->c[j->nc];
277         }
278 }
279
280 void
281 addtojar(Jar *jar, char *line, int ondisk)
282 {
283         Cookie c;
284         int i, j, nf, *pint;
285         char *f[20], *attr, *val, **pstr;
286         
287         memset(&c, 0, sizeof c);
288         c.expire = ~0;
289         c.ondisk = ondisk;
290         nf = tokenize(line, f, nelem(f));
291         for(i=0; i<nf; i++){
292                 attr = f[i];
293                 if((val = strchr(attr, '=')) != nil)
294                         *val++ = '\0';
295                 else
296                         val = "";
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);
301                                 *pstr = val;
302                         }
303                 }
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);
308                                 if(val[0]=='\0')
309                                         *pint = 1;
310                                 else
311                                         *pint = strtoul(val, 0, 0);
312                         }
313                 }
314         }
315         if(c.name==nil || c.value==nil || c.dom==nil || c.path==nil){
316                 if(debug)
317                         fprint(2, "ignoring fractional cookie %K\n", &c);
318                 return;
319         }
320         addcookie(jar, &c);
321 }
322
323 Jar*
324 newjar(void)
325 {
326         Jar *jar;
327
328         jar = emalloc9p(sizeof(Jar));
329         return jar;
330 }
331
332 int
333 expirejar(Jar *jar, int exiting)
334 {
335         int i, n;
336         uint now;
337
338         now = time(0);
339         n = 0;
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]);
343                         n++;
344                 }
345         }
346         return n;
347 }
348
349 int
350 syncjar(Jar *jar)
351 {
352         int i, fd, doread, dowrite;
353         char *line;
354         Biobuf *b;
355         Dir *d;
356         Qid q;
357
358         if(jar->file==nil)
359                 return 0;
360
361         doread = 0;
362         dowrite = jar->dirty;
363
364         q = jar->qid;
365         if((d = dirstat(jar->file)) == nil)
366                 dowrite = 1;
367         else {
368                 if(q.path != d->qid.path || q.vers != d->qid.vers){
369                         q = d->qid;
370                         doread = 1;
371                 }
372                 free(d);
373         }
374
375         if(!doread && !dowrite)
376                 return 0;
377
378         fd = -1;
379         for(i=0; i<50; i++){
380                 if((fd = create(jar->lockfile, OWRITE, DMEXCL|0666)) < 0){
381                         sleep(100);
382                         continue;
383                 }
384                 break;
385         }
386         if(fd < 0){
387                 if(debug)
388                         fprint(2, "open %s: %r", jar->lockfile);
389                 werrstr("cannot acquire jar lock: %r");
390                 return -1;
391         }
392
393         if(doread){
394                 for(i=0; i<jar->nc; i++)        /* mark is cleared by addcookie */
395                         jar->c[i].mark = jar->c[i].ondisk;
396
397                 if((b = Bopen(jar->file, OREAD)) == nil){
398                         if(debug)
399                                 fprint(2, "Bopen %s: %r", jar->file);
400                         werrstr("cannot read cookie file %s: %r", jar->file);
401                         close(fd);
402                         return -1;
403                 }
404                 for(; (line = Brdstr(b, '\n', 1)) != nil; free(line)){
405                         if(*line == '#')
406                                 continue;
407                         addtojar(jar, line, 1);
408                 }
409                 Bterm(b);
410
411                 for(i=0; i<jar->nc; i++)
412                         if(jar->c[i].mark)
413                                 delcookie(jar, &jar->c[i]);
414         }
415
416         purgejar(jar);
417
418         if(dowrite){
419                 b = Bopen(jar->file, OTRUNC|OWRITE);
420                 if(b == nil){
421                         if(debug)
422                                 fprint(2, "Bopen write %s: %r", jar->file);
423                         close(fd);
424                         return -1;
425                 }
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)
430                                 continue;
431                         Bprint(b, "%K\n", &jar->c[i]);
432                         jar->c[i].ondisk = 1;
433                 }
434                 Bflush(b);
435                 if((d = dirfstat(Bfildes(b))) != nil){
436                         q = d->qid;
437                         free(d);
438                 }
439                 Bterm(b);
440         }
441
442         jar->qid = q;
443         jar->dirty = 0;
444
445         close(fd);
446         return 0;
447 }
448
449 Jar*
450 readjar(char *file)
451 {
452         char *lock, *p;
453         Jar *jar;
454
455         jar = newjar();
456         lock = emalloc9p(strlen(file)+10);
457         strcpy(lock, file);
458         if((p = strrchr(lock, '/')) != nil)
459                 p++;
460         else
461                 p = lock;
462         memmove(p+2, p, strlen(p)+1);
463         p[0] = 'L';
464         p[1] = '.';
465         jar->lockfile = lock;
466         jar->file = file;
467         jar->dirty = 0;
468
469         if(syncjar(jar) < 0){
470                 free(jar->file);
471                 free(jar->lockfile);
472                 free(jar);
473                 return nil;
474         }
475         return jar;
476 }
477
478 void
479 closejar(Jar *jar)
480 {
481         int i;
482
483         if(jar == nil)
484                 return;
485         expirejar(jar, 0);
486         if(jar->dirty)
487                 if(syncjar(jar) < 0)
488                         fprint(2, "warning: cannot rewrite cookie jar: %r\n");
489
490         for(i=0; i<jar->nc; i++)
491                 freecookie(&jar->c[i]);
492
493         free(jar->file);
494         free(jar->c);
495         free(jar);      
496 }
497
498 /*
499  * Domain name matching is per RFC2109, section 2:
500  *
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
504  *
505  * * both host names are IP addresses and their host name strings match
506  *   exactly; or
507  *
508  * * both host names are FQDN strings and their host name strings match
509  *   exactly; or
510  *
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.)
514  *
515  * Note that domain-match is not a commutative operation: a.b.c.com
516  * domain-matches .c.com, but not the reverse.
517  *
518  * (This does not verify that IP addresses and FQDN's are well-formed.)
519  */
520 int
521 isdomainmatch(char *name, char *pattern)
522 {
523         int lname, lpattern;
524
525         if(cistrcmp(name, pattern)==0)
526                 return 1;
527
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)
532                         return 1;
533         }
534
535         return 0;
536 }
537
538 /*
539  * RFC2109 4.3.4:
540  *      - domain must match
541  *      - path in cookie must be a prefix of request path
542  *      - cookie must not have expired
543  */
544 int
545 iscookiematch(Cookie *c, char *dom, char *path, uint now)
546 {
547         return isdomainmatch(dom, c->dom)
548                 && strncmp(c->path, path, strlen(c->path))==0
549                 && c->expire >= now;
550 }
551
552 /* 
553  * Produce a subjar of matching cookies.
554  * Secure cookies are only included if secure is set.
555  */
556 Jar*
557 cookiesearch(Jar *jar, char *dom, char *path, int issecure)
558 {
559         int i;
560         Jar *j;
561         Cookie *c;
562         uint now;
563
564         now = time(0);
565         j = newjar();
566         for(i=0; i<jar->nc; i++){
567                 c = &jar->c[i];
568                 if(!c->deleted && (issecure || !c->secure) && iscookiematch(c, dom, path, now))
569                         addcookie(j, c);
570         }
571         if(j->nc == 0){
572                 closejar(j);
573                 werrstr("no cookies found");
574                 return nil;
575         }
576         qsort(j->c, j->nc, sizeof(j->c[0]), (int(*)(const void*, const void*))cookiecmp);
577         return j;
578 }
579
580 /*
581  * RFC2109 4.3.2 security checks
582  */
583 char*
584 isbadcookie(Cookie *c, char *dom, char *path)
585 {
586         if(strncmp(c->path, path, strlen(c->path)) != 0)
587                 return "cookie path is not a prefix of the request path";
588
589         if(c->explicitdom && c->dom[0] != '.')
590                 return "cookie domain doesn't start with dot";
591
592         if(memchr(c->dom+1, '.', strlen(c->dom)-1-1) == nil)
593                 return "cookie domain doesn't have embedded dots";
594
595         if(!isdomainmatch(dom, c->dom))
596                 return "request host does not match cookie domain";
597
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";
601
602         return 0;
603 }
604
605 /*
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
609  */
610 int
611 isleap(int year)
612 {
613         return year%4==0 && (year%100!=0 || year%400==0);
614 }
615
616 uint
617 strtotime(char *s)
618 {
619         char *os;
620         int i;
621         Tm tm;
622
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,
626         };
627         static char *wday[] = {
628                 "Sunday", "Monday", "Tuesday", "Wednesday",
629                 "Thursday", "Friday", "Saturday",
630         };
631         static char *mon[] = {
632                 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
633                 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
634         };
635
636         os = s;
637         /* Sunday, */
638         for(i=0; i<nelem(wday); i++){
639                 if(cistrncmp(s, wday[i], strlen(wday[i])) == 0){
640                         s += strlen(wday[i]);
641                         break;
642                 }
643                 if(cistrncmp(s, wday[i], 3) == 0){
644                         s += 3;
645                         break;
646                 }
647         }
648         if(i==nelem(wday)){
649                 if(debug)
650                         fprint(2, "bad wday (%s)\n", os);
651                 return -1;
652         }
653         if(*s++ != ',' || *s++ != ' '){
654                 if(debug)
655                         fprint(2, "bad wday separator (%s)\n", os);
656                 return -1;
657         }
658
659         /* 25- */
660         if(!isdigit(s[0]) || !isdigit(s[1]) || (s[2]!='-' && s[2]!=' ')){
661                 if(debug)
662                         fprint(2, "bad day of month (%s)\n", os);
663                 return -1;
664         }
665         tm.mday = strtol(s, 0, 10);
666         s += 3;
667
668         /* Jan- */
669         for(i=0; i<nelem(mon); i++)
670                 if(cistrncmp(s, mon[i], 3) == 0){
671                         tm.mon = i;
672                         s += 3;
673                         break;
674                 }
675         if(i==nelem(mon)){
676                 if(debug)
677                         fprint(2, "bad month (%s)\n", os);
678                 return -1;
679         }
680         if(s[0] != '-' && s[0] != ' '){
681                 if(debug)
682                         fprint(2, "bad month separator (%s)\n", os);
683                 return -1;
684         }
685         s++;
686
687         /* 2002 */
688         if(!isdigit(s[0]) || !isdigit(s[1])){
689                 if(debug)
690                         fprint(2, "bad year (%s)\n", os);
691                 return -1;
692         }
693         tm.year = strtol(s, 0, 10);
694         s += 2;
695         if(isdigit(s[0]) && isdigit(s[1]))
696                 s += 2;
697         else{
698                 if(tm.year <= 68)
699                         tm.year += 2000;
700                 else
701                         tm.year += 1900;
702         }
703         if(tm.mday==0 || tm.mday > mday[isleap(tm.year)][tm.mon]){
704                 if(debug)
705                         fprint(2, "invalid day of month (%s)\n", os);
706                 return -1;
707         }
708         tm.year -= 1900;
709         if(*s++ != ' '){
710                 if(debug)
711                         fprint(2, "bad year separator (%s)\n", os);
712                 return -1;
713         }
714
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]!=' '){
718                 if(debug)
719                         fprint(2, "bad time (%s)\n", os);
720                 return -1;
721         }
722
723         tm.hour = atoi(s);
724         tm.min = atoi(s+3);
725         tm.sec = atoi(s+6);
726         if(tm.hour >= 24 || tm.min >= 60 || tm.sec >= 60){
727                 if(debug)
728                         fprint(2, "invalid time (%s)\n", os);
729                 return -1;
730         }
731         s += 9;
732
733         if(cistrcmp(s, "GMT") != 0){
734                 if(debug)
735                         fprint(2, "time zone not GMT (%s)\n", os);
736                 return -1;
737         }
738         strcpy(tm.zone, "GMT");
739         tm.yday = 0;
740         return tm2sec(&tm);
741 }
742
743 /*
744  * skip linear whitespace.  we're a bit more lenient than RFC2616 2.2.
745  */
746 char*
747 skipspace(char *s)
748 {
749         while(*s=='\r' || *s=='\n' || *s==' ' || *s=='\t')
750                 s++;
751         return s;
752 }
753
754 /*
755  * Try to identify old netscape headers.
756  * The old headers:
757  *      - didn't allow spaces around the '='
758  *      - used an 'Expires' attribute
759  *      - had no 'Version' attribute
760  *      - had no quotes
761  *      - allowed whitespace in values
762  *      - apparently separated attr/value pairs with ';' exclusively
763  */
764 int
765 isnetscape(char *hdr)
766 {
767         char *s;
768
769         for(s=hdr; (s=strchr(s, '=')) != nil; s++){
770                 if(isspace(s[1]) || (s > hdr && isspace(s[-1])))
771                         return 0;
772                 if(s[1]=='"')
773                         return 0;
774         }
775         if(cistrstr(hdr, "version="))
776                 return 0;
777         return 1;
778 }
779
780 /*
781  * Parse HTTP response headers, adding cookies to jar.
782  * Overwrites the headers.  May overwrite path.
783  */
784 char* parsecookie(Cookie*, char*, char**, int, char*, char*);
785 int
786 parsehttp(Jar *jar, char *hdr, char *dom, char *path)
787 {
788         static char setcookie[] = "Set-Cookie:";
789         char *e, *p, *nextp;
790         Cookie c;
791         int isns, n;
792
793         isns = isnetscape(hdr);
794         n = 0;
795         for(p=hdr; p; p=nextp){
796                 p = skipspace(p);
797                 if(*p == '\0')
798                         break;
799                 nextp = strchr(p, '\n');
800                 if(nextp != nil)
801                         *nextp++ = '\0';
802                 if(debug)
803                         fprint(2, "?%s\n", p);
804                 if(cistrncmp(p, setcookie, strlen(setcookie)) != 0)
805                         continue;
806                 if(debug)
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){
811                                 if(debug)
812                                         fprint(2, "parse cookie: %s\n", e);
813                                 break;
814                         }
815                         if((e = isbadcookie(&c, dom, path)) != nil){
816                                 if(debug)
817                                         fprint(2, "reject cookie; %s\n", e);
818                                 continue;
819                         }
820                         addcookie(jar, &c);
821                         n++;
822                 }
823         }
824         return n;
825 }
826
827 static char*
828 skipquoted(char *s)
829 {
830         /*
831          * Sec 2.2 of RFC2616 defines a "quoted-string" as:
832          *
833          *  quoted-string  = ( <"> *(qdtext | quoted-pair ) <"> )
834          *  qdtext         = <any TEXT except <">>
835          *  quoted-pair    = "\" CHAR
836          *
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;
841          */
842         if(*s != '"')
843                 return s;
844
845         for(s++; 32 <= *s && *s < 127 && *s != '"'; s++)
846                 if(*s == '\\' && *(s+1) != '\0')
847                         s++;
848         return s;
849 }
850
851 static char*
852 skiptoken(char *s)
853 {
854         /*
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)
860          */
861         while(32 <= *s && *s < 127 && strchr("()<>@,;:[]?={}\" \t\\", *s)==nil)
862                 s++;
863
864         return s;
865 }
866
867 static char*
868 skipvalue(char *s, int isns)
869 {
870         char *t;
871
872         /*
873          * An RFC2109 value is an HTTP token or an HTTP quoted string.
874          * Netscape servers ignore the spec and rely on semicolons, apparently.
875          */
876         if(isns){
877                 if((t = strchr(s, ';')) == nil)
878                         t = s+strlen(s);
879                 return t;
880         }
881         if(*s == '"')
882                 return skipquoted(s);
883         return skiptoken(s);
884 }
885
886 /*
887  * RMID=80b186bb64c03c65fab767f8; expires=Monday, 10-Feb-2003 04:44:39 GMT; 
888  *      path=/; domain=.nytimes.com
889  */
890 char*
891 parsecookie(Cookie *c, char *p, char **e, int isns, char *dom, char *path)
892 {
893         int i, done;
894         char *t, *u, *attr, *val;
895
896         memset(c, 0, sizeof *c);
897         c->expire = ~0;
898
899         /* NAME=VALUE */
900         t = skiptoken(p);
901         c->name = p;
902         p = skipspace(t);
903         if(*p != '='){
904         Badname:
905                 return "malformed cookie: no NAME=VALUE";
906         }
907         *t = '\0';
908         p = skipspace(p+1);
909         t = skipvalue(p, isns);
910         if(*t)
911                 *t++ = '\0';
912         c->value = p;
913         p = skipspace(t);
914         if(c->name[0]=='\0' || c->value[0]=='\0')
915                 goto Badname;
916
917         done = 0;
918         for(; *p && !done; p=skipspace(p)){
919                 attr = p;
920                 t = skiptoken(p);
921                 u = skipspace(t);
922                 switch(*u){
923                 case '\0':
924                         *t = '\0';
925                         p = val = u;
926                         break;
927                 case ';':
928                         *t = '\0';
929                         val = "";
930                         p = u+1;
931                         break;
932                 case '=':
933                         *t = '\0';
934                         val = skipspace(u+1);
935                         p = skipvalue(val, isns);
936                         if(*p==',')
937                                 done = 1;
938                         if(*p)
939                                 *p++ = '\0';
940                         break;
941                 case ',':
942                         if(!isns){
943                                 val = "";
944                                 p = u;
945                                 *p++ = '\0';
946                                 done = 1;
947                                 break;
948                         }
949                 default:
950                         if(debug)
951                                 fprint(2, "syntax: %s\n", p);
952                         return "syntax error";
953                 }
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){
958                         if(!isns)
959                                 return "non-netscape cookie has Expires tag";
960                         if(!val[0])
961                                 return "bad expires tag";
962                         c->expire = strtotime(val);
963                         if(c->expire == ~0)
964                                 return "cannot parse netscape expires tag";
965                 }
966                 if(cistrcmp(attr, "max-age") == 0)
967                         c->expire = time(0)+atoi(val);
968                 if(cistrcmp(attr, "secure") == 0)
969                         c->secure = 1;
970         }
971         *e = p;
972
973         if(c->dom){
974                 /* add leading dot for explicit domain */
975                 if(c->dom[0] != '.' && strcmp(ipattr(c->dom), "dom") == 0){
976                         static char *ddom = nil;
977
978                         ddom = realloc(ddom, strlen(c->dom)+2);
979                         if(ddom != nil){
980                                 ddom[0] = '.';
981                                 strcpy(ddom+1, c->dom);
982                                 c->dom = ddom;
983                         }
984                 }
985                 c->explicitdom = 1;
986         }else
987                 c->dom = dom;
988         if(c->path)
989                 c->explicitpath = 1;
990         else{
991                 c->path = path;
992                 if((t = strchr(c->path, '#')) != 0)
993                         *t = '\0';
994                 if((t = strchr(c->path, '?')) != 0)
995                         *t = '\0';
996                 if((t = strrchr(c->path, '/')) != 0)
997                         *t = '\0';
998         }
999         c->netscapestyle = isns;
1000
1001         return nil;
1002 }
1003
1004 Jar *jar;
1005
1006 enum
1007 {
1008         Xhttp = 1,
1009         Xcookies,
1010
1011         NeedUrl = 0,
1012         HaveUrl,
1013 };
1014
1015 typedef struct Aux Aux;
1016 struct Aux
1017 {
1018         int state;
1019         char *dom;
1020         char *path;
1021         char *inhttp;
1022         char *outhttp;
1023         char *ctext;
1024         int rdoff;
1025 };
1026 enum
1027 {
1028         AuxBuf = 4096,
1029         MaxCtext = 16*1024*1024,
1030 };
1031
1032 void
1033 fsopen(Req *r)
1034 {
1035         char *s, *es;
1036         int i, sz;
1037         Aux *a;
1038
1039         switch((uintptr)r->fid->file->aux){
1040         case Xhttp:
1041                 syncjar(jar);
1042                 a = emalloc9p(sizeof(Aux));
1043                 r->fid->aux = a;
1044                 a->inhttp = emalloc9p(AuxBuf);
1045                 a->outhttp = emalloc9p(AuxBuf);
1046                 break;
1047
1048         case Xcookies:
1049                 syncjar(jar);
1050                 a = emalloc9p(sizeof(Aux));
1051                 r->fid->aux = a;
1052                 if(r->ifcall.mode&OTRUNC){
1053                         a->ctext = emalloc9p(1);
1054                         a->ctext[0] = '\0';
1055                 }else{
1056                         sz = 256*jar->nc+1024;  /* BUG should do better */
1057                         a->ctext = emalloc9p(sz);
1058                         a->ctext[0] = '\0';
1059                         s = a->ctext;
1060                         es = s+sz;
1061                         for(i=0; i<jar->nc; i++)
1062                                 s = seprint(s, es, "%K\n", &jar->c[i]);
1063                 }
1064                 break;
1065         }
1066         respond(r, nil);
1067 }
1068
1069 void
1070 fsread(Req *r)
1071 {
1072         Aux *a;
1073
1074         a = r->fid->aux;
1075         switch((uintptr)r->fid->file->aux){
1076         case Xhttp:
1077                 if(a->state == NeedUrl){
1078                         respond(r, "must write url before read");
1079                         return;
1080                 }
1081                 r->ifcall.offset = a->rdoff;
1082                 readstr(r, a->outhttp);
1083                 a->rdoff += r->ofcall.count;
1084                 respond(r, nil);
1085                 return;
1086
1087         case Xcookies:
1088                 readstr(r, a->ctext);
1089                 respond(r, nil);
1090                 return;
1091
1092         default:
1093                 respond(r, "bug in webcookies");
1094                 return;
1095         }
1096 }
1097
1098 void
1099 fswrite(Req *r)
1100 {
1101         Aux *a;
1102         int i, sz, hlen, issecure;
1103         char buf[1024], *p;
1104         Jar *j;
1105
1106         a = r->fid->aux;
1107         switch((uintptr)r->fid->file->aux){
1108         case Xhttp:
1109                 if(a->state == NeedUrl){
1110                         if(r->ifcall.count >= sizeof buf){
1111                                 respond(r, "url too long");
1112                                 return;
1113                         }
1114                         memmove(buf, r->ifcall.data, r->ifcall.count);
1115                         buf[r->ifcall.count] = '\0';
1116                         issecure = 0;
1117                         if(cistrncmp(buf, "http://", 7) == 0)
1118                                 hlen = 7;
1119                         else if(cistrncmp(buf, "https://", 8) == 0){
1120                                 hlen = 8;
1121                                 issecure = 1;
1122                         }else{
1123                                 respond(r, "url must begin http:// or https://");
1124                                 return;
1125                         }
1126                         if(buf[hlen]=='/'){
1127                                 respond(r, "url without host name");
1128                                 return;
1129                         }
1130                         p = strchr(buf+hlen, '/');
1131                         if(p == nil)
1132                                 a->path = estrdup9p("/");
1133                         else{
1134                                 a->path = estrdup9p(p);
1135                                 *p = '\0';
1136                         }
1137                         a->dom = estrdup9p(buf+hlen);
1138                         a->state = HaveUrl;
1139                         j = cookiesearch(jar, a->dom, a->path, issecure);
1140                         if(debug){
1141                                 fprint(2, "search %s %s got %p\n", a->dom, a->path, j);
1142                                 if(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]);
1146                                 }
1147                         }
1148                         snprint(a->outhttp, AuxBuf, "%J", j);
1149                         if(j)
1150                                 closejar(j);
1151                 }else{
1152                         if(strlen(a->inhttp)+r->ifcall.count >= AuxBuf){
1153                                 respond(r, "http headers too large");
1154                                 return;
1155                         }
1156                         memmove(a->inhttp+strlen(a->inhttp), r->ifcall.data, r->ifcall.count);
1157                 }
1158                 r->ofcall.count = r->ifcall.count;
1159                 respond(r, nil);
1160                 return;
1161
1162         case Xcookies:
1163                 sz = r->ifcall.count+r->ifcall.offset;
1164                 if(sz > strlen(a->ctext)){
1165                         if(sz >= MaxCtext){
1166                                 respond(r, "cookie file too large");
1167                                 return;
1168                         }
1169                         a->ctext = erealloc9p(a->ctext, sz+1);
1170                         a->ctext[sz] = '\0';
1171                 }
1172                 memmove(a->ctext+r->ifcall.offset, r->ifcall.data, r->ifcall.count);
1173                 r->ofcall.count = r->ifcall.count;
1174                 respond(r, nil);
1175                 return;
1176
1177         default:
1178                 respond(r, "bug in webcookies");
1179                 return;
1180         }
1181 }
1182
1183 void
1184 fsdestroyfid(Fid *fid)
1185 {
1186         char *p, *nextp;
1187         Aux *a;
1188         int i;
1189
1190         a = fid->aux;
1191         if(a == nil)
1192                 return;
1193         switch((uintptr)fid->file->aux){
1194         case Xhttp:
1195                 parsehttp(jar, a->inhttp, a->dom, a->path);
1196                 break;
1197         case Xcookies:
1198                 for(i=0; i<jar->nc; i++)
1199                         jar->c[i].mark = 1;
1200                 for(p=a->ctext; *p; p=nextp){
1201                         if((nextp = strchr(p, '\n')) != nil)
1202                                 *nextp++ = '\0';
1203                         else
1204                                 nextp = "";
1205                         addtojar(jar, p, 0);
1206                 }
1207                 for(i=0; i<jar->nc; i++)
1208                         if(jar->c[i].mark)
1209                                 delcookie(jar, &jar->c[i]);
1210                 break;
1211         }
1212         if(jar->dirty)
1213                 syncjar(jar);
1214         free(a->dom);
1215         free(a->path);
1216         free(a->inhttp);
1217         free(a->outhttp);
1218         free(a->ctext);
1219         free(a);
1220 }
1221
1222 void
1223 fsend(Srv*)
1224 {
1225         closejar(jar);
1226 }
1227
1228 Srv fs = 
1229 {
1230 .open=          fsopen,
1231 .read=          fsread,
1232 .write=         fswrite,
1233 .destroyfid=    fsdestroyfid,
1234 .end=           fsend,
1235 };
1236
1237 void
1238 usage(void)
1239 {
1240         fprint(2, "usage: webcookies [-f file] [-m mtpt] [-s service]\n");
1241         exits("usage");
1242 }
1243         
1244 void
1245 main(int argc, char **argv)
1246 {
1247         char *file, *mtpt, *home, *srv;
1248         int fd;
1249
1250         file = nil;
1251         srv = nil;
1252         mtpt = "/mnt/webcookies";
1253         ARGBEGIN{
1254         case 'D':
1255                 chatty9p++;
1256                 break;
1257         case 'd':
1258                 debug = 1;
1259                 break;
1260         case 'f':
1261                 file = EARGF(usage());
1262                 break;
1263         case 's':
1264                 srv = EARGF(usage());
1265                 break;
1266         case 'm':
1267                 mtpt = EARGF(usage());
1268                 break;
1269         default:
1270                 usage();
1271         }ARGEND
1272
1273         if(argc != 0)
1274                 usage();
1275
1276         quotefmtinstall();
1277         fmtinstall('J', jarfmt);
1278         fmtinstall('K', cookiefmt);
1279
1280         if(file == nil){
1281                 home = getenv("home");
1282                 if(home == nil)
1283                         sysfatal("no cookie file specified and no $home");
1284                 file = emalloc9p(strlen(home)+30);
1285                 strcpy(file, home);
1286                 strcat(file, "/lib/webcookies");
1287         }
1288         if(access(file, AEXIST) < 0){
1289                 if((fd = create(file, OWRITE, 0600)) < 0)
1290                         sysfatal("create %s: %r", file);
1291                 close(fd);
1292         }
1293                         
1294         jar = readjar(file);
1295         if(jar == nil)
1296                 sysfatal("readjar: %r");
1297
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));
1301
1302         postmountsrv(&fs, srv, mtpt, MREPL);
1303         exits(nil);
1304 }