]> git.lizzy.rs Git - plan9front.git/blob - sys/src/cmd/webcookies.c
pc, pc64: disable all pci devices for /dev/reboot
[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|0600)) < 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                 i = create(jar->file, OWRITE, 0600);
420                 if(i < 0 || (b = Bfdopen(i, OWRITE)) == nil){
421                         if(debug)
422                                 fprint(2, "Bopen write %s: %r", jar->file);
423                         if(i >= 0)
424                                 close(i);
425                         close(fd);
426                         return -1;
427                 }
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)
432                                 continue;
433                         Bprint(b, "%K\n", &jar->c[i]);
434                         jar->c[i].ondisk = 1;
435                 }
436                 Bflush(b);
437                 if((d = dirfstat(Bfildes(b))) != nil){
438                         q = d->qid;
439                         free(d);
440                 }
441                 Bterm(b);
442         }
443
444         jar->qid = q;
445         jar->dirty = 0;
446
447         close(fd);
448         return 0;
449 }
450
451 void
452 closejar(Jar *jar)
453 {
454         int i;
455
456         if(jar == nil)
457                 return;
458         expirejar(jar, 0);
459         if(jar->dirty)
460                 if(syncjar(jar) < 0)
461                         fprint(2, "warning: cannot rewrite cookie jar: %r\n");
462
463         for(i=0; i<jar->nc; i++)
464                 freecookie(&jar->c[i]);
465
466         free(jar->lockfile);
467         free(jar->file);
468         free(jar->c);
469         free(jar);      
470 }
471
472 Jar*
473 readjar(char *file)
474 {
475         char *lock, *p;
476         Jar *jar;
477
478         jar = newjar();
479         file = estrdup9p(file);
480         lock = emalloc9p(strlen(file)+10);
481         strcpy(lock, file);
482         if((p = strrchr(lock, '/')) != nil)
483                 p++;
484         else
485                 p = lock;
486         memmove(p+2, p, strlen(p)+1);
487         p[0] = 'L';
488         p[1] = '.';
489         jar->lockfile = lock;
490         jar->file = file;
491         jar->dirty = 0;
492
493         if(syncjar(jar) < 0){
494                 closejar(jar);
495                 return nil;
496         }
497         return jar;
498 }
499
500
501 /*
502  * Domain name matching is per RFC2109, section 2:
503  *
504  * Hosts names can be specified either as an IP address or a FQHN
505  * string.  Sometimes we compare one host name with another.  Host A's
506  * name domain-matches host B's if
507  *
508  * * both host names are IP addresses and their host name strings match
509  *   exactly; or
510  *
511  * * both host names are FQDN strings and their host name strings match
512  *   exactly; or
513  *
514  * * A is a FQDN string and has the form NB, where N is a non-empty name
515  *   string, B has the form .B', and B' is a FQDN string.  (So, x.y.com
516  *   domain-matches .y.com but not y.com.)
517  *
518  * Note that domain-match is not a commutative operation: a.b.c.com
519  * domain-matches .c.com, but not the reverse.
520  *
521  * (This does not verify that IP addresses and FQDN's are well-formed.)
522  */
523 int
524 isdomainmatch(char *name, char *pattern)
525 {
526         int lname, lpattern;
527
528         if(cistrcmp(name, pattern + (pattern[0]=='.'))==0)
529                 return 1;
530
531         if(strcmp(ipattr(name), "dom")==0 && pattern[0]=='.'){
532                 lname = strlen(name);
533                 lpattern = strlen(pattern);
534                 if(lname >= lpattern && cistrcmp(name+lname-lpattern, pattern)==0)
535                         return 1;
536         }
537
538         return 0;
539 }
540
541 /*
542  * RFC2109 4.3.4:
543  *      - domain must match
544  *      - path in cookie must be a prefix of request path
545  *      - cookie must not have expired
546  */
547 int
548 iscookiematch(Cookie *c, char *dom, char *path, uint now)
549 {
550         return isdomainmatch(dom, c->dom)
551                 && strncmp(c->path, path, strlen(c->path))==0
552                 && c->expire >= now;
553 }
554
555 /* 
556  * Produce a subjar of matching cookies.
557  * Secure cookies are only included if secure is set.
558  */
559 Jar*
560 cookiesearch(Jar *jar, char *dom, char *path, int issecure)
561 {
562         int i;
563         Jar *j;
564         Cookie *c;
565         uint now;
566
567         now = time(0);
568         j = newjar();
569         for(i=0; i<jar->nc; i++){
570                 c = &jar->c[i];
571                 if(!c->deleted && (issecure || !c->secure) && iscookiematch(c, dom, path, now))
572                         addcookie(j, c);
573         }
574         if(j->nc == 0){
575                 closejar(j);
576                 werrstr("no cookies found");
577                 return nil;
578         }
579         qsort(j->c, j->nc, sizeof(j->c[0]), (int(*)(const void*, const void*))cookiecmp);
580         return j;
581 }
582
583 /*
584  * RFC2109 4.3.2 security checks
585  */
586 char*
587 isbadcookie(Cookie *c, char *dom, char *path)
588 {
589         if(strncmp(c->path, path, strlen(c->path)) != 0)
590                 return "cookie path is not a prefix of the request path";
591
592         if(c->explicitdom && c->dom[0] != '.')
593                 return "cookie domain doesn't start with dot";
594
595         if(strlen(c->dom)<=2 || memchr(c->dom+1, '.', strlen(c->dom)-2) == nil)
596                 return "cookie domain doesn't have embedded dots";
597
598         if(!isdomainmatch(dom, c->dom))
599                 return "request host does not match cookie domain";
600
601         if(strcmp(ipattr(dom), "dom")==0 && strlen(dom)>strlen(c->dom)
602         && memchr(dom, '.', strlen(dom)-strlen(c->dom)) != nil)
603                 return "request host contains dots before cookie domain";
604
605         return 0;
606 }
607
608 /*
609  * Sunday, 25-Jan-2002 12:24:36 GMT
610  * Sunday, 25 Jan 2002 12:24:36 GMT
611  * Sun, 25 Jan 02 12:24:36 GMT
612  */
613 int
614 isleap(int year)
615 {
616         return year%4==0 && (year%100!=0 || year%400==0);
617 }
618
619 uint
620 strtotime(char *s)
621 {
622         char *os;
623         int i;
624         Tm tm;
625
626         static int mday[2][12] = {
627                 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
628                 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
629         };
630         static char *wday[] = {
631                 "Sunday", "Monday", "Tuesday", "Wednesday",
632                 "Thursday", "Friday", "Saturday",
633         };
634         static char *mon[] = {
635                 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
636                 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
637         };
638
639         memset(&tm, 0, sizeof(tm));
640
641         os = s;
642         /* Sunday, */
643         for(i=0; i<nelem(wday); i++){
644                 if(cistrncmp(s, wday[i], strlen(wday[i])) == 0){
645                         s += strlen(wday[i]);
646                         break;
647                 }
648                 if(cistrncmp(s, wday[i], 3) == 0){
649                         s += 3;
650                         break;
651                 }
652         }
653         if(i==nelem(wday)){
654                 if(debug)
655                         fprint(2, "bad wday (%s)\n", os);
656                 return -1;
657         }
658         if(*s++ != ',' || *s++ != ' '){
659                 if(debug)
660                         fprint(2, "bad wday separator (%s)\n", os);
661                 return -1;
662         }
663
664         /* 25- */
665         if(!isdigit(s[0]) || !isdigit(s[1]) || (s[2]!='-' && s[2]!=' ')){
666                 if(debug)
667                         fprint(2, "bad day of month (%s)\n", os);
668                 return -1;
669         }
670         tm.mday = strtol(s, 0, 10);
671         s += 3;
672
673         /* Jan- */
674         for(i=0; i<nelem(mon); i++)
675                 if(cistrncmp(s, mon[i], 3) == 0){
676                         tm.mon = i;
677                         s += 3;
678                         break;
679                 }
680         if(i==nelem(mon)){
681                 if(debug)
682                         fprint(2, "bad month (%s)\n", os);
683                 return -1;
684         }
685         if(s[0] != '-' && s[0] != ' '){
686                 if(debug)
687                         fprint(2, "bad month separator (%s)\n", os);
688                 return -1;
689         }
690         s++;
691
692         /* 2002 */
693         if(!isdigit(s[0]) || !isdigit(s[1])){
694                 if(debug)
695                         fprint(2, "bad year (%s)\n", os);
696                 return -1;
697         }
698         tm.year = strtol(s, 0, 10);
699         s += 2;
700         if(isdigit(s[0]) && isdigit(s[1]))
701                 s += 2;
702         else{
703                 if(tm.year <= 68)
704                         tm.year += 2000;
705                 else
706                         tm.year += 1900;
707         }
708         if(tm.mday==0 || tm.mday > mday[isleap(tm.year)][tm.mon]){
709                 if(debug)
710                         fprint(2, "invalid day of month (%s)\n", os);
711                 return -1;
712         }
713         tm.year -= 1900;
714         if(*s++ != ' '){
715                 if(debug)
716                         fprint(2, "bad year separator (%s)\n", os);
717                 return -1;
718         }
719
720         if(!isdigit(s[0]) || !isdigit(s[1]) || s[2]!=':'
721         || !isdigit(s[3]) || !isdigit(s[4]) || s[5]!=':'
722         || !isdigit(s[6]) || !isdigit(s[7]) || s[8]!=' '){
723                 if(debug)
724                         fprint(2, "bad time (%s)\n", os);
725                 return -1;
726         }
727
728         tm.hour = strtol(s, 0, 10);
729         tm.min = strtol(s+3, 0, 10);
730         tm.sec = strtol(s+6, 0, 10);
731         if(tm.hour >= 24 || tm.min >= 60 || tm.sec >= 60){
732                 if(debug)
733                         fprint(2, "invalid time (%s)\n", os);
734                 return -1;
735         }
736         s += 9;
737
738         if(cistrcmp(s, "GMT") != 0){
739                 if(debug)
740                         fprint(2, "time zone not GMT (%s)\n", os);
741                 return -1;
742         }
743         strcpy(tm.zone, "GMT");
744         tm.yday = 0;
745         return tm2sec(&tm);
746 }
747
748 /*
749  * skip linear whitespace.  we're a bit more lenient than RFC2616 2.2.
750  */
751 char*
752 skipspace(char *s)
753 {
754         while(*s=='\r' || *s=='\n' || *s==' ' || *s=='\t')
755                 s++;
756         return s;
757 }
758
759 /*
760  * Try to identify old netscape headers.
761  * The old headers:
762  *      - didn't allow spaces around the '='
763  *      - used an 'Expires' attribute
764  *      - had no 'Version' attribute
765  *      - had no quotes
766  *      - allowed whitespace in values
767  *      - apparently separated attr/value pairs with ';' exclusively
768  */
769 int
770 isnetscape(char *hdr)
771 {
772         char *s;
773
774         for(s=hdr; (s=strchr(s, '=')) != nil; s++){
775                 if(isspace(s[1]) || (s > hdr && isspace(s[-1])))
776                         return 0;
777                 if(s[1]=='"')
778                         return 0;
779         }
780         if(cistrstr(hdr, "version="))
781                 return 0;
782         return 1;
783 }
784
785 /*
786  * Parse HTTP response headers, adding cookies to jar.
787  * Overwrites the headers.  May overwrite path.
788  */
789 char* parsecookie(Cookie*, char*, char**, int, char*, char*);
790 int
791 parsehttp(Jar *jar, char *hdr, char *dom, char *path)
792 {
793         static char setcookie[] = "Set-Cookie:";
794         char *e, *p, *nextp;
795         Cookie c;
796         int isns, n;
797
798         isns = isnetscape(hdr);
799         n = 0;
800         for(p=hdr; p; p=nextp){
801                 p = skipspace(p);
802                 if(*p == '\0')
803                         break;
804                 nextp = strchr(p, '\n');
805                 if(nextp != nil)
806                         *nextp++ = '\0';
807                 if(debug)
808                         fprint(2, "?%s\n", p);
809                 if(cistrncmp(p, setcookie, strlen(setcookie)) != 0)
810                         continue;
811                 if(debug)
812                         fprint(2, "%s\n", p);
813                 p = skipspace(p+strlen(setcookie));
814                 for(; *p; p=skipspace(p)){
815                         if((e = parsecookie(&c, p, &p, isns, dom, path)) != nil){
816                                 if(debug)
817                                         fprint(2, "parse cookie: %s\n", e);
818                                 break;
819                         }
820                         if((e = isbadcookie(&c, dom, path)) != nil){
821                                 if(debug)
822                                         fprint(2, "reject cookie; %s\n", e);
823                                 continue;
824                         }
825                         addcookie(jar, &c);
826                         n++;
827                 }
828         }
829         return n;
830 }
831
832 static char*
833 skipquoted(char *s)
834 {
835         /*
836          * Sec 2.2 of RFC2616 defines a "quoted-string" as:
837          *
838          *  quoted-string  = ( <"> *(qdtext | quoted-pair ) <"> )
839          *  qdtext         = <any TEXT except <">>
840          *  quoted-pair    = "\" CHAR
841          *
842          * TEXT is any octet except CTLs, but including LWS;
843          * LWS is [CR LF] 1*(SP | HT);
844          * CHARs are ASCII octets 0-127;  (NOTE: we reject 0's)
845          * CTLs are octets 0-31 and 127;
846          */
847         if(*s != '"')
848                 return s;
849
850         for(s++; 32 <= *s && *s < 127 && *s != '"'; s++)
851                 if(*s == '\\' && *(s+1) != '\0')
852                         s++;
853         return s;
854 }
855
856 static char*
857 skiptoken(char *s)
858 {
859         /*
860          * Sec 2.2 of RFC2616 defines a "token" as
861          *  1*<any CHAR except CTLs or separators>;
862          * CHARs are ASCII octets 0-127;
863          * CTLs are octets 0-31 and 127;
864          * separators are "()<>@,;:\/[]?={}", double-quote, SP (32), and HT (9)
865          */
866         while(32 <= *s && *s < 127 && strchr("()<>@,;:[]?={}\" \t\\", *s)==nil)
867                 s++;
868
869         return s;
870 }
871
872 static char*
873 skipvalue(char *s, int isns)
874 {
875         char *t;
876
877         /*
878          * An RFC2109 value is an HTTP token or an HTTP quoted string.
879          * Netscape servers ignore the spec and rely on semicolons, apparently.
880          */
881         if(isns){
882                 if((t = strchr(s, ';')) == nil)
883                         t = s+strlen(s);
884                 return t;
885         }
886         if(*s == '"')
887                 return skipquoted(s);
888         return skiptoken(s);
889 }
890
891 /*
892  * RMID=80b186bb64c03c65fab767f8; expires=Monday, 10-Feb-2003 04:44:39 GMT; 
893  *      path=/; domain=.nytimes.com
894  */
895 char*
896 parsecookie(Cookie *c, char *p, char **e, int isns, char *dom, char *path)
897 {
898         int i, done;
899         char *t, *u, *attr, *val;
900
901         memset(c, 0, sizeof *c);
902         c->expire = ~0;
903
904         /* NAME=VALUE */
905         t = skiptoken(p);
906         c->name = p;
907         p = skipspace(t);
908         if(*p != '='){
909         Badname:
910                 return "malformed cookie: no NAME=VALUE";
911         }
912         *t = '\0';
913         p = skipspace(p+1);
914         t = skipvalue(p, isns);
915         if(*t)
916                 *t++ = '\0';
917         c->value = p;
918         p = skipspace(t);
919         if(c->name[0]=='\0' || c->value[0]=='\0')
920                 goto Badname;
921
922         done = 0;
923         for(; *p && !done; p=skipspace(p)){
924                 attr = p;
925                 t = skiptoken(p);
926                 u = skipspace(t);
927                 switch(*u){
928                 case '\0':
929                         *t = '\0';
930                         p = val = u;
931                         break;
932                 case ';':
933                         *t = '\0';
934                         val = "";
935                         p = u+1;
936                         break;
937                 case '=':
938                         *t = '\0';
939                         val = skipspace(u+1);
940                         p = skipvalue(val, isns);
941                         if(*p==',')
942                                 done = 1;
943                         if(*p)
944                                 *p++ = '\0';
945                         break;
946                 case ',':
947                         if(!isns){
948                                 val = "";
949                                 p = u;
950                                 *p++ = '\0';
951                                 done = 1;
952                                 break;
953                         }
954                 default:
955                         if(debug)
956                                 fprint(2, "syntax: %s\n", p);
957                         return "syntax error";
958                 }
959                 for(i=0; i<nelem(stab); i++)
960                         if(stab[i].ishttp && cistrcmp(stab[i].s, attr)==0)
961                                 *(char**)((char*)c+stab[i].offset) = val;
962                 if(cistrcmp(attr, "expires") == 0){
963                         if(!isns)
964                                 return "non-netscape cookie has Expires tag";
965                         if(!val[0])
966                                 return "bad expires tag";
967                         c->expire = strtotime(val);
968                         if(c->expire == ~0)
969                                 return "cannot parse netscape expires tag";
970                 }
971                 if(cistrcmp(attr, "max-age") == 0)
972                         c->expire = time(0)+atoi(val);
973                 if(cistrcmp(attr, "secure") == 0)
974                         c->secure = 1;
975         }
976         *e = p;
977
978         if(c->dom){
979                 /* add leading dot for explicit domain */
980                 if(c->dom[0] != '.' && strcmp(ipattr(c->dom), "dom") == 0){
981                         static char ddom[1024];
982
983                         ddom[0] = '.';
984                         ddom[sizeof(ddom)-1] = '\0';
985                         strncpy(ddom+1, c->dom, sizeof(ddom)-2);
986                         c->dom = ddom;
987                 }
988                 c->explicitdom = 1;
989         }else
990                 c->dom = dom;
991         if(c->path)
992                 c->explicitpath = 1;
993         else {
994                 static char dpath[1024];
995
996                 /* implicit path is "directory" of request-uri's path component */
997                 dpath[sizeof(dpath)-1] = '\0';
998                 strncpy(dpath, path, sizeof(dpath)-1);
999                 if((t = strrchr(dpath, '/')) != nil)
1000                         t[1] = '\0';
1001                 c->path = dpath;
1002         }
1003         c->netscapestyle = isns;
1004
1005         return nil;
1006 }
1007
1008 Jar *jar;
1009
1010 enum
1011 {
1012         Xhttp = 1,
1013         Xcookies,
1014
1015         NeedUrl = 0,
1016         HaveUrl,
1017 };
1018
1019 typedef struct Aux Aux;
1020 struct Aux
1021 {
1022         int state;
1023         char *dom;
1024         char *path;
1025         char *inhttp;
1026         char *outhttp;
1027         char *ctext;
1028         int rdoff;
1029 };
1030 enum
1031 {
1032         AuxBuf = 4096,
1033         MaxCtext = 16*1024*1024,
1034 };
1035
1036 void
1037 fsopen(Req *r)
1038 {
1039         char *s, *es;
1040         int i, sz;
1041         Aux *a;
1042
1043         switch((uintptr)r->fid->file->aux){
1044         case Xhttp:
1045                 syncjar(jar);
1046                 a = emalloc9p(sizeof(Aux));
1047                 r->fid->aux = a;
1048                 a->inhttp = emalloc9p(AuxBuf);
1049                 a->outhttp = emalloc9p(AuxBuf);
1050                 break;
1051
1052         case Xcookies:
1053                 syncjar(jar);
1054                 a = emalloc9p(sizeof(Aux));
1055                 r->fid->aux = a;
1056                 if(r->ifcall.mode&OTRUNC){
1057                         a->ctext = emalloc9p(1);
1058                         a->ctext[0] = '\0';
1059                 }else{
1060                         sz = 256*jar->nc+1024;  /* BUG should do better */
1061                         a->ctext = emalloc9p(sz);
1062                         a->ctext[0] = '\0';
1063                         s = a->ctext;
1064                         es = s+sz;
1065                         for(i=0; i<jar->nc; i++)
1066                                 s = seprint(s, es, "%K\n", &jar->c[i]);
1067                 }
1068                 break;
1069         }
1070         respond(r, nil);
1071 }
1072
1073 void
1074 fsread(Req *r)
1075 {
1076         Aux *a;
1077
1078         a = r->fid->aux;
1079         switch((uintptr)r->fid->file->aux){
1080         case Xhttp:
1081                 if(a->state == NeedUrl){
1082                         respond(r, "must write url before read");
1083                         return;
1084                 }
1085                 r->ifcall.offset = a->rdoff;
1086                 readstr(r, a->outhttp);
1087                 a->rdoff += r->ofcall.count;
1088                 respond(r, nil);
1089                 return;
1090
1091         case Xcookies:
1092                 readstr(r, a->ctext);
1093                 respond(r, nil);
1094                 return;
1095
1096         default:
1097                 respond(r, "bug in webcookies");
1098                 return;
1099         }
1100 }
1101
1102 void
1103 fswrite(Req *r)
1104 {
1105         Aux *a;
1106         int i, sz, hlen, issecure;
1107         char buf[1024], *p;
1108         Jar *j;
1109
1110         a = r->fid->aux;
1111         switch((uintptr)r->fid->file->aux){
1112         case Xhttp:
1113                 if(a->state == NeedUrl){
1114                         if(r->ifcall.count >= sizeof buf){
1115                                 respond(r, "url too long");
1116                                 return;
1117                         }
1118                         memmove(buf, r->ifcall.data, r->ifcall.count);
1119                         buf[r->ifcall.count] = '\0';
1120                         issecure = 0;
1121                         if(cistrncmp(buf, "http://", 7) == 0)
1122                                 hlen = 7;
1123                         else if(cistrncmp(buf, "https://", 8) == 0){
1124                                 hlen = 8;
1125                                 issecure = 1;
1126                         }else{
1127                                 respond(r, "url must begin http:// or https://");
1128                                 return;
1129                         }
1130                         if(buf[hlen]=='/'){
1131                                 respond(r, "url without host name");
1132                                 return;
1133                         }
1134                         p = strchr(buf+hlen, '/');
1135                         if(p == nil)
1136                                 a->path = estrdup9p("/");
1137                         else {
1138                                 a->path = estrdup9p(p);
1139                                 *p = '\0';
1140
1141                                 if((p = strchr(a->path, '#')) != nil)
1142                                         *p = '\0';
1143                                 if((p = strchr(a->path, '?')) != nil)
1144                                         *p = '\0';
1145                         }
1146                         a->dom = estrdup9p(buf+hlen);
1147                         a->state = HaveUrl;
1148                         j = cookiesearch(jar, a->dom, a->path, issecure);
1149                         if(debug){
1150                                 fprint(2, "search %s %s got %p\n", a->dom, a->path, j);
1151                                 if(j){
1152                                         fprint(2, "%d cookies\n", j->nc);
1153                                         for(i=0; i<j->nc; i++)
1154                                                 fprint(2, "%K\n", &j->c[i]);
1155                                 }
1156                         }
1157                         snprint(a->outhttp, AuxBuf, "%J", j);
1158                         closejar(j);
1159                 }else{
1160                         if(strlen(a->inhttp)+r->ifcall.count >= AuxBuf){
1161                                 respond(r, "http headers too large");
1162                                 return;
1163                         }
1164                         memmove(a->inhttp+strlen(a->inhttp), r->ifcall.data, r->ifcall.count);
1165                 }
1166                 r->ofcall.count = r->ifcall.count;
1167                 respond(r, nil);
1168                 return;
1169
1170         case Xcookies:
1171                 sz = r->ifcall.count+r->ifcall.offset;
1172                 if(sz > strlen(a->ctext)){
1173                         if(sz >= MaxCtext){
1174                                 respond(r, "cookie file too large");
1175                                 return;
1176                         }
1177                         a->ctext = erealloc9p(a->ctext, sz+1);
1178                         a->ctext[sz] = '\0';
1179                 }
1180                 memmove(a->ctext+r->ifcall.offset, r->ifcall.data, r->ifcall.count);
1181                 r->ofcall.count = r->ifcall.count;
1182                 respond(r, nil);
1183                 return;
1184
1185         default:
1186                 respond(r, "bug in webcookies");
1187                 return;
1188         }
1189 }
1190
1191 void
1192 fsdestroyfid(Fid *fid)
1193 {
1194         char *p, *nextp;
1195         Aux *a;
1196         int i;
1197
1198         a = fid->aux;
1199         if(a == nil)
1200                 return;
1201         switch((uintptr)fid->file->aux){
1202         case Xhttp:
1203                 parsehttp(jar, a->inhttp, a->dom, a->path);
1204                 break;
1205         case Xcookies:
1206                 for(i=0; i<jar->nc; i++)
1207                         jar->c[i].mark = 1;
1208                 for(p=a->ctext; *p; p=nextp){
1209                         if((nextp = strchr(p, '\n')) != nil)
1210                                 *nextp++ = '\0';
1211                         else
1212                                 nextp = "";
1213                         addtojar(jar, p, 0);
1214                 }
1215                 for(i=0; i<jar->nc; i++)
1216                         if(jar->c[i].mark)
1217                                 delcookie(jar, &jar->c[i]);
1218                 break;
1219         }
1220         if(jar->dirty)
1221                 syncjar(jar);
1222         free(a->dom);
1223         free(a->path);
1224         free(a->inhttp);
1225         free(a->outhttp);
1226         free(a->ctext);
1227         free(a);
1228 }
1229
1230 void
1231 fsend(Srv*)
1232 {
1233         closejar(jar);
1234 }
1235
1236 Srv fs = 
1237 {
1238 .open=          fsopen,
1239 .read=          fsread,
1240 .write=         fswrite,
1241 .destroyfid=    fsdestroyfid,
1242 .end=           fsend,
1243 };
1244
1245 void
1246 usage(void)
1247 {
1248         fprint(2, "usage: webcookies [-f file] [-m mtpt] [-s service]\n");
1249         exits("usage");
1250 }
1251         
1252 void
1253 main(int argc, char **argv)
1254 {
1255         char *file, *mtpt, *home, *srv;
1256
1257         file = nil;
1258         srv = nil;
1259         mtpt = "/mnt/webcookies";
1260         ARGBEGIN{
1261         case 'D':
1262                 chatty9p++;
1263                 break;
1264         case 'd':
1265                 debug = 1;
1266                 break;
1267         case 'f':
1268                 file = EARGF(usage());
1269                 break;
1270         case 's':
1271                 srv = EARGF(usage());
1272                 break;
1273         case 'm':
1274                 mtpt = EARGF(usage());
1275                 break;
1276         default:
1277                 usage();
1278         }ARGEND
1279
1280         if(argc != 0)
1281                 usage();
1282
1283         quotefmtinstall();
1284         fmtinstall('J', jarfmt);
1285         fmtinstall('K', cookiefmt);
1286
1287         if(file == nil){
1288                 home = getenv("home");
1289                 if(home == nil)
1290                         sysfatal("no cookie file specified and no $home");
1291                 file = emalloc9p(strlen(home)+30);
1292                 strcpy(file, home);
1293                 strcat(file, "/lib/webcookies");
1294         }
1295
1296         jar = readjar(file);
1297         if(jar == nil)
1298                 sysfatal("readjar: %r");
1299
1300         fs.tree = alloctree("cookie", "cookie", DMDIR|0555, nil);
1301         closefile(createfile(fs.tree->root, "http", "cookie", 0666, (void*)Xhttp));
1302         closefile(createfile(fs.tree->root, "cookies", "cookie", 0666, (void*)Xcookies));
1303
1304         postmountsrv(&fs, srv, mtpt, MREPL);
1305         exits(nil);
1306 }