You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

httpcore.c 41KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578
  1. /*
  2. * Copyright (C) 2007 Michael Brown <mbrown@fensystems.co.uk>.
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public License as
  6. * published by the Free Software Foundation; either version 2 of the
  7. * License, or any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  17. * 02110-1301, USA.
  18. *
  19. * You can also choose to distribute this program under the terms of
  20. * the Unmodified Binary Distribution Licence (as given in the file
  21. * COPYING.UBDL), provided that you have satisfied its requirements.
  22. */
  23. FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
  24. /**
  25. * @file
  26. *
  27. * Hyper Text Transfer Protocol (HTTP) core functionality
  28. *
  29. */
  30. #include <stdint.h>
  31. #include <stdlib.h>
  32. #include <stdio.h>
  33. #include <string.h>
  34. #include <strings.h>
  35. #include <byteswap.h>
  36. #include <errno.h>
  37. #include <ctype.h>
  38. #include <assert.h>
  39. #include <ipxe/uri.h>
  40. #include <ipxe/refcnt.h>
  41. #include <ipxe/iobuf.h>
  42. #include <ipxe/xfer.h>
  43. #include <ipxe/open.h>
  44. #include <ipxe/socket.h>
  45. #include <ipxe/tcpip.h>
  46. #include <ipxe/process.h>
  47. #include <ipxe/retry.h>
  48. #include <ipxe/timer.h>
  49. #include <ipxe/linebuf.h>
  50. #include <ipxe/base64.h>
  51. #include <ipxe/base16.h>
  52. #include <ipxe/md5.h>
  53. #include <ipxe/blockdev.h>
  54. #include <ipxe/acpi.h>
  55. #include <ipxe/version.h>
  56. #include <ipxe/params.h>
  57. #include <ipxe/profile.h>
  58. #include <ipxe/http.h>
  59. /* Disambiguate the various error causes */
  60. #define EACCES_401 __einfo_error ( EINFO_EACCES_401 )
  61. #define EINFO_EACCES_401 \
  62. __einfo_uniqify ( EINFO_EACCES, 0x01, "HTTP 401 Unauthorized" )
  63. #define EIO_OTHER __einfo_error ( EINFO_EIO_OTHER )
  64. #define EINFO_EIO_OTHER \
  65. __einfo_uniqify ( EINFO_EIO, 0x01, "Unrecognised HTTP response code" )
  66. #define EIO_CONTENT_LENGTH __einfo_error ( EINFO_EIO_CONTENT_LENGTH )
  67. #define EINFO_EIO_CONTENT_LENGTH \
  68. __einfo_uniqify ( EINFO_EIO, 0x02, "Content length mismatch" )
  69. #define EINVAL_RESPONSE __einfo_error ( EINFO_EINVAL_RESPONSE )
  70. #define EINFO_EINVAL_RESPONSE \
  71. __einfo_uniqify ( EINFO_EINVAL, 0x01, "Invalid content length" )
  72. #define EINVAL_HEADER __einfo_error ( EINFO_EINVAL_HEADER )
  73. #define EINFO_EINVAL_HEADER \
  74. __einfo_uniqify ( EINFO_EINVAL, 0x02, "Invalid header" )
  75. #define EINVAL_CONTENT_LENGTH __einfo_error ( EINFO_EINVAL_CONTENT_LENGTH )
  76. #define EINFO_EINVAL_CONTENT_LENGTH \
  77. __einfo_uniqify ( EINFO_EINVAL, 0x03, "Invalid content length" )
  78. #define EINVAL_CHUNK_LENGTH __einfo_error ( EINFO_EINVAL_CHUNK_LENGTH )
  79. #define EINFO_EINVAL_CHUNK_LENGTH \
  80. __einfo_uniqify ( EINFO_EINVAL, 0x04, "Invalid chunk length" )
  81. #define ENOENT_404 __einfo_error ( EINFO_ENOENT_404 )
  82. #define EINFO_ENOENT_404 \
  83. __einfo_uniqify ( EINFO_ENOENT, 0x01, "HTTP 404 Not Found" )
  84. #define EPERM_403 __einfo_error ( EINFO_EPERM_403 )
  85. #define EINFO_EPERM_403 \
  86. __einfo_uniqify ( EINFO_EPERM, 0x01, "HTTP 403 Forbidden" )
  87. #define EPROTO_UNSOLICITED __einfo_error ( EINFO_EPROTO_UNSOLICITED )
  88. #define EINFO_EPROTO_UNSOLICITED \
  89. __einfo_uniqify ( EINFO_EPROTO, 0x01, "Unsolicited data" )
  90. /** Block size used for HTTP block device request */
  91. #define HTTP_BLKSIZE 512
  92. /** Retry delay used when we cannot understand the Retry-After header */
  93. #define HTTP_RETRY_SECONDS 5
  94. /** Receive profiler */
  95. static struct profiler http_rx_profiler __profiler = { .name = "http.rx" };
  96. /** Data transfer profiler */
  97. static struct profiler http_xfer_profiler __profiler = { .name = "http.xfer" };
  98. /** HTTP flags */
  99. enum http_flags {
  100. /** Request is waiting to be transmitted */
  101. HTTP_TX_PENDING = 0x0001,
  102. /** Fetch header only */
  103. HTTP_HEAD_ONLY = 0x0002,
  104. /** Client would like to keep connection alive */
  105. HTTP_CLIENT_KEEPALIVE = 0x0004,
  106. /** Server will keep connection alive */
  107. HTTP_SERVER_KEEPALIVE = 0x0008,
  108. /** Discard the current request and try again */
  109. HTTP_TRY_AGAIN = 0x0010,
  110. /** Provide Basic authentication details */
  111. HTTP_BASIC_AUTH = 0x0020,
  112. /** Provide Digest authentication details */
  113. HTTP_DIGEST_AUTH = 0x0040,
  114. /** Socket must be reopened */
  115. HTTP_REOPEN_SOCKET = 0x0080,
  116. };
  117. /** HTTP receive state */
  118. enum http_rx_state {
  119. HTTP_RX_RESPONSE = 0,
  120. HTTP_RX_HEADER,
  121. HTTP_RX_CHUNK_LEN,
  122. /* In HTTP_RX_DATA, it is acceptable for the server to close
  123. * the connection (unless we are in the middle of a chunked
  124. * transfer).
  125. */
  126. HTTP_RX_DATA,
  127. /* In the following states, it is acceptable for the server to
  128. * close the connection.
  129. */
  130. HTTP_RX_TRAILER,
  131. HTTP_RX_IDLE,
  132. HTTP_RX_DEAD,
  133. };
  134. /**
  135. * An HTTP request
  136. *
  137. */
  138. struct http_request {
  139. /** Reference count */
  140. struct refcnt refcnt;
  141. /** Data transfer interface */
  142. struct interface xfer;
  143. /** Partial transfer interface */
  144. struct interface partial;
  145. /** URI being fetched */
  146. struct uri *uri;
  147. /** Default port */
  148. unsigned int default_port;
  149. /** Filter (if any) */
  150. int ( * filter ) ( struct interface *xfer,
  151. const char *name,
  152. struct interface **next );
  153. /** Transport layer interface */
  154. struct interface socket;
  155. /** Flags */
  156. unsigned int flags;
  157. /** Starting offset of partial transfer (if applicable) */
  158. size_t partial_start;
  159. /** Length of partial transfer (if applicable) */
  160. size_t partial_len;
  161. /** TX process */
  162. struct process process;
  163. /** RX state */
  164. enum http_rx_state rx_state;
  165. /** Response code */
  166. unsigned int code;
  167. /** Received length */
  168. size_t rx_len;
  169. /** Length remaining (or 0 if unknown) */
  170. size_t remaining;
  171. /** HTTP is using Transfer-Encoding: chunked */
  172. int chunked;
  173. /** Current chunk length remaining (if applicable) */
  174. size_t chunk_remaining;
  175. /** Line buffer for received header lines */
  176. struct line_buffer linebuf;
  177. /** Receive data buffer (if applicable) */
  178. userptr_t rx_buffer;
  179. /** Authentication realm (if any) */
  180. char *auth_realm;
  181. /** Authentication nonce (if any) */
  182. char *auth_nonce;
  183. /** Authentication opaque string (if any) */
  184. char *auth_opaque;
  185. /** Request retry timer */
  186. struct retry_timer timer;
  187. /** Retry delay (in timer ticks) */
  188. unsigned long retry_delay;
  189. };
  190. /**
  191. * Free HTTP request
  192. *
  193. * @v refcnt Reference counter
  194. */
  195. static void http_free ( struct refcnt *refcnt ) {
  196. struct http_request *http =
  197. container_of ( refcnt, struct http_request, refcnt );
  198. uri_put ( http->uri );
  199. empty_line_buffer ( &http->linebuf );
  200. free ( http->auth_realm );
  201. free ( http->auth_nonce );
  202. free ( http->auth_opaque );
  203. free ( http );
  204. };
  205. /**
  206. * Close HTTP request
  207. *
  208. * @v http HTTP request
  209. * @v rc Return status code
  210. */
  211. static void http_close ( struct http_request *http, int rc ) {
  212. /* Prevent further processing of any current packet */
  213. http->rx_state = HTTP_RX_DEAD;
  214. /* Prevent reconnection */
  215. http->flags &= ~HTTP_CLIENT_KEEPALIVE;
  216. /* Remove process */
  217. process_del ( &http->process );
  218. /* Close all data transfer interfaces */
  219. intf_shutdown ( &http->socket, rc );
  220. intf_shutdown ( &http->partial, rc );
  221. intf_shutdown ( &http->xfer, rc );
  222. }
  223. /**
  224. * Open HTTP socket
  225. *
  226. * @v http HTTP request
  227. * @ret rc Return status code
  228. */
  229. static int http_socket_open ( struct http_request *http ) {
  230. struct uri *uri = http->uri;
  231. struct sockaddr_tcpip server;
  232. struct interface *socket;
  233. int rc;
  234. /* Open socket */
  235. memset ( &server, 0, sizeof ( server ) );
  236. server.st_port = htons ( uri_port ( uri, http->default_port ) );
  237. socket = &http->socket;
  238. if ( http->filter ) {
  239. if ( ( rc = http->filter ( socket, uri->host, &socket ) ) != 0 )
  240. return rc;
  241. }
  242. if ( ( rc = xfer_open_named_socket ( socket, SOCK_STREAM,
  243. ( struct sockaddr * ) &server,
  244. uri->host, NULL ) ) != 0 )
  245. return rc;
  246. return 0;
  247. }
  248. /**
  249. * Retry HTTP request
  250. *
  251. * @v timer Retry timer
  252. * @v fail Failure indicator
  253. */
  254. static void http_retry ( struct retry_timer *timer, int fail __unused ) {
  255. struct http_request *http =
  256. container_of ( timer, struct http_request, timer );
  257. int rc;
  258. /* Reopen socket if required */
  259. if ( http->flags & HTTP_REOPEN_SOCKET ) {
  260. http->flags &= ~HTTP_REOPEN_SOCKET;
  261. DBGC ( http, "HTTP %p reopening connection\n", http );
  262. if ( ( rc = http_socket_open ( http ) ) != 0 ) {
  263. http_close ( http, rc );
  264. return;
  265. }
  266. }
  267. /* Retry the request if applicable */
  268. if ( http->flags & HTTP_TRY_AGAIN ) {
  269. http->flags &= ~HTTP_TRY_AGAIN;
  270. DBGC ( http, "HTTP %p retrying request\n", http );
  271. http->flags |= HTTP_TX_PENDING;
  272. http->rx_state = HTTP_RX_RESPONSE;
  273. process_add ( &http->process );
  274. }
  275. }
  276. /**
  277. * Mark HTTP request as completed successfully
  278. *
  279. * @v http HTTP request
  280. */
  281. static void http_done ( struct http_request *http ) {
  282. /* If we are not at an appropriate stage of the protocol
  283. * (including being in the middle of a chunked transfer),
  284. * force an error.
  285. */
  286. if ( ( http->rx_state < HTTP_RX_DATA ) || ( http->chunked != 0 ) ) {
  287. DBGC ( http, "HTTP %p connection closed unexpectedly in state "
  288. "%d\n", http, http->rx_state );
  289. http_close ( http, -ECONNRESET );
  290. return;
  291. }
  292. /* If we had a Content-Length, and the received content length
  293. * isn't correct, force an error
  294. */
  295. if ( http->remaining != 0 ) {
  296. DBGC ( http, "HTTP %p incorrect length %zd, should be %zd\n",
  297. http, http->rx_len, ( http->rx_len + http->remaining ) );
  298. http_close ( http, -EIO_CONTENT_LENGTH );
  299. return;
  300. }
  301. /* Enter idle state */
  302. http->rx_state = HTTP_RX_IDLE;
  303. http->rx_len = 0;
  304. assert ( http->remaining == 0 );
  305. assert ( http->chunked == 0 );
  306. assert ( http->chunk_remaining == 0 );
  307. /* Close partial transfer interface */
  308. if ( ! ( http->flags & HTTP_TRY_AGAIN ) )
  309. intf_restart ( &http->partial, 0 );
  310. /* Close everything unless we want to keep the connection alive */
  311. if ( ! ( http->flags & ( HTTP_CLIENT_KEEPALIVE | HTTP_TRY_AGAIN ) ) ) {
  312. http_close ( http, 0 );
  313. return;
  314. }
  315. /* If the server is not intending to keep the connection
  316. * alive, then close the socket and mark it as requiring
  317. * reopening.
  318. */
  319. if ( ! ( http->flags & HTTP_SERVER_KEEPALIVE ) ) {
  320. intf_restart ( &http->socket, 0 );
  321. http->flags &= ~HTTP_SERVER_KEEPALIVE;
  322. http->flags |= HTTP_REOPEN_SOCKET;
  323. }
  324. /* Start request retry timer */
  325. start_timer_fixed ( &http->timer, http->retry_delay );
  326. http->retry_delay = 0;
  327. }
  328. /**
  329. * Convert HTTP response code to return status code
  330. *
  331. * @v response HTTP response code
  332. * @ret rc Return status code
  333. */
  334. static int http_response_to_rc ( unsigned int response ) {
  335. switch ( response ) {
  336. case 200:
  337. case 206:
  338. case 301:
  339. case 302:
  340. case 303:
  341. return 0;
  342. case 404:
  343. return -ENOENT_404;
  344. case 403:
  345. return -EPERM_403;
  346. case 401:
  347. return -EACCES_401;
  348. default:
  349. return -EIO_OTHER;
  350. }
  351. }
  352. /**
  353. * Handle HTTP response
  354. *
  355. * @v http HTTP request
  356. * @v response HTTP response
  357. * @ret rc Return status code
  358. */
  359. static int http_rx_response ( struct http_request *http, char *response ) {
  360. char *spc;
  361. DBGC ( http, "HTTP %p response \"%s\"\n", http, response );
  362. /* Check response starts with "HTTP/" */
  363. if ( strncmp ( response, "HTTP/", 5 ) != 0 )
  364. return -EINVAL_RESPONSE;
  365. /* Locate and store response code */
  366. spc = strchr ( response, ' ' );
  367. if ( ! spc )
  368. return -EINVAL_RESPONSE;
  369. http->code = strtoul ( spc, NULL, 10 );
  370. /* Move to receive headers */
  371. http->rx_state = ( ( http->flags & HTTP_HEAD_ONLY ) ?
  372. HTTP_RX_TRAILER : HTTP_RX_HEADER );
  373. return 0;
  374. }
  375. /**
  376. * Handle HTTP Location header
  377. *
  378. * @v http HTTP request
  379. * @v value HTTP header value
  380. * @ret rc Return status code
  381. */
  382. static int http_rx_location ( struct http_request *http, char *value ) {
  383. int rc;
  384. /* Redirect to new location */
  385. DBGC ( http, "HTTP %p redirecting to %s\n", http, value );
  386. if ( ( rc = xfer_redirect ( &http->xfer, LOCATION_URI_STRING,
  387. value ) ) != 0 ) {
  388. DBGC ( http, "HTTP %p could not redirect: %s\n",
  389. http, strerror ( rc ) );
  390. return rc;
  391. }
  392. return 0;
  393. }
  394. /**
  395. * Handle HTTP Content-Length header
  396. *
  397. * @v http HTTP request
  398. * @v value HTTP header value
  399. * @ret rc Return status code
  400. */
  401. static int http_rx_content_length ( struct http_request *http, char *value ) {
  402. struct block_device_capacity capacity;
  403. size_t content_len;
  404. char *endp;
  405. /* Parse content length */
  406. content_len = strtoul ( value, &endp, 10 );
  407. if ( ! ( ( *endp == '\0' ) || isspace ( *endp ) ) ) {
  408. DBGC ( http, "HTTP %p invalid Content-Length \"%s\"\n",
  409. http, value );
  410. return -EINVAL_CONTENT_LENGTH;
  411. }
  412. /* If we already have an expected content length, and this
  413. * isn't it, then complain
  414. */
  415. if ( http->remaining && ( http->remaining != content_len ) ) {
  416. DBGC ( http, "HTTP %p incorrect Content-Length %zd (expected "
  417. "%zd)\n", http, content_len, http->remaining );
  418. return -EIO_CONTENT_LENGTH;
  419. }
  420. if ( ! ( http->flags & HTTP_HEAD_ONLY ) )
  421. http->remaining = content_len;
  422. /* Do nothing more if we are retrying the request */
  423. if ( http->flags & HTTP_TRY_AGAIN )
  424. return 0;
  425. /* Use seek() to notify recipient of filesize */
  426. xfer_seek ( &http->xfer, http->remaining );
  427. xfer_seek ( &http->xfer, 0 );
  428. /* Report block device capacity if applicable */
  429. if ( http->flags & HTTP_HEAD_ONLY ) {
  430. capacity.blocks = ( content_len / HTTP_BLKSIZE );
  431. capacity.blksize = HTTP_BLKSIZE;
  432. capacity.max_count = -1U;
  433. block_capacity ( &http->partial, &capacity );
  434. }
  435. return 0;
  436. }
  437. /**
  438. * Handle HTTP Transfer-Encoding header
  439. *
  440. * @v http HTTP request
  441. * @v value HTTP header value
  442. * @ret rc Return status code
  443. */
  444. static int http_rx_transfer_encoding ( struct http_request *http, char *value ){
  445. if ( strcasecmp ( value, "chunked" ) == 0 ) {
  446. /* Mark connection as using chunked transfer encoding */
  447. http->chunked = 1;
  448. }
  449. return 0;
  450. }
  451. /**
  452. * Handle HTTP Connection header
  453. *
  454. * @v http HTTP request
  455. * @v value HTTP header value
  456. * @ret rc Return status code
  457. */
  458. static int http_rx_connection ( struct http_request *http, char *value ) {
  459. if ( strcasecmp ( value, "keep-alive" ) == 0 ) {
  460. /* Mark connection as being kept alive by the server */
  461. http->flags |= HTTP_SERVER_KEEPALIVE;
  462. }
  463. return 0;
  464. }
  465. /**
  466. * Handle WWW-Authenticate Basic header
  467. *
  468. * @v http HTTP request
  469. * @v params Parameters
  470. * @ret rc Return status code
  471. */
  472. static int http_rx_basic_auth ( struct http_request *http, char *params ) {
  473. DBGC ( http, "HTTP %p Basic authentication required (%s)\n",
  474. http, params );
  475. /* If we received a 401 Unauthorized response, then retry
  476. * using Basic authentication
  477. */
  478. if ( ( http->code == 401 ) &&
  479. ( ! ( http->flags & HTTP_BASIC_AUTH ) ) &&
  480. ( http->uri->user != NULL ) ) {
  481. http->flags |= ( HTTP_TRY_AGAIN | HTTP_BASIC_AUTH );
  482. }
  483. return 0;
  484. }
  485. /**
  486. * Parse Digest authentication parameter
  487. *
  488. * @v params Parameters
  489. * @v name Parameter name (including trailing "=\"")
  490. * @ret value Parameter value, or NULL
  491. */
  492. static char * http_digest_param ( char *params, const char *name ) {
  493. char *key;
  494. char *value;
  495. char *terminator;
  496. /* Locate parameter */
  497. key = strstr ( params, name );
  498. if ( ! key )
  499. return NULL;
  500. /* Extract value */
  501. value = ( key + strlen ( name ) );
  502. terminator = strchr ( value, '"' );
  503. if ( ! terminator )
  504. return NULL;
  505. return strndup ( value, ( terminator - value ) );
  506. }
  507. /**
  508. * Handle WWW-Authenticate Digest header
  509. *
  510. * @v http HTTP request
  511. * @v params Parameters
  512. * @ret rc Return status code
  513. */
  514. static int http_rx_digest_auth ( struct http_request *http, char *params ) {
  515. DBGC ( http, "HTTP %p Digest authentication required (%s)\n",
  516. http, params );
  517. /* If we received a 401 Unauthorized response, then retry
  518. * using Digest authentication
  519. */
  520. if ( ( http->code == 401 ) &&
  521. ( ! ( http->flags & HTTP_DIGEST_AUTH ) ) &&
  522. ( http->uri->user != NULL ) ) {
  523. /* Extract realm */
  524. free ( http->auth_realm );
  525. http->auth_realm = http_digest_param ( params, "realm=\"" );
  526. if ( ! http->auth_realm ) {
  527. DBGC ( http, "HTTP %p Digest prompt missing realm\n",
  528. http );
  529. return -EINVAL_HEADER;
  530. }
  531. /* Extract nonce */
  532. free ( http->auth_nonce );
  533. http->auth_nonce = http_digest_param ( params, "nonce=\"" );
  534. if ( ! http->auth_nonce ) {
  535. DBGC ( http, "HTTP %p Digest prompt missing nonce\n",
  536. http );
  537. return -EINVAL_HEADER;
  538. }
  539. /* Extract opaque */
  540. free ( http->auth_opaque );
  541. http->auth_opaque = http_digest_param ( params, "opaque=\"" );
  542. if ( ! http->auth_opaque ) {
  543. /* Not an error; "opaque" is optional */
  544. }
  545. http->flags |= ( HTTP_TRY_AGAIN | HTTP_DIGEST_AUTH );
  546. }
  547. return 0;
  548. }
  549. /** An HTTP WWW-Authenticate header handler */
  550. struct http_auth_header_handler {
  551. /** Scheme (e.g. "Basic") */
  552. const char *scheme;
  553. /** Handle received parameters
  554. *
  555. * @v http HTTP request
  556. * @v params Parameters
  557. * @ret rc Return status code
  558. */
  559. int ( * rx ) ( struct http_request *http, char *params );
  560. };
  561. /** List of HTTP WWW-Authenticate header handlers */
  562. static struct http_auth_header_handler http_auth_header_handlers[] = {
  563. {
  564. .scheme = "Basic",
  565. .rx = http_rx_basic_auth,
  566. },
  567. {
  568. .scheme = "Digest",
  569. .rx = http_rx_digest_auth,
  570. },
  571. { NULL, NULL },
  572. };
  573. /**
  574. * Handle HTTP WWW-Authenticate header
  575. *
  576. * @v http HTTP request
  577. * @v value HTTP header value
  578. * @ret rc Return status code
  579. */
  580. static int http_rx_www_authenticate ( struct http_request *http, char *value ) {
  581. struct http_auth_header_handler *handler;
  582. char *separator;
  583. char *scheme;
  584. char *params;
  585. int rc;
  586. /* Extract scheme */
  587. separator = strchr ( value, ' ' );
  588. if ( ! separator ) {
  589. DBGC ( http, "HTTP %p malformed WWW-Authenticate header\n",
  590. http );
  591. return -EINVAL_HEADER;
  592. }
  593. *separator = '\0';
  594. scheme = value;
  595. params = ( separator + 1 );
  596. /* Hand off to header handler, if one exists */
  597. for ( handler = http_auth_header_handlers; handler->scheme; handler++ ){
  598. if ( strcasecmp ( scheme, handler->scheme ) == 0 ) {
  599. if ( ( rc = handler->rx ( http, params ) ) != 0 )
  600. return rc;
  601. break;
  602. }
  603. }
  604. return 0;
  605. }
  606. /**
  607. * Handle HTTP Retry-After header
  608. *
  609. * @v http HTTP request
  610. * @v value HTTP header value
  611. * @ret rc Return status code
  612. */
  613. static int http_rx_retry_after ( struct http_request *http, char *value ) {
  614. unsigned long seconds;
  615. char *endp;
  616. DBGC ( http, "HTTP %p retry requested (%s)\n", http, value );
  617. /* If we received a 503 Service Unavailable response, then
  618. * retry after the specified number of seconds. If the value
  619. * is not a simple number of seconds (e.g. a full HTTP date),
  620. * then retry after a fixed delay, since we don't have code
  621. * able to parse full HTTP dates.
  622. */
  623. if ( http->code == 503 ) {
  624. seconds = strtoul ( value, &endp, 10 );
  625. if ( *endp != '\0' ) {
  626. seconds = HTTP_RETRY_SECONDS;
  627. DBGC ( http, "HTTP %p cannot understand \"%s\"; "
  628. "using %ld seconds\n", http, value, seconds );
  629. }
  630. http->flags |= HTTP_TRY_AGAIN;
  631. http->retry_delay = ( seconds * TICKS_PER_SEC );
  632. }
  633. return 0;
  634. }
  635. /** An HTTP header handler */
  636. struct http_header_handler {
  637. /** Name (e.g. "Content-Length") */
  638. const char *header;
  639. /** Handle received header
  640. *
  641. * @v http HTTP request
  642. * @v value HTTP header value
  643. * @ret rc Return status code
  644. *
  645. * If an error is returned, the download will be aborted.
  646. */
  647. int ( * rx ) ( struct http_request *http, char *value );
  648. };
  649. /** List of HTTP header handlers */
  650. static struct http_header_handler http_header_handlers[] = {
  651. {
  652. .header = "Location",
  653. .rx = http_rx_location,
  654. },
  655. {
  656. .header = "Content-Length",
  657. .rx = http_rx_content_length,
  658. },
  659. {
  660. .header = "Transfer-Encoding",
  661. .rx = http_rx_transfer_encoding,
  662. },
  663. {
  664. .header = "Connection",
  665. .rx = http_rx_connection,
  666. },
  667. {
  668. .header = "WWW-Authenticate",
  669. .rx = http_rx_www_authenticate,
  670. },
  671. {
  672. .header = "Retry-After",
  673. .rx = http_rx_retry_after,
  674. },
  675. { NULL, NULL }
  676. };
  677. /**
  678. * Handle HTTP header
  679. *
  680. * @v http HTTP request
  681. * @v header HTTP header
  682. * @ret rc Return status code
  683. */
  684. static int http_rx_header ( struct http_request *http, char *header ) {
  685. struct http_header_handler *handler;
  686. char *separator;
  687. char *value;
  688. int rc;
  689. /* An empty header line marks the end of this phase */
  690. if ( ! header[0] ) {
  691. empty_line_buffer ( &http->linebuf );
  692. /* Handle response code */
  693. if ( ! ( http->flags & HTTP_TRY_AGAIN ) ) {
  694. if ( ( rc = http_response_to_rc ( http->code ) ) != 0 )
  695. return rc;
  696. }
  697. /* Move to next state */
  698. if ( http->rx_state == HTTP_RX_HEADER ) {
  699. DBGC ( http, "HTTP %p start of data\n", http );
  700. http->rx_state = ( http->chunked ?
  701. HTTP_RX_CHUNK_LEN : HTTP_RX_DATA );
  702. if ( ( http->partial_len != 0 ) &&
  703. ( ! ( http->flags & HTTP_TRY_AGAIN ) ) ) {
  704. http->remaining = http->partial_len;
  705. }
  706. return 0;
  707. } else {
  708. DBGC ( http, "HTTP %p end of trailer\n", http );
  709. http_done ( http );
  710. return 0;
  711. }
  712. }
  713. DBGC ( http, "HTTP %p header \"%s\"\n", http, header );
  714. /* Split header at the ": " */
  715. separator = strstr ( header, ": " );
  716. if ( ! separator ) {
  717. DBGC ( http, "HTTP %p malformed header\n", http );
  718. return -EINVAL_HEADER;
  719. }
  720. *separator = '\0';
  721. value = ( separator + 2 );
  722. /* Hand off to header handler, if one exists */
  723. for ( handler = http_header_handlers ; handler->header ; handler++ ) {
  724. if ( strcasecmp ( header, handler->header ) == 0 ) {
  725. if ( ( rc = handler->rx ( http, value ) ) != 0 )
  726. return rc;
  727. break;
  728. }
  729. }
  730. return 0;
  731. }
  732. /**
  733. * Handle HTTP chunk length
  734. *
  735. * @v http HTTP request
  736. * @v length HTTP chunk length
  737. * @ret rc Return status code
  738. */
  739. static int http_rx_chunk_len ( struct http_request *http, char *length ) {
  740. char *endp;
  741. /* Skip blank lines between chunks */
  742. if ( length[0] == '\0' )
  743. return 0;
  744. /* Parse chunk length */
  745. http->chunk_remaining = strtoul ( length, &endp, 16 );
  746. if ( *endp != '\0' ) {
  747. DBGC ( http, "HTTP %p invalid chunk length \"%s\"\n",
  748. http, length );
  749. return -EINVAL_CHUNK_LENGTH;
  750. }
  751. /* Terminate chunked encoding if applicable */
  752. if ( http->chunk_remaining == 0 ) {
  753. DBGC ( http, "HTTP %p end of chunks\n", http );
  754. http->chunked = 0;
  755. http->rx_state = HTTP_RX_TRAILER;
  756. return 0;
  757. }
  758. /* Use seek() to notify recipient of new filesize */
  759. DBGC ( http, "HTTP %p start of chunk of length %zd\n",
  760. http, http->chunk_remaining );
  761. if ( ! ( http->flags & HTTP_TRY_AGAIN ) ) {
  762. xfer_seek ( &http->xfer,
  763. ( http->rx_len + http->chunk_remaining ) );
  764. xfer_seek ( &http->xfer, http->rx_len );
  765. }
  766. /* Start receiving data */
  767. http->rx_state = HTTP_RX_DATA;
  768. return 0;
  769. }
  770. /** An HTTP line-based data handler */
  771. struct http_line_handler {
  772. /** Handle line
  773. *
  774. * @v http HTTP request
  775. * @v line Line to handle
  776. * @ret rc Return status code
  777. */
  778. int ( * rx ) ( struct http_request *http, char *line );
  779. };
  780. /** List of HTTP line-based data handlers */
  781. static struct http_line_handler http_line_handlers[] = {
  782. [HTTP_RX_RESPONSE] = { .rx = http_rx_response },
  783. [HTTP_RX_HEADER] = { .rx = http_rx_header },
  784. [HTTP_RX_CHUNK_LEN] = { .rx = http_rx_chunk_len },
  785. [HTTP_RX_TRAILER] = { .rx = http_rx_header },
  786. };
  787. /**
  788. * Handle new data arriving via HTTP connection
  789. *
  790. * @v http HTTP request
  791. * @v iobuf I/O buffer
  792. * @v meta Data transfer metadata
  793. * @ret rc Return status code
  794. */
  795. static int http_socket_deliver ( struct http_request *http,
  796. struct io_buffer *iobuf,
  797. struct xfer_metadata *meta __unused ) {
  798. struct http_line_handler *lh;
  799. char *line;
  800. size_t data_len;
  801. ssize_t line_len;
  802. int rc = 0;
  803. profile_start ( &http_rx_profiler );
  804. while ( iobuf && iob_len ( iobuf ) ) {
  805. switch ( http->rx_state ) {
  806. case HTTP_RX_IDLE:
  807. /* Receiving any data in this state is an error */
  808. DBGC ( http, "HTTP %p received %zd bytes while %s\n",
  809. http, iob_len ( iobuf ),
  810. ( ( http->rx_state == HTTP_RX_IDLE ) ?
  811. "idle" : "dead" ) );
  812. rc = -EPROTO_UNSOLICITED;
  813. goto done;
  814. case HTTP_RX_DEAD:
  815. /* Do no further processing */
  816. goto done;
  817. case HTTP_RX_DATA:
  818. /* Pass received data to caller */
  819. data_len = iob_len ( iobuf );
  820. if ( http->chunk_remaining &&
  821. ( http->chunk_remaining < data_len ) ) {
  822. data_len = http->chunk_remaining;
  823. }
  824. if ( http->remaining &&
  825. ( http->remaining < data_len ) ) {
  826. data_len = http->remaining;
  827. }
  828. if ( http->flags & HTTP_TRY_AGAIN ) {
  829. /* Discard all received data */
  830. iob_pull ( iobuf, data_len );
  831. } else if ( http->rx_buffer != UNULL ) {
  832. /* Copy to partial transfer buffer */
  833. copy_to_user ( http->rx_buffer, http->rx_len,
  834. iobuf->data, data_len );
  835. iob_pull ( iobuf, data_len );
  836. } else if ( data_len < iob_len ( iobuf ) ) {
  837. /* Deliver partial buffer as raw data */
  838. profile_start ( &http_xfer_profiler );
  839. rc = xfer_deliver_raw ( &http->xfer,
  840. iobuf->data, data_len );
  841. iob_pull ( iobuf, data_len );
  842. if ( rc != 0 )
  843. goto done;
  844. profile_stop ( &http_xfer_profiler );
  845. } else {
  846. /* Deliver whole I/O buffer */
  847. profile_start ( &http_xfer_profiler );
  848. if ( ( rc = xfer_deliver_iob ( &http->xfer,
  849. iob_disown ( iobuf ) ) ) != 0 )
  850. goto done;
  851. profile_stop ( &http_xfer_profiler );
  852. }
  853. http->rx_len += data_len;
  854. if ( http->chunk_remaining ) {
  855. http->chunk_remaining -= data_len;
  856. if ( http->chunk_remaining == 0 )
  857. http->rx_state = HTTP_RX_CHUNK_LEN;
  858. }
  859. if ( http->remaining ) {
  860. http->remaining -= data_len;
  861. if ( ( http->remaining == 0 ) &&
  862. ( http->rx_state == HTTP_RX_DATA ) ) {
  863. http_done ( http );
  864. }
  865. }
  866. break;
  867. case HTTP_RX_RESPONSE:
  868. case HTTP_RX_HEADER:
  869. case HTTP_RX_CHUNK_LEN:
  870. case HTTP_RX_TRAILER:
  871. /* In the other phases, buffer and process a
  872. * line at a time
  873. */
  874. line_len = line_buffer ( &http->linebuf, iobuf->data,
  875. iob_len ( iobuf ) );
  876. if ( line_len < 0 ) {
  877. rc = line_len;
  878. DBGC ( http, "HTTP %p could not buffer line: "
  879. "%s\n", http, strerror ( rc ) );
  880. goto done;
  881. }
  882. iob_pull ( iobuf, line_len );
  883. line = buffered_line ( &http->linebuf );
  884. if ( line ) {
  885. lh = &http_line_handlers[http->rx_state];
  886. if ( ( rc = lh->rx ( http, line ) ) != 0 )
  887. goto done;
  888. }
  889. break;
  890. default:
  891. assert ( 0 );
  892. break;
  893. }
  894. }
  895. done:
  896. if ( rc )
  897. http_close ( http, rc );
  898. free_iob ( iobuf );
  899. profile_stop ( &http_rx_profiler );
  900. return rc;
  901. }
  902. /**
  903. * Check HTTP socket flow control window
  904. *
  905. * @v http HTTP request
  906. * @ret len Length of window
  907. */
  908. static size_t http_socket_window ( struct http_request *http __unused ) {
  909. /* Window is always open. This is to prevent TCP from
  910. * stalling if our parent window is not currently open.
  911. */
  912. return ( ~( ( size_t ) 0 ) );
  913. }
  914. /**
  915. * Close HTTP socket
  916. *
  917. * @v http HTTP request
  918. * @v rc Reason for close
  919. */
  920. static void http_socket_close ( struct http_request *http, int rc ) {
  921. /* If we have an error, terminate */
  922. if ( rc != 0 ) {
  923. http_close ( http, rc );
  924. return;
  925. }
  926. /* Mark HTTP request as complete */
  927. http_done ( http );
  928. }
  929. /**
  930. * Generate HTTP Basic authorisation string
  931. *
  932. * @v http HTTP request
  933. * @ret auth Authorisation string, or NULL on error
  934. *
  935. * The authorisation string is dynamically allocated, and must be
  936. * freed by the caller.
  937. */
  938. static char * http_basic_auth ( struct http_request *http ) {
  939. const char *user = http->uri->user;
  940. const char *password = ( http->uri->password ?
  941. http->uri->password : "" );
  942. size_t user_pw_len =
  943. ( strlen ( user ) + 1 /* ":" */ + strlen ( password ) );
  944. char user_pw[ user_pw_len + 1 /* NUL */ ];
  945. size_t user_pw_base64_len = base64_encoded_len ( user_pw_len );
  946. char user_pw_base64[ user_pw_base64_len + 1 /* NUL */ ];
  947. char *auth;
  948. int len;
  949. /* Sanity check */
  950. assert ( user != NULL );
  951. /* Make "user:password" string from decoded fields */
  952. snprintf ( user_pw, sizeof ( user_pw ), "%s:%s", user, password );
  953. /* Base64-encode the "user:password" string */
  954. base64_encode ( ( void * ) user_pw, user_pw_len, user_pw_base64 );
  955. /* Generate the authorisation string */
  956. len = asprintf ( &auth, "Authorization: Basic %s\r\n",
  957. user_pw_base64 );
  958. if ( len < 0 )
  959. return NULL;
  960. return auth;
  961. }
  962. /**
  963. * Generate HTTP Digest authorisation string
  964. *
  965. * @v http HTTP request
  966. * @v method HTTP method (e.g. "GET")
  967. * @v uri HTTP request URI (e.g. "/index.html")
  968. * @ret auth Authorisation string, or NULL on error
  969. *
  970. * The authorisation string is dynamically allocated, and must be
  971. * freed by the caller.
  972. */
  973. static char * http_digest_auth ( struct http_request *http,
  974. const char *method, const char *uri ) {
  975. const char *user = http->uri->user;
  976. const char *password = ( http->uri->password ?
  977. http->uri->password : "" );
  978. const char *realm = http->auth_realm;
  979. const char *nonce = http->auth_nonce;
  980. const char *opaque = http->auth_opaque;
  981. static const char colon = ':';
  982. uint8_t ctx[MD5_CTX_SIZE];
  983. uint8_t digest[MD5_DIGEST_SIZE];
  984. char ha1[ base16_encoded_len ( sizeof ( digest ) ) + 1 /* NUL */ ];
  985. char ha2[ base16_encoded_len ( sizeof ( digest ) ) + 1 /* NUL */ ];
  986. char response[ base16_encoded_len ( sizeof ( digest ) ) + 1 /* NUL */ ];
  987. char *auth;
  988. int len;
  989. /* Sanity checks */
  990. assert ( user != NULL );
  991. assert ( realm != NULL );
  992. assert ( nonce != NULL );
  993. /* Generate HA1 */
  994. digest_init ( &md5_algorithm, ctx );
  995. digest_update ( &md5_algorithm, ctx, user, strlen ( user ) );
  996. digest_update ( &md5_algorithm, ctx, &colon, sizeof ( colon ) );
  997. digest_update ( &md5_algorithm, ctx, realm, strlen ( realm ) );
  998. digest_update ( &md5_algorithm, ctx, &colon, sizeof ( colon ) );
  999. digest_update ( &md5_algorithm, ctx, password, strlen ( password ) );
  1000. digest_final ( &md5_algorithm, ctx, digest );
  1001. base16_encode ( digest, sizeof ( digest ), ha1 );
  1002. /* Generate HA2 */
  1003. digest_init ( &md5_algorithm, ctx );
  1004. digest_update ( &md5_algorithm, ctx, method, strlen ( method ) );
  1005. digest_update ( &md5_algorithm, ctx, &colon, sizeof ( colon ) );
  1006. digest_update ( &md5_algorithm, ctx, uri, strlen ( uri ) );
  1007. digest_final ( &md5_algorithm, ctx, digest );
  1008. base16_encode ( digest, sizeof ( digest ), ha2 );
  1009. /* Generate response */
  1010. digest_init ( &md5_algorithm, ctx );
  1011. digest_update ( &md5_algorithm, ctx, ha1, strlen ( ha1 ) );
  1012. digest_update ( &md5_algorithm, ctx, &colon, sizeof ( colon ) );
  1013. digest_update ( &md5_algorithm, ctx, nonce, strlen ( nonce ) );
  1014. digest_update ( &md5_algorithm, ctx, &colon, sizeof ( colon ) );
  1015. digest_update ( &md5_algorithm, ctx, ha2, strlen ( ha2 ) );
  1016. digest_final ( &md5_algorithm, ctx, digest );
  1017. base16_encode ( digest, sizeof ( digest ), response );
  1018. /* Generate the authorisation string */
  1019. len = asprintf ( &auth, "Authorization: Digest username=\"%s\", "
  1020. "realm=\"%s\", nonce=\"%s\", uri=\"%s\", "
  1021. "%s%s%sresponse=\"%s\"\r\n", user, realm, nonce, uri,
  1022. ( opaque ? "opaque=\"" : "" ),
  1023. ( opaque ? opaque : "" ),
  1024. ( opaque ? "\", " : "" ), response );
  1025. if ( len < 0 )
  1026. return NULL;
  1027. return auth;
  1028. }
  1029. /**
  1030. * Generate HTTP POST parameter list
  1031. *
  1032. * @v http HTTP request
  1033. * @v buf Buffer to contain HTTP POST parameters
  1034. * @v len Length of buffer
  1035. * @ret len Length of parameter list (excluding terminating NUL)
  1036. */
  1037. static size_t http_post_params ( struct http_request *http,
  1038. char *buf, size_t len ) {
  1039. struct parameter *param;
  1040. ssize_t remaining = len;
  1041. size_t frag_len;
  1042. /* Add each parameter in the form "key=value", joined with "&" */
  1043. len = 0;
  1044. for_each_param ( param, http->uri->params ) {
  1045. /* Add the "&", if applicable */
  1046. if ( len ) {
  1047. if ( remaining > 0 )
  1048. *buf = '&';
  1049. buf++;
  1050. len++;
  1051. remaining--;
  1052. }
  1053. /* URI-encode the key */
  1054. frag_len = uri_encode ( param->key, 0, buf, remaining );
  1055. buf += frag_len;
  1056. len += frag_len;
  1057. remaining -= frag_len;
  1058. /* Add the "=" */
  1059. if ( remaining > 0 )
  1060. *buf = '=';
  1061. buf++;
  1062. len++;
  1063. remaining--;
  1064. /* URI-encode the value */
  1065. frag_len = uri_encode ( param->value, 0, buf, remaining );
  1066. buf += frag_len;
  1067. len += frag_len;
  1068. remaining -= frag_len;
  1069. }
  1070. /* Ensure string is NUL-terminated even if no parameters are present */
  1071. if ( remaining > 0 )
  1072. *buf = '\0';
  1073. return len;
  1074. }
  1075. /**
  1076. * Generate HTTP POST body
  1077. *
  1078. * @v http HTTP request
  1079. * @ret post I/O buffer containing POST body, or NULL on error
  1080. */
  1081. static struct io_buffer * http_post ( struct http_request *http ) {
  1082. struct io_buffer *post;
  1083. size_t len;
  1084. size_t check_len;
  1085. /* Calculate length of parameter list */
  1086. len = http_post_params ( http, NULL, 0 );
  1087. /* Allocate parameter list */
  1088. post = alloc_iob ( len + 1 /* NUL */ );
  1089. if ( ! post )
  1090. return NULL;
  1091. /* Fill parameter list */
  1092. check_len = http_post_params ( http, iob_put ( post, len ),
  1093. ( len + 1 /* NUL */ ) );
  1094. assert ( len == check_len );
  1095. DBGC ( http, "HTTP %p POST %s\n", http, ( ( char * ) post->data ) );
  1096. return post;
  1097. }
  1098. /**
  1099. * HTTP process
  1100. *
  1101. * @v http HTTP request
  1102. */
  1103. static void http_step ( struct http_request *http ) {
  1104. struct io_buffer *post;
  1105. struct uri host_uri;
  1106. struct uri path_uri;
  1107. char *host_uri_string;
  1108. char *path_uri_string;
  1109. char *method;
  1110. char *range;
  1111. char *auth;
  1112. char *content;
  1113. int len;
  1114. int rc;
  1115. /* Do nothing if we have already transmitted the request */
  1116. if ( ! ( http->flags & HTTP_TX_PENDING ) )
  1117. return;
  1118. /* Do nothing until socket is ready */
  1119. if ( ! xfer_window ( &http->socket ) )
  1120. return;
  1121. /* Force a HEAD request if we have nowhere to send any received data */
  1122. if ( ( xfer_window ( &http->xfer ) == 0 ) &&
  1123. ( http->rx_buffer == UNULL ) ) {
  1124. http->flags |= ( HTTP_HEAD_ONLY | HTTP_CLIENT_KEEPALIVE );
  1125. }
  1126. /* Determine method */
  1127. method = ( ( http->flags & HTTP_HEAD_ONLY ) ? "HEAD" :
  1128. ( http->uri->params ? "POST" : "GET" ) );
  1129. /* Construct host URI */
  1130. memset ( &host_uri, 0, sizeof ( host_uri ) );
  1131. host_uri.host = http->uri->host;
  1132. host_uri.port = http->uri->port;
  1133. host_uri_string = format_uri_alloc ( &host_uri );
  1134. if ( ! host_uri_string ) {
  1135. rc = -ENOMEM;
  1136. goto err_host_uri;
  1137. }
  1138. /* Construct path URI */
  1139. memset ( &path_uri, 0, sizeof ( path_uri ) );
  1140. path_uri.path = ( http->uri->path ? http->uri->path : "/" );
  1141. path_uri.query = http->uri->query;
  1142. path_uri_string = format_uri_alloc ( &path_uri );
  1143. if ( ! path_uri_string ) {
  1144. rc = -ENOMEM;
  1145. goto err_path_uri;
  1146. }
  1147. /* Calculate range request parameters if applicable */
  1148. if ( http->partial_len ) {
  1149. len = asprintf ( &range, "Range: bytes=%zd-%zd\r\n",
  1150. http->partial_start,
  1151. ( http->partial_start + http->partial_len
  1152. - 1 ) );
  1153. if ( len < 0 ) {
  1154. rc = len;
  1155. goto err_range;
  1156. }
  1157. } else {
  1158. range = NULL;
  1159. }
  1160. /* Construct authorisation, if applicable */
  1161. if ( http->flags & HTTP_BASIC_AUTH ) {
  1162. auth = http_basic_auth ( http );
  1163. if ( ! auth ) {
  1164. rc = -ENOMEM;
  1165. goto err_auth;
  1166. }
  1167. } else if ( http->flags & HTTP_DIGEST_AUTH ) {
  1168. auth = http_digest_auth ( http, method, path_uri_string );
  1169. if ( ! auth ) {
  1170. rc = -ENOMEM;
  1171. goto err_auth;
  1172. }
  1173. } else {
  1174. auth = NULL;
  1175. }
  1176. /* Construct POST content, if applicable */
  1177. if ( http->uri->params ) {
  1178. post = http_post ( http );
  1179. if ( ! post ) {
  1180. rc = -ENOMEM;
  1181. goto err_post;
  1182. }
  1183. len = asprintf ( &content, "Content-Type: "
  1184. "application/x-www-form-urlencoded\r\n"
  1185. "Content-Length: %zd\r\n", iob_len ( post ) );
  1186. if ( len < 0 ) {
  1187. rc = len;
  1188. goto err_content;
  1189. }
  1190. } else {
  1191. post = NULL;
  1192. content = NULL;
  1193. }
  1194. /* Mark request as transmitted */
  1195. http->flags &= ~HTTP_TX_PENDING;
  1196. /* Send request */
  1197. if ( ( rc = xfer_printf ( &http->socket,
  1198. "%s %s HTTP/1.1\r\n"
  1199. "User-Agent: iPXE/%s\r\n"
  1200. "Host: %s\r\n"
  1201. "%s%s%s%s"
  1202. "\r\n",
  1203. method, path_uri_string, product_version,
  1204. host_uri_string,
  1205. ( ( http->flags & HTTP_CLIENT_KEEPALIVE ) ?
  1206. "Connection: keep-alive\r\n" : "" ),
  1207. ( range ? range : "" ),
  1208. ( auth ? auth : "" ),
  1209. ( content ? content : "" ) ) ) != 0 ) {
  1210. goto err_xfer;
  1211. }
  1212. /* Send POST content, if applicable */
  1213. if ( post ) {
  1214. if ( ( rc = xfer_deliver_iob ( &http->socket,
  1215. iob_disown ( post ) ) ) != 0 )
  1216. goto err_xfer_post;
  1217. }
  1218. err_xfer_post:
  1219. err_xfer:
  1220. free ( content );
  1221. err_content:
  1222. free ( post );
  1223. err_post:
  1224. free ( auth );
  1225. err_auth:
  1226. free ( range );
  1227. err_range:
  1228. free ( path_uri_string );
  1229. err_path_uri:
  1230. free ( host_uri_string );
  1231. err_host_uri:
  1232. if ( rc != 0 )
  1233. http_close ( http, rc );
  1234. }
  1235. /**
  1236. * Check HTTP data transfer flow control window
  1237. *
  1238. * @v http HTTP request
  1239. * @ret len Length of window
  1240. */
  1241. static size_t http_xfer_window ( struct http_request *http ) {
  1242. /* New block commands may be issued only when we are idle */
  1243. return ( ( http->rx_state == HTTP_RX_IDLE ) ? 1 : 0 );
  1244. }
  1245. /**
  1246. * Initiate HTTP partial read
  1247. *
  1248. * @v http HTTP request
  1249. * @v partial Partial transfer interface
  1250. * @v offset Starting offset
  1251. * @v buffer Data buffer
  1252. * @v len Length
  1253. * @ret rc Return status code
  1254. */
  1255. static int http_partial_read ( struct http_request *http,
  1256. struct interface *partial,
  1257. size_t offset, userptr_t buffer, size_t len ) {
  1258. /* Sanity check */
  1259. if ( http_xfer_window ( http ) == 0 )
  1260. return -EBUSY;
  1261. /* Initialise partial transfer parameters */
  1262. http->rx_buffer = buffer;
  1263. http->partial_start = offset;
  1264. http->partial_len = len;
  1265. /* Schedule request */
  1266. http->rx_state = HTTP_RX_RESPONSE;
  1267. http->flags = ( HTTP_TX_PENDING | HTTP_CLIENT_KEEPALIVE );
  1268. if ( ! len )
  1269. http->flags |= HTTP_HEAD_ONLY;
  1270. process_add ( &http->process );
  1271. /* Attach to parent interface and return */
  1272. intf_plug_plug ( &http->partial, partial );
  1273. return 0;
  1274. }
  1275. /**
  1276. * Issue HTTP block device read
  1277. *
  1278. * @v http HTTP request
  1279. * @v block Block data interface
  1280. * @v lba Starting logical block address
  1281. * @v count Number of blocks to transfer
  1282. * @v buffer Data buffer
  1283. * @v len Length of data buffer
  1284. * @ret rc Return status code
  1285. */
  1286. static int http_block_read ( struct http_request *http,
  1287. struct interface *block,
  1288. uint64_t lba, unsigned int count,
  1289. userptr_t buffer, size_t len __unused ) {
  1290. return http_partial_read ( http, block, ( lba * HTTP_BLKSIZE ),
  1291. buffer, ( count * HTTP_BLKSIZE ) );
  1292. }
  1293. /**
  1294. * Read HTTP block device capacity
  1295. *
  1296. * @v http HTTP request
  1297. * @v block Block data interface
  1298. * @ret rc Return status code
  1299. */
  1300. static int http_block_read_capacity ( struct http_request *http,
  1301. struct interface *block ) {
  1302. return http_partial_read ( http, block, 0, 0, 0 );
  1303. }
  1304. /**
  1305. * Describe HTTP device in an ACPI table
  1306. *
  1307. * @v http HTTP request
  1308. * @v acpi ACPI table
  1309. * @v len Length of ACPI table
  1310. * @ret rc Return status code
  1311. */
  1312. static int http_acpi_describe ( struct http_request *http,
  1313. struct acpi_description_header *acpi,
  1314. size_t len ) {
  1315. DBGC ( http, "HTTP %p cannot yet describe device in an ACPI table\n",
  1316. http );
  1317. ( void ) acpi;
  1318. ( void ) len;
  1319. return 0;
  1320. }
  1321. /** HTTP socket interface operations */
  1322. static struct interface_operation http_socket_operations[] = {
  1323. INTF_OP ( xfer_window, struct http_request *, http_socket_window ),
  1324. INTF_OP ( xfer_deliver, struct http_request *, http_socket_deliver ),
  1325. INTF_OP ( xfer_window_changed, struct http_request *, http_step ),
  1326. INTF_OP ( intf_close, struct http_request *, http_socket_close ),
  1327. };
  1328. /** HTTP socket interface descriptor */
  1329. static struct interface_descriptor http_socket_desc =
  1330. INTF_DESC_PASSTHRU ( struct http_request, socket,
  1331. http_socket_operations, xfer );
  1332. /** HTTP partial transfer interface operations */
  1333. static struct interface_operation http_partial_operations[] = {
  1334. INTF_OP ( intf_close, struct http_request *, http_close ),
  1335. };
  1336. /** HTTP partial transfer interface descriptor */
  1337. static struct interface_descriptor http_partial_desc =
  1338. INTF_DESC ( struct http_request, partial, http_partial_operations );
  1339. /** HTTP data transfer interface operations */
  1340. static struct interface_operation http_xfer_operations[] = {
  1341. INTF_OP ( xfer_window, struct http_request *, http_xfer_window ),
  1342. INTF_OP ( block_read, struct http_request *, http_block_read ),
  1343. INTF_OP ( block_read_capacity, struct http_request *,
  1344. http_block_read_capacity ),
  1345. INTF_OP ( intf_close, struct http_request *, http_close ),
  1346. INTF_OP ( acpi_describe, struct http_request *, http_acpi_describe ),
  1347. };
  1348. /** HTTP data transfer interface descriptor */
  1349. static struct interface_descriptor http_xfer_desc =
  1350. INTF_DESC_PASSTHRU ( struct http_request, xfer,
  1351. http_xfer_operations, socket );
  1352. /** HTTP process descriptor */
  1353. static struct process_descriptor http_process_desc =
  1354. PROC_DESC_ONCE ( struct http_request, process, http_step );
  1355. /**
  1356. * Initiate an HTTP connection, with optional filter
  1357. *
  1358. * @v xfer Data transfer interface
  1359. * @v uri Uniform Resource Identifier
  1360. * @v default_port Default port number
  1361. * @v filter Filter to apply to socket, or NULL
  1362. * @ret rc Return status code
  1363. */
  1364. int http_open_filter ( struct interface *xfer, struct uri *uri,
  1365. unsigned int default_port,
  1366. int ( * filter ) ( struct interface *xfer,
  1367. const char *name,
  1368. struct interface **next ) ) {
  1369. struct http_request *http;
  1370. int rc;
  1371. /* Sanity checks */
  1372. if ( ! uri->host )
  1373. return -EINVAL;
  1374. /* Allocate and populate HTTP structure */
  1375. http = zalloc ( sizeof ( *http ) );
  1376. if ( ! http )
  1377. return -ENOMEM;
  1378. ref_init ( &http->refcnt, http_free );
  1379. intf_init ( &http->xfer, &http_xfer_desc, &http->refcnt );
  1380. intf_init ( &http->partial, &http_partial_desc, &http->refcnt );
  1381. http->uri = uri_get ( uri );
  1382. http->default_port = default_port;
  1383. http->filter = filter;
  1384. intf_init ( &http->socket, &http_socket_desc, &http->refcnt );
  1385. process_init ( &http->process, &http_process_desc, &http->refcnt );
  1386. timer_init ( &http->timer, http_retry, &http->refcnt );
  1387. http->flags = HTTP_TX_PENDING;
  1388. /* Open socket */
  1389. if ( ( rc = http_socket_open ( http ) ) != 0 )
  1390. goto err;
  1391. /* Attach to parent interface, mortalise self, and return */
  1392. intf_plug_plug ( &http->xfer, xfer );
  1393. ref_put ( &http->refcnt );
  1394. return 0;
  1395. err:
  1396. DBGC ( http, "HTTP %p could not create request: %s\n",
  1397. http, strerror ( rc ) );
  1398. http_close ( http, rc );
  1399. ref_put ( &http->refcnt );
  1400. return rc;
  1401. }