webcookies.c 23 KB

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