webcookies.c 23 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253
  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. tm.yday = 0;
  635. return tm2sec(&tm);
  636. }
  637. /*
  638. * skip linear whitespace. we're a bit more lenient than RFC2616 2.2.
  639. */
  640. char*
  641. skipspace(char *s)
  642. {
  643. while(*s=='\r' || *s=='\n' || *s==' ' || *s=='\t')
  644. s++;
  645. return s;
  646. }
  647. /*
  648. * Try to identify old netscape headers.
  649. * The old headers:
  650. * - didn't allow spaces around the '='
  651. * - used an 'Expires' attribute
  652. * - had no 'Version' attribute
  653. * - had no quotes
  654. * - allowed whitespace in values
  655. * - apparently separated attr/value pairs with ';' exclusively
  656. */
  657. int
  658. isnetscape(char *hdr)
  659. {
  660. char *s;
  661. for(s=hdr; (s=strchr(s, '=')) != nil; s++){
  662. if(isspace(s[1]) || (s > hdr && isspace(s[-1])))
  663. return 0;
  664. if(s[1]=='"')
  665. return 0;
  666. }
  667. if(cistrstr(hdr, "version="))
  668. return 0;
  669. return 1;
  670. }
  671. /*
  672. * Parse HTTP response headers, adding cookies to jar.
  673. * Overwrites the headers.
  674. */
  675. char* parsecookie(Cookie*, char*, char**, int, char*, char*);
  676. int
  677. parsehttp(Jar *jar, char *hdr, char *dom, char *path)
  678. {
  679. static char setcookie[] = "Set-Cookie:";
  680. char *e, *p, *nextp;
  681. Cookie c;
  682. int isns, n;
  683. isns = isnetscape(hdr);
  684. n = 0;
  685. for(p=hdr; p; p=nextp){
  686. p = skipspace(p);
  687. if(*p == '\0')
  688. break;
  689. nextp = strchr(p, '\n');
  690. if(nextp != nil)
  691. *nextp++ = '\0';
  692. if(debug)
  693. fprint(2, "?%s\n", p);
  694. if(cistrncmp(p, setcookie, strlen(setcookie)) != 0)
  695. continue;
  696. if(debug)
  697. fprint(2, "%s\n", p);
  698. p = skipspace(p+strlen(setcookie));
  699. for(; *p; p=skipspace(p)){
  700. if((e = parsecookie(&c, p, &p, isns, dom, path)) != nil){
  701. if(debug)
  702. fprint(2, "parse cookie: %s\n", e);
  703. break;
  704. }
  705. if((e = isbadcookie(&c, dom, path)) != nil){
  706. if(debug)
  707. fprint(2, "reject cookie; %s\n", e);
  708. continue;
  709. }
  710. addcookie(jar, &c);
  711. n++;
  712. }
  713. }
  714. return n;
  715. }
  716. static char*
  717. skipquoted(char *s)
  718. {
  719. /*
  720. * Sec 2.2 of RFC2616 defines a "quoted-string" as:
  721. *
  722. * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
  723. * qdtext = <any TEXT except <">>
  724. * quoted-pair = "\" CHAR
  725. *
  726. * TEXT is any octet except CTLs, but including LWS;
  727. * LWS is [CR LF] 1*(SP | HT);
  728. * CHARs are ASCII octets 0-127; (NOTE: we reject 0's)
  729. * CTLs are octets 0-31 and 127;
  730. */
  731. if(*s != '"')
  732. return s;
  733. for(s++; 32 <= *s && *s < 127 && *s != '"'; s++)
  734. if(*s == '\\' && *(s+1) != '\0')
  735. s++;
  736. return s;
  737. }
  738. static char*
  739. skiptoken(char *s)
  740. {
  741. /*
  742. * Sec 2.2 of RFC2616 defines a "token" as
  743. * 1*<any CHAR except CTLs or separators>;
  744. * CHARs are ASCII octets 0-127;
  745. * CTLs are octets 0-31 and 127;
  746. * separators are "()<>@,;:\/[]?={}", double-quote, SP (32), and HT (9)
  747. */
  748. while(32 <= *s && *s < 127 && strchr("()<>@,;:[]?={}\" \t\\", *s)==nil)
  749. s++;
  750. return s;
  751. }
  752. static char*
  753. skipvalue(char *s, int isns)
  754. {
  755. char *t;
  756. /*
  757. * An RFC2109 value is an HTTP token or an HTTP quoted string.
  758. * Netscape servers ignore the spec and rely on semicolons, apparently.
  759. */
  760. if(isns){
  761. if((t = strchr(s, ';')) == nil)
  762. t = s+strlen(s);
  763. return t;
  764. }
  765. if(*s == '"')
  766. return skipquoted(s);
  767. return skiptoken(s);
  768. }
  769. /*
  770. * RMID=80b186bb64c03c65fab767f8; expires=Monday, 10-Feb-2003 04:44:39 GMT;
  771. * path=/; domain=.nytimes.com
  772. */
  773. char*
  774. parsecookie(Cookie *c, char *p, char **e, int isns, char *dom, char *path)
  775. {
  776. int i, done;
  777. char *t, *u, *attr, *val;
  778. memset(c, 0, sizeof *c);
  779. /* NAME=VALUE */
  780. t = skiptoken(p);
  781. c->name = p;
  782. p = skipspace(t);
  783. if(*p != '='){
  784. Badname:
  785. return "malformed cookie: no NAME=VALUE";
  786. }
  787. *t = '\0';
  788. p = skipspace(p+1);
  789. t = skipvalue(p, isns);
  790. if(*t)
  791. *t++ = '\0';
  792. c->value = p;
  793. p = skipspace(t);
  794. if(c->name[0]=='\0' || c->value[0]=='\0')
  795. goto Badname;
  796. done = 0;
  797. for(; *p && !done; p=skipspace(p)){
  798. attr = p;
  799. t = skiptoken(p);
  800. u = skipspace(t);
  801. switch(*u){
  802. case ';':
  803. *t = '\0';
  804. val = "";
  805. p = u+1;
  806. break;
  807. case '=':
  808. *t = '\0';
  809. val = skipspace(u+1);
  810. p = skipvalue(val, isns);
  811. if(*p==',')
  812. done = 1;
  813. if(*p)
  814. *p++ = '\0';
  815. break;
  816. case ',':
  817. if(!isns){
  818. val = "";
  819. p = u;
  820. *p++ = '\0';
  821. done = 1;
  822. break;
  823. }
  824. default:
  825. if(debug)
  826. fprint(2, "syntax: %s\n", p);
  827. return "syntax error";
  828. }
  829. for(i=0; i<nelem(stab); i++)
  830. if(stab[i].ishttp && cistrcmp(stab[i].s, attr)==0)
  831. *(char**)((ulong)c+stab[i].offset) = val;
  832. if(cistrcmp(attr, "expires") == 0){
  833. if(!isns)
  834. return "non-netscape cookie has Expires tag";
  835. if(!val[0])
  836. return "bad expires tag";
  837. c->expire = strtotime(val);
  838. if(c->expire == ~0)
  839. return "cannot parse netscape expires tag";
  840. }
  841. if(cistrcmp(attr, "max-age") == 0)
  842. c->expire = time(0)+atoi(val);
  843. if(cistrcmp(attr, "secure") == 0)
  844. c->secure = 1;
  845. }
  846. if(c->dom)
  847. c->explicitdom = 1;
  848. else
  849. c->dom = dom;
  850. if(c->path)
  851. c->explicitpath = 1;
  852. else
  853. c->path = path;
  854. c->netscapestyle = isns;
  855. *e = p;
  856. return nil;
  857. }
  858. Jar *jar;
  859. enum
  860. {
  861. Xhttp = 1,
  862. Xcookies,
  863. NeedUrl = 0,
  864. HaveUrl,
  865. };
  866. typedef struct Aux Aux;
  867. struct Aux
  868. {
  869. int state;
  870. char *dom;
  871. char *path;
  872. char *inhttp;
  873. char *outhttp;
  874. char *ctext;
  875. int rdoff;
  876. };
  877. enum
  878. {
  879. AuxBuf = 4096,
  880. MaxCtext = 16*1024*1024,
  881. };
  882. void
  883. fsopen(Req *r)
  884. {
  885. char *s, *es;
  886. int i, sz;
  887. Aux *a;
  888. switch((int)r->fid->file->aux){
  889. case Xhttp:
  890. syncjar(jar);
  891. a = emalloc9p(sizeof(Aux));
  892. r->fid->aux = a;
  893. a->inhttp = emalloc9p(AuxBuf);
  894. a->outhttp = emalloc9p(AuxBuf);
  895. break;
  896. case Xcookies:
  897. syncjar(jar);
  898. a = emalloc9p(sizeof(Aux));
  899. r->fid->aux = a;
  900. if(r->ifcall.mode&OTRUNC){
  901. a->ctext = emalloc9p(1);
  902. a->ctext[0] = '\0';
  903. }else{
  904. sz = 256*jar->nc+1024; /* BUG should do better */
  905. a->ctext = emalloc9p(sz);
  906. a->ctext[0] = '\0';
  907. s = a->ctext;
  908. es = s+sz;
  909. for(i=0; i<jar->nc; i++)
  910. s = seprint(s, es, "%K\n", &jar->c[i]);
  911. }
  912. break;
  913. }
  914. respond(r, nil);
  915. }
  916. void
  917. fsread(Req *r)
  918. {
  919. Aux *a;
  920. a = r->fid->aux;
  921. switch((int)r->fid->file->aux){
  922. case Xhttp:
  923. if(a->state == NeedUrl){
  924. respond(r, "must write url before read");
  925. return;
  926. }
  927. r->ifcall.offset = a->rdoff;
  928. readstr(r, a->outhttp);
  929. a->rdoff += r->ofcall.count;
  930. respond(r, nil);
  931. return;
  932. case Xcookies:
  933. readstr(r, a->ctext);
  934. respond(r, nil);
  935. return;
  936. default:
  937. respond(r, "bug in webcookies");
  938. return;
  939. }
  940. }
  941. void
  942. fswrite(Req *r)
  943. {
  944. Aux *a;
  945. int i, sz, hlen, issecure;
  946. char buf[1024], *p;
  947. Jar *j;
  948. a = r->fid->aux;
  949. switch((int)r->fid->file->aux){
  950. case Xhttp:
  951. if(a->state == NeedUrl){
  952. if(r->ifcall.count >= sizeof buf){
  953. respond(r, "url too long");
  954. return;
  955. }
  956. memmove(buf, r->ifcall.data, r->ifcall.count);
  957. buf[r->ifcall.count] = '\0';
  958. issecure = 0;
  959. if(cistrncmp(buf, "http://", 7) == 0)
  960. hlen = 7;
  961. else if(cistrncmp(buf, "https://", 8) == 0){
  962. hlen = 8;
  963. issecure = 1;
  964. }else{
  965. respond(r, "url must begin http:// or https://");
  966. return;
  967. }
  968. if(buf[hlen]=='/'){
  969. respond(r, "url without host name");
  970. return;
  971. }
  972. p = strchr(buf+hlen, '/');
  973. if(p == nil)
  974. a->path = estrdup9p("/");
  975. else{
  976. a->path = estrdup9p(p);
  977. *p = '\0';
  978. }
  979. a->dom = estrdup9p(buf+hlen);
  980. a->state = HaveUrl;
  981. j = cookiesearch(jar, a->dom, a->path, issecure);
  982. if(debug){
  983. fprint(2, "search %s %s got %p\n", a->dom, a->path, j);
  984. if(j){
  985. fprint(2, "%d cookies\n", j->nc);
  986. for(i=0; i<j->nc; i++)
  987. fprint(2, "%K\n", &j->c[i]);
  988. }
  989. }
  990. snprint(a->outhttp, AuxBuf, "%J", j);
  991. if(j)
  992. closejar(j);
  993. }else{
  994. if(strlen(a->inhttp)+r->ifcall.count >= AuxBuf){
  995. respond(r, "http headers too large");
  996. return;
  997. }
  998. memmove(a->inhttp+strlen(a->inhttp), r->ifcall.data, r->ifcall.count);
  999. }
  1000. r->ofcall.count = r->ifcall.count;
  1001. respond(r, nil);
  1002. return;
  1003. case Xcookies:
  1004. sz = r->ifcall.count+r->ifcall.offset;
  1005. if(sz > strlen(a->ctext)){
  1006. if(sz >= MaxCtext){
  1007. respond(r, "cookie file too large");
  1008. return;
  1009. }
  1010. a->ctext = erealloc9p(a->ctext, sz+1);
  1011. a->ctext[sz] = '\0';
  1012. }
  1013. memmove(a->ctext+r->ifcall.offset, r->ifcall.data, r->ifcall.count);
  1014. r->ofcall.count = r->ifcall.count;
  1015. respond(r, nil);
  1016. return;
  1017. default:
  1018. respond(r, "bug in webcookies");
  1019. return;
  1020. }
  1021. }
  1022. void
  1023. fsdestroyfid(Fid *fid)
  1024. {
  1025. char *p, *nextp;
  1026. Aux *a;
  1027. int i;
  1028. a = fid->aux;
  1029. if(a == nil)
  1030. return;
  1031. switch((int)fid->file->aux){
  1032. case Xhttp:
  1033. parsehttp(jar, a->inhttp, a->dom, a->path);
  1034. break;
  1035. case Xcookies:
  1036. for(i=0; i<jar->nc; i++)
  1037. jar->c[i].mark = 1;
  1038. for(p=a->ctext; *p; p=nextp){
  1039. if((nextp = strchr(p, '\n')) != nil)
  1040. *nextp++ = '\0';
  1041. else
  1042. nextp = "";
  1043. addtojar(jar, p, 0);
  1044. }
  1045. for(i=0; i<jar->nc; i++)
  1046. if(jar->c[i].mark)
  1047. delcookie(jar, &jar->c[i]);
  1048. break;
  1049. }
  1050. syncjar(jar);
  1051. free(a->dom);
  1052. free(a->path);
  1053. free(a->inhttp);
  1054. free(a->outhttp);
  1055. free(a->ctext);
  1056. free(a);
  1057. }
  1058. void
  1059. fsend(Srv*)
  1060. {
  1061. closejar(jar);
  1062. }
  1063. Srv fs =
  1064. {
  1065. .open= fsopen,
  1066. .read= fsread,
  1067. .write= fswrite,
  1068. .destroyfid= fsdestroyfid,
  1069. .end= fsend,
  1070. };
  1071. void
  1072. usage(void)
  1073. {
  1074. fprint(2, "usage: webcookies [-f file] [-m mtpt] [-s service]\n");
  1075. exits("usage");
  1076. }
  1077. void
  1078. main(int argc, char **argv)
  1079. {
  1080. char *file, *mtpt, *home, *srv;
  1081. file = nil;
  1082. srv = nil;
  1083. mtpt = "/mnt/webcookies";
  1084. ARGBEGIN{
  1085. case 'D':
  1086. chatty9p++;
  1087. break;
  1088. case 'd':
  1089. debug = 1;
  1090. break;
  1091. case 'f':
  1092. file = EARGF(usage());
  1093. break;
  1094. case 's':
  1095. srv = EARGF(usage());
  1096. break;
  1097. case 'm':
  1098. mtpt = EARGF(usage());
  1099. break;
  1100. default:
  1101. usage();
  1102. }ARGEND
  1103. if(argc != 0)
  1104. usage();
  1105. quotefmtinstall();
  1106. fmtinstall('J', jarfmt);
  1107. fmtinstall('K', cookiefmt);
  1108. if(file == nil){
  1109. home = getenv("home");
  1110. if(home == nil)
  1111. sysfatal("no cookie file specified and no $home");
  1112. file = emalloc9p(strlen(home)+30);
  1113. strcpy(file, home);
  1114. strcat(file, "/lib/webcookies");
  1115. }
  1116. if(access(file, AEXIST) < 0)
  1117. close(create(file, OWRITE, 0666));
  1118. jar = readjar(file);
  1119. if(jar == nil)
  1120. sysfatal("readjar: %r");
  1121. fs.tree = alloctree("cookie", "cookie", DMDIR|0555, nil);
  1122. closefile(createfile(fs.tree->root, "http", "cookie", 0666, (void*)Xhttp));
  1123. closefile(createfile(fs.tree->root, "cookies", "cookie", 0666, (void*)Xcookies));
  1124. postmountsrv(&fs, srv, mtpt, MREPL);
  1125. exits(nil);
  1126. }