http.c 10 KB

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