uclient-http.c 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  1. /*
  2. * uclient - ustream based protocol client library
  3. *
  4. * Copyright (C) 2014 Felix Fietkau <nbd@openwrt.org>
  5. *
  6. * Permission to use, copy, modify, and/or distribute this software for any
  7. * purpose with or without fee is hereby granted, provided that the above
  8. * copyright notice and this permission notice appear in all copies.
  9. *
  10. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  11. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  12. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  13. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  14. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  15. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  16. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  17. */
  18. #include <sys/socket.h>
  19. #include <stdio.h>
  20. #include <ctype.h>
  21. #include <unistd.h>
  22. #include <stdint.h>
  23. #include <string.h>
  24. #include <fcntl.h>
  25. #include <libubox/ustream.h>
  26. #include <libubox/ustream-ssl.h>
  27. #include <libubox/usock.h>
  28. #include <libubox/blobmsg.h>
  29. #include "uclient.h"
  30. #include "uclient-utils.h"
  31. #include "uclient-backend.h"
  32. enum auth_type {
  33. AUTH_TYPE_UNKNOWN,
  34. AUTH_TYPE_NONE,
  35. AUTH_TYPE_BASIC,
  36. AUTH_TYPE_DIGEST,
  37. };
  38. enum request_type {
  39. REQ_GET,
  40. REQ_HEAD,
  41. REQ_POST,
  42. REQ_PUT,
  43. REQ_DELETE,
  44. __REQ_MAX
  45. };
  46. enum http_state {
  47. HTTP_STATE_INIT,
  48. HTTP_STATE_HEADERS_SENT,
  49. HTTP_STATE_REQUEST_DONE,
  50. HTTP_STATE_RECV_HEADERS,
  51. HTTP_STATE_RECV_DATA,
  52. HTTP_STATE_ERROR,
  53. };
  54. static const char * const request_types[__REQ_MAX] = {
  55. [REQ_GET] = "GET",
  56. [REQ_HEAD] = "HEAD",
  57. [REQ_POST] = "POST",
  58. [REQ_PUT] = "PUT",
  59. [REQ_DELETE] = "DELETE",
  60. };
  61. struct uclient_http {
  62. struct uclient uc;
  63. const struct ustream_ssl_ops *ssl_ops;
  64. struct ustream_ssl_ctx *ssl_ctx;
  65. struct ustream *us;
  66. struct ustream_fd ufd;
  67. struct ustream_ssl ussl;
  68. struct uloop_timeout disconnect_t;
  69. unsigned int seq;
  70. bool ssl_require_validation;
  71. bool ssl;
  72. bool eof;
  73. bool connection_close;
  74. bool disconnect;
  75. enum request_type req_type;
  76. enum http_state state;
  77. enum auth_type auth_type;
  78. char *auth_str;
  79. long read_chunked;
  80. long content_length;
  81. int usock_flags;
  82. uint32_t nc;
  83. struct blob_buf headers;
  84. struct blob_buf meta;
  85. };
  86. enum {
  87. PREFIX_HTTP,
  88. PREFIX_HTTPS,
  89. __PREFIX_MAX,
  90. };
  91. static const char * const uclient_http_prefix[] = {
  92. [PREFIX_HTTP] = "http://",
  93. [PREFIX_HTTPS] = "https://",
  94. [__PREFIX_MAX] = NULL
  95. };
  96. static int uclient_http_connect(struct uclient *cl);
  97. static int uclient_do_connect(struct uclient_http *uh, const char *port)
  98. {
  99. socklen_t sl;
  100. int fd;
  101. if (uh->uc.url->port)
  102. port = uh->uc.url->port;
  103. memset(&uh->uc.remote_addr, 0, sizeof(uh->uc.remote_addr));
  104. fd = usock_inet_timeout(USOCK_TCP | USOCK_NONBLOCK | uh->usock_flags,
  105. uh->uc.url->host, port, &uh->uc.remote_addr,
  106. uh->uc.timeout_msecs);
  107. if (fd < 0)
  108. return -1;
  109. fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
  110. ustream_fd_init(&uh->ufd, fd);
  111. sl = sizeof(uh->uc.local_addr);
  112. memset(&uh->uc.local_addr, 0, sl);
  113. getsockname(fd, &uh->uc.local_addr.sa, &sl);
  114. return 0;
  115. }
  116. static void uclient_http_disconnect(struct uclient_http *uh)
  117. {
  118. uloop_timeout_cancel(&uh->disconnect_t);
  119. if (!uh->us)
  120. return;
  121. if (uh->ssl)
  122. ustream_free(&uh->ussl.stream);
  123. ustream_free(&uh->ufd.stream);
  124. if(uh->ufd.fd.fd)
  125. close(uh->ufd.fd.fd);
  126. uh->us = NULL;
  127. }
  128. static void uclient_http_free_url_state(struct uclient *cl)
  129. {
  130. struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
  131. uh->auth_type = AUTH_TYPE_UNKNOWN;
  132. free(uh->auth_str);
  133. uh->auth_str = NULL;
  134. uclient_http_disconnect(uh);
  135. }
  136. static void uclient_http_error(struct uclient_http *uh, int code)
  137. {
  138. uh->state = HTTP_STATE_ERROR;
  139. uh->us->eof = true;
  140. ustream_state_change(uh->us);
  141. uclient_backend_set_error(&uh->uc, code);
  142. }
  143. static void uclient_http_request_disconnect(struct uclient *cl)
  144. {
  145. struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
  146. if (!uh->us)
  147. return;
  148. uh->eof = true;
  149. uh->disconnect = true;
  150. uloop_timeout_set(&uh->disconnect_t, 1);
  151. }
  152. static void uclient_notify_eof(struct uclient_http *uh)
  153. {
  154. struct ustream *us = uh->us;
  155. if (uh->disconnect)
  156. return;
  157. if (!uh->eof) {
  158. if (!us->eof && !us->write_error)
  159. return;
  160. if (ustream_pending_data(us, false))
  161. return;
  162. }
  163. if ((uh->content_length < 0 && uh->read_chunked >= 0) ||
  164. uh->content_length == 0)
  165. uh->uc.data_eof = true;
  166. uclient_backend_set_eof(&uh->uc);
  167. if (uh->connection_close)
  168. uclient_http_request_disconnect(&uh->uc);
  169. }
  170. static void uclient_http_reset_state(struct uclient_http *uh)
  171. {
  172. uh->seq++;
  173. uclient_backend_reset_state(&uh->uc);
  174. uh->read_chunked = -1;
  175. uh->content_length = -1;
  176. uh->eof = false;
  177. uh->disconnect = false;
  178. uh->connection_close = false;
  179. uh->state = HTTP_STATE_INIT;
  180. if (uh->auth_type == AUTH_TYPE_UNKNOWN && !uh->uc.url->auth)
  181. uh->auth_type = AUTH_TYPE_NONE;
  182. }
  183. static void uclient_http_init_request(struct uclient_http *uh)
  184. {
  185. uh->seq++;
  186. uclient_http_reset_state(uh);
  187. blob_buf_init(&uh->meta, 0);
  188. }
  189. static enum auth_type
  190. uclient_http_update_auth_type(struct uclient_http *uh)
  191. {
  192. if (!uh->auth_str)
  193. return AUTH_TYPE_NONE;
  194. if (!strncasecmp(uh->auth_str, "basic", 5))
  195. return AUTH_TYPE_BASIC;
  196. if (!strncasecmp(uh->auth_str, "digest", 6))
  197. return AUTH_TYPE_DIGEST;
  198. return AUTH_TYPE_NONE;
  199. }
  200. static void uclient_http_process_headers(struct uclient_http *uh)
  201. {
  202. enum {
  203. HTTP_HDR_TRANSFER_ENCODING,
  204. HTTP_HDR_CONNECTION,
  205. HTTP_HDR_CONTENT_LENGTH,
  206. HTTP_HDR_AUTH,
  207. __HTTP_HDR_MAX,
  208. };
  209. static const struct blobmsg_policy hdr_policy[__HTTP_HDR_MAX] = {
  210. #define hdr(_name) { .name = _name, .type = BLOBMSG_TYPE_STRING }
  211. [HTTP_HDR_TRANSFER_ENCODING] = hdr("transfer-encoding"),
  212. [HTTP_HDR_CONNECTION] = hdr("connection"),
  213. [HTTP_HDR_CONTENT_LENGTH] = hdr("content-length"),
  214. [HTTP_HDR_AUTH] = hdr("www-authenticate"),
  215. #undef hdr
  216. };
  217. struct blob_attr *tb[__HTTP_HDR_MAX];
  218. struct blob_attr *cur;
  219. blobmsg_parse(hdr_policy, __HTTP_HDR_MAX, tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
  220. cur = tb[HTTP_HDR_TRANSFER_ENCODING];
  221. if (cur && strstr(blobmsg_data(cur), "chunked"))
  222. uh->read_chunked = 0;
  223. cur = tb[HTTP_HDR_CONNECTION];
  224. if (cur && strstr(blobmsg_data(cur), "close"))
  225. uh->connection_close = true;
  226. cur = tb[HTTP_HDR_CONTENT_LENGTH];
  227. if (cur)
  228. uh->content_length = strtoul(blobmsg_data(cur), NULL, 10);
  229. cur = tb[HTTP_HDR_AUTH];
  230. if (cur) {
  231. free(uh->auth_str);
  232. uh->auth_str = strdup(blobmsg_data(cur));
  233. }
  234. uh->auth_type = uclient_http_update_auth_type(uh);
  235. }
  236. static bool uclient_request_supports_body(enum request_type req_type)
  237. {
  238. switch (req_type) {
  239. case REQ_POST:
  240. case REQ_PUT:
  241. case REQ_DELETE:
  242. return true;
  243. default:
  244. return false;
  245. }
  246. }
  247. static int
  248. uclient_http_add_auth_basic(struct uclient_http *uh)
  249. {
  250. struct uclient_url *url = uh->uc.url;
  251. int auth_len = strlen(url->auth);
  252. char *auth_buf;
  253. if (auth_len > 512)
  254. return -EINVAL;
  255. auth_buf = alloca(base64_len(auth_len) + 1);
  256. if (!auth_buf)
  257. return -ENOMEM;
  258. base64_encode(url->auth, auth_len, auth_buf);
  259. ustream_printf(uh->us, "Authorization: Basic %s\r\n", auth_buf);
  260. return 0;
  261. }
  262. static char *digest_unquote_sep(char **str)
  263. {
  264. char *cur = *str + 1;
  265. char *start = cur;
  266. char *out;
  267. if (**str != '"')
  268. return NULL;
  269. out = cur;
  270. while (1) {
  271. if (!*cur)
  272. return NULL;
  273. if (*cur == '"') {
  274. cur++;
  275. break;
  276. }
  277. if (*cur == '\\')
  278. cur++;
  279. *(out++) = *(cur++);
  280. }
  281. if (*cur == ',')
  282. cur++;
  283. *out = 0;
  284. *str = cur;
  285. return start;
  286. }
  287. static char *digest_sep(char **str)
  288. {
  289. char *cur, *next;
  290. cur = *str;
  291. next = strchr(*str, ',');
  292. if (next) {
  293. *str = next + 1;
  294. *next = 0;
  295. } else {
  296. *str += strlen(*str);
  297. }
  298. return cur;
  299. }
  300. static bool strmatch(char **str, const char *prefix)
  301. {
  302. int len = strlen(prefix);
  303. if (strncmp(*str, prefix, len) != 0 || (*str)[len] != '=')
  304. return false;
  305. *str += len + 1;
  306. return true;
  307. }
  308. static void
  309. get_cnonce(char *dest)
  310. {
  311. uint32_t val = 0;
  312. FILE *f;
  313. size_t n;
  314. f = fopen("/dev/urandom", "r");
  315. if (f) {
  316. n = fread(&val, sizeof(val), 1, f);
  317. fclose(f);
  318. if (n != 1)
  319. return;
  320. }
  321. bin_to_hex(dest, &val, sizeof(val));
  322. }
  323. static void add_field(char **buf, int *ofs, int *len, const char *name, const char *val)
  324. {
  325. int available = *len - *ofs;
  326. int required;
  327. const char *next;
  328. char *cur;
  329. if (*len && !*buf)
  330. return;
  331. required = strlen(name) + 4 + strlen(val) * 2;
  332. if (required > available)
  333. *len += required - available + 64;
  334. *buf = realloc(*buf, *len);
  335. if (!*buf)
  336. return;
  337. cur = *buf + *ofs;
  338. cur += sprintf(cur, ", %s=\"", name);
  339. while ((next = strchr(val, '"'))) {
  340. if (next > val) {
  341. memcpy(cur, val, next - val);
  342. cur += next - val;
  343. }
  344. cur += sprintf(cur, "\\\"");
  345. val = next + 1;
  346. }
  347. cur += sprintf(cur, "%s\"", val);
  348. *ofs = cur - *buf;
  349. }
  350. static int
  351. uclient_http_add_auth_digest(struct uclient_http *uh)
  352. {
  353. struct uclient_url *url = uh->uc.url;
  354. const char *realm = NULL, *opaque = NULL;
  355. const char *user, *password;
  356. char *buf, *next;
  357. int len, ofs;
  358. int err = 0;
  359. char cnonce_str[9];
  360. char nc_str[9];
  361. char ahash[33];
  362. char hash[33];
  363. struct http_digest_data data = {
  364. .nc = nc_str,
  365. .cnonce = cnonce_str,
  366. .auth_hash = ahash,
  367. };
  368. len = strlen(uh->auth_str) + 1;
  369. if (len > 512) {
  370. err = -EINVAL;
  371. goto fail;
  372. }
  373. buf = alloca(len);
  374. if (!buf) {
  375. err = -ENOMEM;
  376. goto fail;
  377. }
  378. strcpy(buf, uh->auth_str);
  379. /* skip auth type */
  380. strsep(&buf, " ");
  381. next = buf;
  382. while (*next) {
  383. const char **dest = NULL;
  384. const char *tmp;
  385. while (*next && isspace(*next))
  386. next++;
  387. if (strmatch(&next, "realm"))
  388. dest = &realm;
  389. else if (strmatch(&next, "qop"))
  390. dest = &data.qop;
  391. else if (strmatch(&next, "nonce"))
  392. dest = &data.nonce;
  393. else if (strmatch(&next, "opaque"))
  394. dest = &opaque;
  395. else if (strmatch(&next, "stale") ||
  396. strmatch(&next, "algorithm") ||
  397. strmatch(&next, "auth-param")) {
  398. digest_sep(&next);
  399. continue;
  400. } else if (strmatch(&next, "domain") ||
  401. strmatch(&next, "qop-options"))
  402. dest = &tmp;
  403. else {
  404. digest_sep(&next);
  405. continue;
  406. }
  407. *dest = digest_unquote_sep(&next);
  408. }
  409. if (!realm || !data.qop || !data.nonce) {
  410. err = -EINVAL;
  411. goto fail;
  412. }
  413. sprintf(nc_str, "%08x", uh->nc++);
  414. get_cnonce(cnonce_str);
  415. data.qop = "auth";
  416. data.uri = url->location;
  417. data.method = request_types[uh->req_type];
  418. password = strchr(url->auth, ':');
  419. if (password) {
  420. char *user_buf;
  421. len = password - url->auth;
  422. if (len > 256) {
  423. err = -EINVAL;
  424. goto fail;
  425. }
  426. user_buf = alloca(len + 1);
  427. if (!user_buf) {
  428. err = -ENOMEM;
  429. goto fail;
  430. }
  431. strncpy(user_buf, url->auth, len);
  432. user_buf[len] = 0;
  433. user = user_buf;
  434. password++;
  435. } else {
  436. user = url->auth;
  437. password = "";
  438. }
  439. http_digest_calculate_auth_hash(ahash, user, realm, password);
  440. http_digest_calculate_response(hash, &data);
  441. buf = NULL;
  442. len = 0;
  443. ofs = 0;
  444. add_field(&buf, &ofs, &len, "username", user);
  445. add_field(&buf, &ofs, &len, "realm", realm);
  446. add_field(&buf, &ofs, &len, "nonce", data.nonce);
  447. add_field(&buf, &ofs, &len, "uri", data.uri);
  448. add_field(&buf, &ofs, &len, "cnonce", data.cnonce);
  449. add_field(&buf, &ofs, &len, "response", hash);
  450. if (opaque)
  451. add_field(&buf, &ofs, &len, "opaque", opaque);
  452. ustream_printf(uh->us, "Authorization: Digest nc=%s, qop=%s%s\r\n", data.nc, data.qop, buf);
  453. free(buf);
  454. return 0;
  455. fail:
  456. return err;
  457. }
  458. static int
  459. uclient_http_add_auth_header(struct uclient_http *uh)
  460. {
  461. if (!uh->uc.url->auth)
  462. return 0;
  463. switch (uh->auth_type) {
  464. case AUTH_TYPE_UNKNOWN:
  465. case AUTH_TYPE_NONE:
  466. break;
  467. case AUTH_TYPE_BASIC:
  468. return uclient_http_add_auth_basic(uh);
  469. case AUTH_TYPE_DIGEST:
  470. return uclient_http_add_auth_digest(uh);
  471. }
  472. return 0;
  473. }
  474. static int
  475. uclient_http_send_headers(struct uclient_http *uh)
  476. {
  477. struct uclient_url *url = uh->uc.url;
  478. struct blob_attr *cur;
  479. enum request_type req_type = uh->req_type;
  480. bool literal_ipv6;
  481. int err;
  482. size_t rem;
  483. if (uh->state >= HTTP_STATE_HEADERS_SENT)
  484. return 0;
  485. if (uh->uc.proxy_url)
  486. url = uh->uc.proxy_url;
  487. literal_ipv6 = strchr(url->host, ':');
  488. ustream_printf(uh->us,
  489. "%s %s HTTP/1.1\r\n"
  490. "Host: %s%s%s%s%s\r\n",
  491. request_types[req_type], url->location,
  492. literal_ipv6 ? "[" : "",
  493. url->host,
  494. literal_ipv6 ? "]" : "",
  495. url->port ? ":" : "",
  496. url->port ? url->port : "");
  497. blobmsg_for_each_attr(cur, uh->headers.head, rem)
  498. ustream_printf(uh->us, "%s: %s\r\n", blobmsg_name(cur), (char *) blobmsg_data(cur));
  499. if (uclient_request_supports_body(uh->req_type))
  500. ustream_printf(uh->us, "Transfer-Encoding: chunked\r\n");
  501. err = uclient_http_add_auth_header(uh);
  502. if (err)
  503. return err;
  504. ustream_printf(uh->us, "\r\n");
  505. uh->state = HTTP_STATE_HEADERS_SENT;
  506. return 0;
  507. }
  508. static void uclient_http_headers_complete(struct uclient_http *uh)
  509. {
  510. enum auth_type auth_type = uh->auth_type;
  511. int seq = uh->uc.seq;
  512. uh->state = HTTP_STATE_RECV_DATA;
  513. uh->uc.meta = uh->meta.head;
  514. uclient_http_process_headers(uh);
  515. if (auth_type == AUTH_TYPE_UNKNOWN && uh->uc.status_code == 401 &&
  516. (uh->req_type == REQ_HEAD || uh->req_type == REQ_GET)) {
  517. uclient_http_connect(&uh->uc);
  518. uclient_http_send_headers(uh);
  519. uh->state = HTTP_STATE_REQUEST_DONE;
  520. return;
  521. }
  522. if (uh->uc.cb->header_done)
  523. uh->uc.cb->header_done(&uh->uc);
  524. if (uh->eof || seq != uh->uc.seq)
  525. return;
  526. if (uh->req_type == REQ_HEAD || uh->uc.status_code == 204 ||
  527. uh->content_length == 0) {
  528. uh->eof = true;
  529. uclient_notify_eof(uh);
  530. }
  531. }
  532. static void uclient_parse_http_line(struct uclient_http *uh, char *data)
  533. {
  534. char *name;
  535. char *sep;
  536. if (uh->state == HTTP_STATE_REQUEST_DONE) {
  537. char *code;
  538. if (!strlen(data))
  539. return;
  540. /* HTTP/1.1 */
  541. strsep(&data, " ");
  542. code = strsep(&data, " ");
  543. if (!code)
  544. goto error;
  545. uh->uc.status_code = strtoul(code, &sep, 10);
  546. if (sep && *sep)
  547. goto error;
  548. uh->state = HTTP_STATE_RECV_HEADERS;
  549. return;
  550. }
  551. if (!*data) {
  552. uclient_http_headers_complete(uh);
  553. return;
  554. }
  555. sep = strchr(data, ':');
  556. if (!sep)
  557. return;
  558. *(sep++) = 0;
  559. for (name = data; *name; name++)
  560. *name = tolower(*name);
  561. name = data;
  562. while (isspace(*sep))
  563. sep++;
  564. blobmsg_add_string(&uh->meta, name, sep);
  565. return;
  566. error:
  567. uh->uc.status_code = 400;
  568. uh->eof = true;
  569. uclient_notify_eof(uh);
  570. }
  571. static void __uclient_notify_read(struct uclient_http *uh)
  572. {
  573. struct uclient *uc = &uh->uc;
  574. unsigned int seq = uh->seq;
  575. char *data;
  576. int len;
  577. if (uh->state < HTTP_STATE_REQUEST_DONE || uh->state == HTTP_STATE_ERROR)
  578. return;
  579. data = ustream_get_read_buf(uh->us, &len);
  580. if (!data || !len)
  581. return;
  582. if (uh->state < HTTP_STATE_RECV_DATA) {
  583. char *sep, *next;
  584. int cur_len;
  585. do {
  586. sep = strchr(data, '\n');
  587. if (!sep)
  588. break;
  589. next = sep + 1;
  590. if (sep > data && sep[-1] == '\r')
  591. sep--;
  592. /* Check for multi-line HTTP headers */
  593. if (sep > data) {
  594. if (!*next)
  595. return;
  596. if (isspace(*next) && *next != '\r' && *next != '\n') {
  597. sep[0] = ' ';
  598. if (sep + 1 < next)
  599. sep[1] = ' ';
  600. continue;
  601. }
  602. }
  603. *sep = 0;
  604. cur_len = next - data;
  605. uclient_parse_http_line(uh, data);
  606. if (seq != uh->seq)
  607. return;
  608. ustream_consume(uh->us, cur_len);
  609. len -= cur_len;
  610. if (uh->eof)
  611. return;
  612. data = ustream_get_read_buf(uh->us, &len);
  613. } while (data && uh->state < HTTP_STATE_RECV_DATA);
  614. if (!len)
  615. return;
  616. }
  617. if (uh->eof)
  618. return;
  619. if (uh->state == HTTP_STATE_RECV_DATA) {
  620. /* Now it's uclient user turn to read some data */
  621. uloop_timeout_cancel(&uc->connection_timeout);
  622. if (uc->cb->data_read)
  623. uc->cb->data_read(uc);
  624. }
  625. }
  626. static void __uclient_notify_write(struct uclient_http *uh)
  627. {
  628. struct uclient *uc = &uh->uc;
  629. if (uc->cb->data_sent)
  630. uc->cb->data_sent(uc);
  631. }
  632. static void uclient_notify_read(struct ustream *us, int bytes)
  633. {
  634. struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
  635. __uclient_notify_read(uh);
  636. }
  637. static void uclient_notify_write(struct ustream *us, int bytes)
  638. {
  639. struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
  640. __uclient_notify_write(uh);
  641. }
  642. static void uclient_notify_state(struct ustream *us)
  643. {
  644. struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
  645. if (uh->ufd.stream.write_error) {
  646. uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
  647. return;
  648. }
  649. uclient_notify_eof(uh);
  650. }
  651. static int uclient_setup_http(struct uclient_http *uh)
  652. {
  653. struct ustream *us = &uh->ufd.stream;
  654. int ret;
  655. uh->us = us;
  656. uh->ssl = false;
  657. us->string_data = true;
  658. us->notify_state = uclient_notify_state;
  659. us->notify_read = uclient_notify_read;
  660. us->notify_write = uclient_notify_write;
  661. ret = uclient_do_connect(uh, "80");
  662. if (ret)
  663. return UCLIENT_ERROR_CONNECT;
  664. return 0;
  665. }
  666. static void uclient_ssl_notify_read(struct ustream *us, int bytes)
  667. {
  668. struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
  669. __uclient_notify_read(uh);
  670. }
  671. static void uclient_ssl_notify_write(struct ustream *us, int bytes)
  672. {
  673. struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
  674. __uclient_notify_write(uh);
  675. }
  676. static void uclient_ssl_notify_state(struct ustream *us)
  677. {
  678. struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
  679. uclient_notify_eof(uh);
  680. }
  681. static void uclient_ssl_notify_error(struct ustream_ssl *ssl, int error, const char *str)
  682. {
  683. struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
  684. uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
  685. }
  686. static void uclient_ssl_notify_verify_error(struct ustream_ssl *ssl, int error, const char *str)
  687. {
  688. struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
  689. if (!uh->ssl_require_validation)
  690. return;
  691. uclient_http_error(uh, UCLIENT_ERROR_SSL_INVALID_CERT);
  692. }
  693. static void uclient_ssl_notify_connected(struct ustream_ssl *ssl)
  694. {
  695. struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
  696. if (!uh->ssl_require_validation)
  697. return;
  698. if (!uh->ussl.valid_cn)
  699. uclient_http_error(uh, UCLIENT_ERROR_SSL_CN_MISMATCH);
  700. }
  701. static int uclient_setup_https(struct uclient_http *uh)
  702. {
  703. struct ustream *us = &uh->ussl.stream;
  704. int ret;
  705. uh->ssl = true;
  706. uh->us = us;
  707. if (!uh->ssl_ctx)
  708. return UCLIENT_ERROR_MISSING_SSL_CONTEXT;
  709. ret = uclient_do_connect(uh, "443");
  710. if (ret)
  711. return UCLIENT_ERROR_CONNECT;
  712. us->string_data = true;
  713. us->notify_state = uclient_ssl_notify_state;
  714. us->notify_read = uclient_ssl_notify_read;
  715. us->notify_write = uclient_ssl_notify_write;
  716. uh->ussl.notify_error = uclient_ssl_notify_error;
  717. uh->ussl.notify_verify_error = uclient_ssl_notify_verify_error;
  718. uh->ussl.notify_connected = uclient_ssl_notify_connected;
  719. uh->ussl.server_name = uh->uc.url->host;
  720. uh->ssl_ops->init(&uh->ussl, &uh->ufd.stream, uh->ssl_ctx, false);
  721. uh->ssl_ops->set_peer_cn(&uh->ussl, uh->uc.url->host);
  722. return 0;
  723. }
  724. static int uclient_http_connect(struct uclient *cl)
  725. {
  726. struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
  727. int ret;
  728. if (!cl->eof || uh->disconnect || uh->connection_close)
  729. uclient_http_disconnect(uh);
  730. uclient_http_init_request(uh);
  731. if (uh->us)
  732. return 0;
  733. uh->ssl = cl->url->prefix == PREFIX_HTTPS;
  734. if (uh->ssl)
  735. ret = uclient_setup_https(uh);
  736. else
  737. ret = uclient_setup_http(uh);
  738. return ret;
  739. }
  740. static void uclient_http_disconnect_cb(struct uloop_timeout *timeout)
  741. {
  742. struct uclient_http *uh = container_of(timeout, struct uclient_http, disconnect_t);
  743. uclient_http_disconnect(uh);
  744. }
  745. static struct uclient *uclient_http_alloc(void)
  746. {
  747. struct uclient_http *uh;
  748. uh = calloc_a(sizeof(*uh));
  749. if (!uh)
  750. return NULL;
  751. uh->disconnect_t.cb = uclient_http_disconnect_cb;
  752. blob_buf_init(&uh->headers, 0);
  753. return &uh->uc;
  754. }
  755. static void uclient_http_free_ssl_ctx(struct uclient_http *uh)
  756. {
  757. uh->ssl_ops = NULL;
  758. uh->ssl_ctx = NULL;
  759. }
  760. static void uclient_http_free(struct uclient *cl)
  761. {
  762. struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
  763. uclient_http_free_url_state(cl);
  764. uclient_http_free_ssl_ctx(uh);
  765. blob_buf_free(&uh->headers);
  766. blob_buf_free(&uh->meta);
  767. free(uh);
  768. }
  769. int
  770. uclient_http_set_request_type(struct uclient *cl, const char *type)
  771. {
  772. struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
  773. unsigned int i;
  774. if (cl->backend != &uclient_backend_http)
  775. return -1;
  776. if (uh->state > HTTP_STATE_INIT)
  777. return -1;
  778. for (i = 0; i < ARRAY_SIZE(request_types); i++) {
  779. if (strcmp(request_types[i], type) != 0)
  780. continue;
  781. uh->req_type = i;
  782. return 0;
  783. }
  784. return -1;
  785. }
  786. int
  787. uclient_http_reset_headers(struct uclient *cl)
  788. {
  789. struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
  790. blob_buf_init(&uh->headers, 0);
  791. return 0;
  792. }
  793. int
  794. uclient_http_set_header(struct uclient *cl, const char *name, const char *value)
  795. {
  796. struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
  797. if (cl->backend != &uclient_backend_http)
  798. return -1;
  799. if (uh->state > HTTP_STATE_INIT)
  800. return -1;
  801. blobmsg_add_string(&uh->headers, name, value);
  802. return 0;
  803. }
  804. static int
  805. uclient_http_send_data(struct uclient *cl, const char *buf, unsigned int len)
  806. {
  807. struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
  808. int err;
  809. if (uh->state >= HTTP_STATE_REQUEST_DONE)
  810. return -1;
  811. err = uclient_http_send_headers(uh);
  812. if (err)
  813. return err;
  814. if (len > 0) {
  815. ustream_printf(uh->us, "%X\r\n", len);
  816. ustream_write(uh->us, buf, len, false);
  817. ustream_printf(uh->us, "\r\n");
  818. }
  819. return len;
  820. }
  821. static int
  822. uclient_http_request_done(struct uclient *cl)
  823. {
  824. struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
  825. int err;
  826. if (uh->state >= HTTP_STATE_REQUEST_DONE)
  827. return -1;
  828. err = uclient_http_send_headers(uh);
  829. if (err)
  830. return err;
  831. if (uclient_request_supports_body(uh->req_type))
  832. ustream_printf(uh->us, "0\r\n\r\n");
  833. uh->state = HTTP_STATE_REQUEST_DONE;
  834. return 0;
  835. }
  836. static int
  837. uclient_http_read(struct uclient *cl, char *buf, unsigned int len)
  838. {
  839. struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
  840. int read_len = 0;
  841. char *data, *data_end;
  842. if (uh->state < HTTP_STATE_RECV_DATA || !uh->us)
  843. return 0;
  844. data = ustream_get_read_buf(uh->us, &read_len);
  845. if (!data || !read_len)
  846. return 0;
  847. data_end = data + read_len;
  848. read_len = 0;
  849. if (uh->read_chunked == 0) {
  850. char *sep;
  851. if (data[0] == '\r' && data[1] == '\n') {
  852. data += 2;
  853. read_len += 2;
  854. }
  855. sep = strstr(data, "\r\n");
  856. if (!sep)
  857. return 0;
  858. *sep = 0;
  859. uh->read_chunked = strtoul(data, NULL, 16);
  860. read_len += sep + 2 - data;
  861. data = sep + 2;
  862. if (!uh->read_chunked) {
  863. uh->eof = true;
  864. uh->uc.data_eof = true;
  865. }
  866. }
  867. unsigned int diff = data_end - data;
  868. if (len > diff)
  869. len = diff;
  870. if (uh->read_chunked >= 0) {
  871. if (len > (unsigned long) uh->read_chunked)
  872. len = uh->read_chunked;
  873. uh->read_chunked -= len;
  874. } else if (uh->content_length >= 0) {
  875. if (len > (unsigned long) uh->content_length)
  876. len = uh->content_length;
  877. uh->content_length -= len;
  878. if (!uh->content_length) {
  879. uh->eof = true;
  880. uh->uc.data_eof = true;
  881. }
  882. }
  883. if (len > 0) {
  884. read_len += len;
  885. memcpy(buf, data, len);
  886. }
  887. if (read_len > 0)
  888. ustream_consume(uh->us, read_len);
  889. uclient_notify_eof(uh);
  890. /* Now that we consumed something and if this isn't EOF, start timer again */
  891. if (!uh->uc.eof && !cl->connection_timeout.pending)
  892. uloop_timeout_set(&cl->connection_timeout, cl->timeout_msecs);
  893. return len;
  894. }
  895. int uclient_http_redirect(struct uclient *cl)
  896. {
  897. struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
  898. struct blobmsg_policy location = {
  899. .name = "location",
  900. .type = BLOBMSG_TYPE_STRING,
  901. };
  902. struct uclient_url *url = cl->url;
  903. struct blob_attr *tb;
  904. if (cl->backend != &uclient_backend_http)
  905. return false;
  906. switch (cl->status_code) {
  907. case 301:
  908. case 302:
  909. case 307:
  910. break;
  911. default:
  912. return false;
  913. }
  914. blobmsg_parse(&location, 1, &tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
  915. if (!tb)
  916. return false;
  917. url = uclient_get_url_location(url, blobmsg_data(tb));
  918. if (!url)
  919. return false;
  920. if (cl->proxy_url) {
  921. free(cl->proxy_url);
  922. cl->proxy_url = url;
  923. }
  924. else {
  925. free(cl->url);
  926. cl->url = url;
  927. }
  928. if (uclient_http_connect(cl))
  929. return -1;
  930. uclient_http_request_done(cl);
  931. return true;
  932. }
  933. int uclient_http_set_ssl_ctx(struct uclient *cl, const struct ustream_ssl_ops *ops,
  934. struct ustream_ssl_ctx *ctx, bool require_validation)
  935. {
  936. struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
  937. if (cl->backend != &uclient_backend_http)
  938. return -1;
  939. uclient_http_free_url_state(cl);
  940. uclient_http_free_ssl_ctx(uh);
  941. uh->ssl_ops = ops;
  942. uh->ssl_ctx = ctx;
  943. uh->ssl_require_validation = !!ctx && require_validation;
  944. return 0;
  945. }
  946. int uclient_http_set_address_family(struct uclient *cl, int af)
  947. {
  948. struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
  949. if (cl->backend != &uclient_backend_http)
  950. return -1;
  951. switch (af) {
  952. case AF_INET:
  953. uh->usock_flags = USOCK_IPV4ONLY;
  954. break;
  955. case AF_INET6:
  956. uh->usock_flags = USOCK_IPV6ONLY;
  957. break;
  958. default:
  959. uh->usock_flags = 0;
  960. break;
  961. }
  962. return 0;
  963. }
  964. const struct uclient_backend uclient_backend_http = {
  965. .prefix = uclient_http_prefix,
  966. .alloc = uclient_http_alloc,
  967. .free = uclient_http_free,
  968. .connect = uclient_http_connect,
  969. .disconnect = uclient_http_request_disconnect,
  970. .update_url = uclient_http_free_url_state,
  971. .update_proxy_url = uclient_http_free_url_state,
  972. .read = uclient_http_read,
  973. .write = uclient_http_send_data,
  974. .request = uclient_http_request_done,
  975. };