webcookies.c 24 KB

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