http.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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. #include <u.h>
  10. #include <libc.h>
  11. #include <bio.h>
  12. #include <ip.h>
  13. #include <plumb.h>
  14. #include <thread.h>
  15. #include <fcall.h>
  16. #include <9p.h>
  17. #include <libsec.h>
  18. #include <auth.h>
  19. #include "dat.h"
  20. #include "fns.h"
  21. char PostContentType[] = "application/x-www-form-urlencoded";
  22. int httpdebug;
  23. typedef struct HttpState HttpState;
  24. struct HttpState
  25. {
  26. int fd;
  27. Client *c;
  28. char *location;
  29. char *setcookie;
  30. char *netaddr;
  31. char *credentials;
  32. char autherror[ERRMAX];
  33. Ibuf b;
  34. };
  35. static void
  36. location(HttpState *hs, char *value)
  37. {
  38. if(hs->location == nil)
  39. hs->location = estrdup(value);
  40. }
  41. static void
  42. contenttype(HttpState *hs, char *value)
  43. {
  44. if(hs->c->contenttype != nil)
  45. free(hs->c->contenttype);
  46. hs->c->contenttype = estrdup(value);
  47. }
  48. static void
  49. setcookie(HttpState *hs, char *value)
  50. {
  51. char *s, *t;
  52. Fmt f;
  53. s = hs->setcookie;
  54. fmtstrinit(&f);
  55. if(s)
  56. fmtprint(&f, "%s", s);
  57. fmtprint(&f, "set-cookie: ");
  58. fmtprint(&f, "%s", value);
  59. fmtprint(&f, "\n");
  60. t = fmtstrflush(&f);
  61. if(t){
  62. free(s);
  63. hs->setcookie = t;
  64. }
  65. }
  66. static char*
  67. unquote(char *s, char **ps)
  68. {
  69. char *p;
  70. if(*s != '"'){
  71. p = strpbrk(s, " \t\r\n");
  72. *p++ = 0;
  73. *ps = p;
  74. return s;
  75. }
  76. for(p=s+1; *p; p++){
  77. if(*p == '\"'){
  78. *p++ = 0;
  79. break;
  80. }
  81. if(*p == '\\' && *(p+1)){
  82. p++;
  83. continue;
  84. }
  85. }
  86. memmove(s, s+1, p-(s+1));
  87. s[p-(s+1)] = 0;
  88. *ps = p;
  89. return s;
  90. }
  91. static char*
  92. servername(char *addr)
  93. {
  94. char *p;
  95. if(strncmp(addr, "tcp!", 4) == 0
  96. || strncmp(addr, "net!", 4) == 0)
  97. addr += 4;
  98. addr = estrdup(addr);
  99. p = addr+strlen(addr);
  100. if(p>addr && *(p-1) == 's')
  101. p--;
  102. if(p>addr+5 && strcmp(p-5, "!http") == 0)
  103. p[-5] = 0;
  104. return addr;
  105. }
  106. void
  107. wwwauthenticate(HttpState *hs, char *line)
  108. {
  109. char cred[64], *user, *pass, *realm, *s, *spec, *name;
  110. Fmt fmt;
  111. UserPasswd *up;
  112. spec = nil;
  113. up = nil;
  114. cred[0] = 0;
  115. hs->autherror[0] = 0;
  116. if(cistrncmp(line, "basic ", 6) != 0){
  117. werrstr("unknown auth: %s", line);
  118. goto error;
  119. }
  120. line += 6;
  121. if(cistrncmp(line, "realm=", 6) != 0){
  122. werrstr("missing realm: %s", line);
  123. goto error;
  124. }
  125. line += 6;
  126. user = hs->c->url->user;
  127. pass = hs->c->url->passwd;
  128. if(user==nil || pass==nil){
  129. realm = unquote(line, &line);
  130. fmtstrinit(&fmt);
  131. name = servername(hs->netaddr);
  132. fmtprint(&fmt, "proto=pass service=http server=%q realm=%q", name, realm);
  133. free(name);
  134. if(hs->c->url->user)
  135. fmtprint(&fmt, " user=%q", hs->c->url->user);
  136. spec = fmtstrflush(&fmt);
  137. if(spec == nil)
  138. goto error;
  139. if((up = auth_getuserpasswd(nil, "%s", spec)) == nil)
  140. goto error;
  141. user = up->user;
  142. pass = up->passwd;
  143. }
  144. if((s = smprint("%s:%s", user, pass)) == nil)
  145. goto error;
  146. free(up);
  147. enc64(cred, sizeof(cred), (uint8_t*)s, strlen(s));
  148. memset(s, 0, strlen(s));
  149. free(s);
  150. hs->credentials = smprint("Basic %s", cred);
  151. if(hs->credentials == nil)
  152. goto error;
  153. return;
  154. error:
  155. free(up);
  156. free(spec);
  157. snprint(hs->autherror, sizeof hs->autherror, "%r");
  158. fprint(2, "%s: Authentication failed: %r\n", argv0);
  159. }
  160. struct {
  161. char *name; /* Case-insensitive */
  162. void (*fn)(HttpState *hs, char *value);
  163. } hdrtab[] = {
  164. { "location:", location },
  165. { "content-type:", contenttype },
  166. { "set-cookie:", setcookie },
  167. { "www-authenticate:", wwwauthenticate },
  168. };
  169. static int
  170. httprcode(HttpState *hs)
  171. {
  172. int n;
  173. char *p;
  174. char buf[256];
  175. n = readline(&hs->b, buf, sizeof(buf)-1);
  176. if(n <= 0)
  177. return n;
  178. if(httpdebug)
  179. fprint(2, "-> %s\n", buf);
  180. p = strchr(buf, ' ');
  181. if(memcmp(buf, "HTTP/", 5) != 0 || p == nil){
  182. werrstr("bad response from server");
  183. return -1;
  184. }
  185. buf[n] = 0;
  186. return atoi(p+1);
  187. }
  188. /*
  189. * read a single mime header, collect continuations.
  190. *
  191. * this routine assumes that there is a blank line twixt
  192. * the header and the message body, otherwise bytes will
  193. * be lost.
  194. */
  195. static int
  196. getheader(HttpState *hs, char *buf, int n)
  197. {
  198. char *p, *e;
  199. int i;
  200. n--;
  201. p = buf;
  202. for(e = p + n; ; p += i){
  203. i = readline(&hs->b, p, e-p);
  204. if(i < 0)
  205. return i;
  206. if(p == buf){
  207. /* first line */
  208. if(strchr(buf, ':') == nil)
  209. break; /* end of headers */
  210. } else {
  211. /* continuation line */
  212. if(*p != ' ' && *p != '\t'){
  213. unreadline(&hs->b, p);
  214. *p = 0;
  215. break; /* end of this header */
  216. }
  217. }
  218. }
  219. if(httpdebug)
  220. fprint(2, "-> %s\n", buf);
  221. return p-buf;
  222. }
  223. static int
  224. httpheaders(HttpState *hs)
  225. {
  226. char buf[2048];
  227. char *p;
  228. int i, n;
  229. for(;;){
  230. n = getheader(hs, buf, sizeof(buf));
  231. if(n < 0)
  232. return -1;
  233. if(n == 0)
  234. return 0;
  235. // print("http header: '%.*s'\n", n, buf);
  236. for(i = 0; i < nelem(hdrtab); i++){
  237. n = strlen(hdrtab[i].name);
  238. if(cistrncmp(buf, hdrtab[i].name, n) == 0){
  239. /* skip field name and leading white */
  240. p = buf + n;
  241. while(*p == ' ' || *p == '\t')
  242. p++;
  243. (*hdrtab[i].fn)(hs, p);
  244. break;
  245. }
  246. }
  247. }
  248. }
  249. int
  250. httpopen(Client *c, Url *url)
  251. {
  252. int fd, code, redirect, authenticate;
  253. char *cookies;
  254. Ioproc *io;
  255. HttpState *hs;
  256. char *service;
  257. if(httpdebug)
  258. fprint(2, "httpopen\n");
  259. io = c->io;
  260. hs = emalloc(sizeof(*hs));
  261. hs->c = c;
  262. if(url->port)
  263. service = url->port;
  264. else
  265. service = url->scheme;
  266. hs->netaddr = estrdup(netmkaddr(url->host, 0, service));
  267. c->aux = hs;
  268. if(httpdebug){
  269. fprint(2, "dial %s\n", hs->netaddr);
  270. fprint(2, "dial port: %s\n", url->port);
  271. }
  272. fd = iotlsdial(io, hs->netaddr, 0, 0, 0, url->ischeme==UShttps);
  273. if(fd < 0){
  274. Error:
  275. if(httpdebug)
  276. fprint(2, "iodial: %r\n");
  277. free(hs->location);
  278. free(hs->setcookie);
  279. free(hs->netaddr);
  280. free(hs->credentials);
  281. if(fd >= 0)
  282. ioclose(io, hs->fd);
  283. hs->fd = -1;
  284. free(hs);
  285. c->aux = nil;
  286. return -1;
  287. }
  288. hs->fd = fd;
  289. if(httpdebug)
  290. fprint(2, "<- %s %s HTTP/1.0\n<- Host: %s\n",
  291. c->havepostbody? "POST": "GET", url->http.page_spec, url->host);
  292. ioprint(io, fd, "%s %s HTTP/1.0\r\nHost: %s\r\n",
  293. c->havepostbody? "POST" : "GET", url->http.page_spec, url->host);
  294. if(httpdebug)
  295. fprint(2, "<- User-Agent: %s\n", c->ctl.useragent);
  296. if(c->ctl.useragent)
  297. ioprint(io, fd, "User-Agent: %s\r\n", c->ctl.useragent);
  298. if(c->ctl.sendcookies){
  299. /* should we use url->page here? sometimes it is nil. */
  300. cookies = httpcookies(url->host, url->http.page_spec,
  301. url->ischeme == UShttps);
  302. if(cookies && cookies[0])
  303. ioprint(io, fd, "%s", cookies);
  304. if(httpdebug)
  305. fprint(2, "<- %s", cookies);
  306. free(cookies);
  307. }
  308. if(c->havepostbody){
  309. ioprint(io, fd, "Content-type: %s\r\n", PostContentType);
  310. ioprint(io, fd, "Content-length: %ud\r\n", c->npostbody);
  311. if(httpdebug){
  312. fprint(2, "<- Content-type: %s\n", PostContentType);
  313. fprint(2, "<- Content-length: %ud\n", c->npostbody);
  314. }
  315. }
  316. if(c->authenticate){
  317. ioprint(io, fd, "Authorization: %s\r\n", c->authenticate);
  318. if(httpdebug)
  319. fprint(2, "<- Authorization: %s\n", c->authenticate);
  320. }
  321. ioprint(io, fd, "\r\n");
  322. if(c->havepostbody)
  323. if(iowrite(io, fd, c->postbody, c->npostbody) != c->npostbody)
  324. goto Error;
  325. redirect = 0;
  326. authenticate = 0;
  327. initibuf(&hs->b, io, fd);
  328. code = httprcode(hs);
  329. switch(code){
  330. case -1: /* connection timed out */
  331. goto Error;
  332. /*
  333. case Eof:
  334. werrstr("EOF from HTTP server");
  335. goto Error;
  336. */
  337. case 200: /* OK */
  338. case 201: /* Created */
  339. case 202: /* Accepted */
  340. case 204: /* No Content */
  341. case 205: /* Reset Content */
  342. #ifdef NOT_DEFINED
  343. if(ofile == nil && r->start != 0)
  344. sysfatal("page changed underfoot");
  345. #endif
  346. break;
  347. case 206: /* Partial Content */
  348. werrstr("Partial Content (206)");
  349. goto Error;
  350. case 301: /* Moved Permanently */
  351. case 302: /* Moved Temporarily */
  352. case 303: /* See Other */
  353. case 307: /* Temporary Redirect */
  354. redirect = 1;
  355. break;
  356. case 304: /* Not Modified */
  357. break;
  358. case 400: /* Bad Request */
  359. werrstr("Bad Request (400)");
  360. goto Error;
  361. case 401: /* Unauthorized */
  362. if(c->authenticate){
  363. werrstr("Authentication failed (401)");
  364. goto Error;
  365. }
  366. authenticate = 1;
  367. break;
  368. case 402: /* Payment Required */
  369. werrstr("Payment Required (402)");
  370. goto Error;
  371. case 403: /* Forbidden */
  372. werrstr("Forbidden by server (403)");
  373. goto Error;
  374. case 404: /* Not Found */
  375. werrstr("Not found on server (404)");
  376. goto Error;
  377. case 405: /* Method Not Allowed */
  378. werrstr("Method not allowed (405)");
  379. goto Error;
  380. case 406: /* Not Acceptable */
  381. werrstr("Not Acceptable (406)");
  382. goto Error;
  383. case 407: /* Proxy auth */
  384. werrstr("Proxy authentication required (407)");
  385. goto Error;
  386. case 408: /* Request Timeout */
  387. werrstr("Request Timeout (408)");
  388. goto Error;
  389. case 409: /* Conflict */
  390. werrstr("Conflict (409)");
  391. goto Error;
  392. case 410: /* Gone */
  393. werrstr("Gone (410)");
  394. goto Error;
  395. case 411: /* Length Required */
  396. werrstr("Length Required (411)");
  397. goto Error;
  398. case 412: /* Precondition Failed */
  399. werrstr("Precondition Failed (412)");
  400. goto Error;
  401. case 413: /* Request Entity Too Large */
  402. werrstr("Request Entity Too Large (413)");
  403. goto Error;
  404. case 414: /* Request-URI Too Long */
  405. werrstr("Request-URI Too Long (414)");
  406. goto Error;
  407. case 415: /* Unsupported Media Type */
  408. werrstr("Unsupported Media Type (415)");
  409. goto Error;
  410. case 416: /* Requested Range Not Satisfiable */
  411. werrstr("Requested Range Not Satisfiable (416)");
  412. goto Error;
  413. case 417: /* Expectation Failed */
  414. werrstr("Expectation Failed (417)");
  415. goto Error;
  416. case 500: /* Internal server error */
  417. werrstr("Server choked (500)");
  418. goto Error;
  419. case 501: /* Not implemented */
  420. werrstr("Server can't do it (501)");
  421. goto Error;
  422. case 502: /* Bad gateway */
  423. werrstr("Bad gateway (502)");
  424. goto Error;
  425. case 503: /* Service unavailable */
  426. werrstr("Service unavailable (503)");
  427. goto Error;
  428. default:
  429. /* Bogus: we should treat unknown code XYZ as code X00 */
  430. werrstr("Unknown response code %d", code);
  431. goto Error;
  432. }
  433. if(httpheaders(hs) < 0)
  434. goto Error;
  435. if(c->ctl.acceptcookies && hs->setcookie)
  436. httpsetcookie(hs->setcookie, url->host, url->path);
  437. if(authenticate){
  438. if(!hs->credentials){
  439. if(hs->autherror[0])
  440. werrstr("%s", hs->autherror);
  441. else
  442. werrstr("unauthorized; no www-authenticate: header");
  443. goto Error;
  444. }
  445. c->authenticate = hs->credentials;
  446. hs->credentials = nil;
  447. }else if(c->authenticate)
  448. c->authenticate = 0;
  449. if(redirect){
  450. if(!hs->location){
  451. werrstr("redirection without Location: header");
  452. goto Error;
  453. }
  454. c->redirect = hs->location;
  455. hs->location = nil;
  456. }
  457. return 0;
  458. }
  459. int
  460. httpread(Client *c, Req *r)
  461. {
  462. HttpState *hs;
  463. int32_t n;
  464. hs = c->aux;
  465. n = readibuf(&hs->b, r->ofcall.data, r->ifcall.count);
  466. if(n < 0)
  467. return -1;
  468. r->ofcall.count = n;
  469. return 0;
  470. }
  471. void
  472. httpclose(Client *c)
  473. {
  474. HttpState *hs;
  475. hs = c->aux;
  476. if(hs == nil)
  477. return;
  478. if(hs->fd >= 0)
  479. ioclose(c->io, hs->fd);
  480. hs->fd = -1;
  481. free(hs->location);
  482. free(hs->setcookie);
  483. free(hs->netaddr);
  484. free(hs->credentials);
  485. free(hs);
  486. c->aux = nil;
  487. }