選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

httpcore.c 50KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968
  1. /*
  2. * Copyright (C) 2015 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/process.h>
  45. #include <ipxe/retry.h>
  46. #include <ipxe/timer.h>
  47. #include <ipxe/linebuf.h>
  48. #include <ipxe/xferbuf.h>
  49. #include <ipxe/blockdev.h>
  50. #include <ipxe/acpi.h>
  51. #include <ipxe/version.h>
  52. #include <ipxe/params.h>
  53. #include <ipxe/profile.h>
  54. #include <ipxe/vsprintf.h>
  55. #include <ipxe/http.h>
  56. /* Disambiguate the various error causes */
  57. #define EACCES_401 __einfo_error ( EINFO_EACCES_401 )
  58. #define EINFO_EACCES_401 \
  59. __einfo_uniqify ( EINFO_EACCES, 0x01, "HTTP 401 Unauthorized" )
  60. #define EINVAL_STATUS __einfo_error ( EINFO_EINVAL_STATUS )
  61. #define EINFO_EINVAL_STATUS \
  62. __einfo_uniqify ( EINFO_EINVAL, 0x01, "Invalid status line" )
  63. #define EINVAL_HEADER __einfo_error ( EINFO_EINVAL_HEADER )
  64. #define EINFO_EINVAL_HEADER \
  65. __einfo_uniqify ( EINFO_EINVAL, 0x02, "Invalid header" )
  66. #define EINVAL_CONTENT_LENGTH __einfo_error ( EINFO_EINVAL_CONTENT_LENGTH )
  67. #define EINFO_EINVAL_CONTENT_LENGTH \
  68. __einfo_uniqify ( EINFO_EINVAL, 0x03, "Invalid content length" )
  69. #define EINVAL_CHUNK_LENGTH __einfo_error ( EINFO_EINVAL_CHUNK_LENGTH )
  70. #define EINFO_EINVAL_CHUNK_LENGTH \
  71. __einfo_uniqify ( EINFO_EINVAL, 0x04, "Invalid chunk length" )
  72. #define EIO_OTHER __einfo_error ( EINFO_EIO_OTHER )
  73. #define EINFO_EIO_OTHER \
  74. __einfo_uniqify ( EINFO_EIO, 0x01, "Unrecognised HTTP response code" )
  75. #define EIO_CONTENT_LENGTH __einfo_error ( EINFO_EIO_CONTENT_LENGTH )
  76. #define EINFO_EIO_CONTENT_LENGTH \
  77. __einfo_uniqify ( EINFO_EIO, 0x02, "Content length mismatch" )
  78. #define EIO_4XX __einfo_error ( EINFO_EIO_4XX )
  79. #define EINFO_EIO_4XX \
  80. __einfo_uniqify ( EINFO_EIO, 0x04, "HTTP 4xx Client Error" )
  81. #define EIO_5XX __einfo_error ( EINFO_EIO_5XX )
  82. #define EINFO_EIO_5XX \
  83. __einfo_uniqify ( EINFO_EIO, 0x05, "HTTP 5xx Server Error" )
  84. #define ENOENT_404 __einfo_error ( EINFO_ENOENT_404 )
  85. #define EINFO_ENOENT_404 \
  86. __einfo_uniqify ( EINFO_ENOENT, 0x01, "HTTP 404 Not Found" )
  87. #define ENOTSUP_CONNECTION __einfo_error ( EINFO_ENOTSUP_CONNECTION )
  88. #define EINFO_ENOTSUP_CONNECTION \
  89. __einfo_uniqify ( EINFO_ENOTSUP, 0x01, "Unsupported connection header" )
  90. #define ENOTSUP_TRANSFER __einfo_error ( EINFO_ENOTSUP_TRANSFER )
  91. #define EINFO_ENOTSUP_TRANSFER \
  92. __einfo_uniqify ( EINFO_ENOTSUP, 0x02, "Unsupported transfer encoding" )
  93. #define EPERM_403 __einfo_error ( EINFO_EPERM_403 )
  94. #define EINFO_EPERM_403 \
  95. __einfo_uniqify ( EINFO_EPERM, 0x01, "HTTP 403 Forbidden" )
  96. #define EPROTO_UNSOLICITED __einfo_error ( EINFO_EPROTO_UNSOLICITED )
  97. #define EINFO_EPROTO_UNSOLICITED \
  98. __einfo_uniqify ( EINFO_EPROTO, 0x01, "Unsolicited data" )
  99. /** Retry delay used when we cannot understand the Retry-After header */
  100. #define HTTP_RETRY_SECONDS 5
  101. /** Receive profiler */
  102. static struct profiler http_rx_profiler __profiler = { .name = "http.rx" };
  103. /** Data transfer profiler */
  104. static struct profiler http_xfer_profiler __profiler = { .name = "http.xfer" };
  105. static struct http_state http_request;
  106. static struct http_state http_headers;
  107. static struct http_state http_trailers;
  108. static struct http_transfer_encoding http_transfer_identity;
  109. /******************************************************************************
  110. *
  111. * Methods
  112. *
  113. ******************************************************************************
  114. */
  115. /** HTTP HEAD method */
  116. struct http_method http_head = {
  117. .name = "HEAD",
  118. };
  119. /** HTTP GET method */
  120. struct http_method http_get = {
  121. .name = "GET",
  122. };
  123. /** HTTP POST method */
  124. struct http_method http_post = {
  125. .name = "POST",
  126. };
  127. /******************************************************************************
  128. *
  129. * Utility functions
  130. *
  131. ******************************************************************************
  132. */
  133. /**
  134. * Handle received HTTP line-buffered data
  135. *
  136. * @v http HTTP transaction
  137. * @v iobuf I/O buffer
  138. * @v linebuf Line buffer
  139. * @ret rc Return status code
  140. */
  141. static int http_rx_linebuf ( struct http_transaction *http,
  142. struct io_buffer *iobuf,
  143. struct line_buffer *linebuf ) {
  144. int consumed;
  145. int rc;
  146. /* Buffer received line */
  147. consumed = line_buffer ( linebuf, iobuf->data, iob_len ( iobuf ) );
  148. if ( consumed < 0 ) {
  149. rc = consumed;
  150. DBGC ( http, "HTTP %p could not buffer line: %s\n",
  151. http, strerror ( rc ) );
  152. return rc;
  153. }
  154. /* Consume line */
  155. iob_pull ( iobuf, consumed );
  156. return 0;
  157. }
  158. /**
  159. * Get HTTP response token
  160. *
  161. * @v line Line position
  162. * @v value Token value to fill in (if any)
  163. * @ret token Token, or NULL
  164. */
  165. char * http_token ( char **line, char **value ) {
  166. char *token;
  167. char quote = '\0';
  168. char c;
  169. /* Avoid returning uninitialised data */
  170. if ( value )
  171. *value = NULL;
  172. /* Skip any initial whitespace or commas */
  173. while ( ( isspace ( **line ) ) || ( **line == ',' ) )
  174. (*line)++;
  175. /* Check for end of line and record token position */
  176. if ( ! **line )
  177. return NULL;
  178. token = *line;
  179. /* Scan for end of token */
  180. while ( ( c = **line ) ) {
  181. /* Terminate if we hit an unquoted whitespace or comma */
  182. if ( ( isspace ( c ) || ( c == ',' ) ) && ! quote )
  183. break;
  184. /* Terminate if we hit a closing quote */
  185. if ( c == quote )
  186. break;
  187. /* Check for value separator */
  188. if ( value && ( ! *value ) && ( c == '=' ) ) {
  189. /* Terminate key portion of token */
  190. *((*line)++) = '\0';
  191. /* Check for quote character */
  192. c = **line;
  193. if ( ( c == '"' ) || ( c == '\'' ) ) {
  194. quote = c;
  195. (*line)++;
  196. }
  197. /* Record value portion of token */
  198. *value = *line;
  199. } else {
  200. /* Move to next character */
  201. (*line)++;
  202. }
  203. }
  204. /* Terminate token, if applicable */
  205. if ( c )
  206. *((*line)++) = '\0';
  207. return token;
  208. }
  209. /******************************************************************************
  210. *
  211. * Transactions
  212. *
  213. ******************************************************************************
  214. */
  215. /**
  216. * Free HTTP transaction
  217. *
  218. * @v refcnt Reference count
  219. */
  220. static void http_free ( struct refcnt *refcnt ) {
  221. struct http_transaction *http =
  222. container_of ( refcnt, struct http_transaction, refcnt );
  223. empty_line_buffer ( &http->response.headers );
  224. empty_line_buffer ( &http->linebuf );
  225. uri_put ( http->uri );
  226. free ( http );
  227. }
  228. /**
  229. * Close HTTP transaction
  230. *
  231. * @v http HTTP transaction
  232. * @v rc Reason for close
  233. */
  234. static void http_close ( struct http_transaction *http, int rc ) {
  235. /* Stop process */
  236. process_del ( &http->process );
  237. /* Stop timer */
  238. stop_timer ( &http->timer );
  239. /* Close all interfaces, allowing for the fact that the
  240. * content-decoded and transfer-decoded interfaces may be
  241. * connected to the same object.
  242. */
  243. intf_shutdown ( &http->conn, rc );
  244. intf_nullify ( &http->transfer );
  245. intf_shutdown ( &http->content, rc );
  246. intf_shutdown ( &http->transfer, rc );
  247. intf_shutdown ( &http->xfer, rc );
  248. }
  249. /**
  250. * Close HTTP transaction with error (even if none specified)
  251. *
  252. * @v http HTTP transaction
  253. * @v rc Reason for close
  254. */
  255. static void http_close_error ( struct http_transaction *http, int rc ) {
  256. /* Treat any close as an error */
  257. http_close ( http, ( rc ? rc : -EPIPE ) );
  258. }
  259. /**
  260. * Reopen stale HTTP connection
  261. *
  262. * @v http HTTP transaction
  263. */
  264. static void http_reopen ( struct http_transaction *http ) {
  265. int rc;
  266. /* Close existing connection */
  267. intf_restart ( &http->conn, -ECANCELED );
  268. /* Reopen connection */
  269. if ( ( rc = http_connect ( &http->conn, http->uri ) ) != 0 ) {
  270. DBGC ( http, "HTTP %p could not reconnect: %s\n",
  271. http, strerror ( rc ) );
  272. goto err_connect;
  273. }
  274. /* Reset state */
  275. http->state = &http_request;
  276. /* Reschedule transmission process */
  277. process_add ( &http->process );
  278. return;
  279. err_connect:
  280. http_close ( http, rc );
  281. }
  282. /**
  283. * Handle retry timer expiry
  284. *
  285. * @v timer Retry timer
  286. * @v over Failure indicator
  287. */
  288. static void http_expired ( struct retry_timer *timer, int over __unused ) {
  289. struct http_transaction *http =
  290. container_of ( timer, struct http_transaction, timer );
  291. /* Reopen connection */
  292. http_reopen ( http );
  293. }
  294. /**
  295. * HTTP transmit process
  296. *
  297. * @v http HTTP transaction
  298. */
  299. static void http_step ( struct http_transaction *http ) {
  300. int rc;
  301. /* Do nothing if we have nothing to transmit */
  302. if ( ! http->state->tx )
  303. return;
  304. /* Do nothing until connection is ready */
  305. if ( ! xfer_window ( &http->conn ) )
  306. return;
  307. /* Do nothing until data transfer interface is ready */
  308. if ( ! xfer_window ( &http->xfer ) )
  309. return;
  310. /* Transmit data */
  311. if ( ( rc = http->state->tx ( http ) ) != 0 )
  312. goto err;
  313. return;
  314. err:
  315. http_close ( http, rc );
  316. }
  317. /**
  318. * Handle received HTTP data
  319. *
  320. * @v http HTTP transaction
  321. * @v iobuf I/O buffer
  322. * @v meta Transfer metadata
  323. * @ret rc Return status code
  324. *
  325. * This function takes ownership of the I/O buffer.
  326. */
  327. static int http_conn_deliver ( struct http_transaction *http,
  328. struct io_buffer *iobuf,
  329. struct xfer_metadata *meta __unused ) {
  330. int rc;
  331. /* Handle received data */
  332. profile_start ( &http_rx_profiler );
  333. while ( iobuf && iob_len ( iobuf ) ) {
  334. /* Sanity check */
  335. if ( ( ! http->state ) || ( ! http->state->rx ) ) {
  336. DBGC ( http, "HTTP %p unexpected data\n", http );
  337. rc = -EPROTO_UNSOLICITED;
  338. goto err;
  339. }
  340. /* Receive (some) data */
  341. if ( ( rc = http->state->rx ( http, &iobuf ) ) != 0 )
  342. goto err;
  343. }
  344. /* Free I/O buffer, if applicable */
  345. free_iob ( iobuf );
  346. profile_stop ( &http_rx_profiler );
  347. return 0;
  348. err:
  349. free_iob ( iobuf );
  350. http_close ( http, rc );
  351. return rc;
  352. }
  353. /**
  354. * Handle server connection close
  355. *
  356. * @v http HTTP transaction
  357. * @v rc Reason for close
  358. */
  359. static void http_conn_close ( struct http_transaction *http, int rc ) {
  360. /* Sanity checks */
  361. assert ( http->state != NULL );
  362. assert ( http->state->close != NULL );
  363. /* Restart server connection interface */
  364. intf_restart ( &http->conn, rc );
  365. /* Hand off to state-specific method */
  366. http->state->close ( http, rc );
  367. }
  368. /**
  369. * Handle received content-decoded data
  370. *
  371. * @v http HTTP transaction
  372. * @v iobuf I/O buffer
  373. * @v meta Data transfer metadata
  374. */
  375. static int http_content_deliver ( struct http_transaction *http,
  376. struct io_buffer *iobuf,
  377. struct xfer_metadata *meta ) {
  378. int rc;
  379. /* Ignore content if this is anything other than a successful
  380. * transfer.
  381. */
  382. if ( http->response.rc != 0 ) {
  383. free_iob ( iobuf );
  384. return 0;
  385. }
  386. /* Deliver to data transfer interface */
  387. profile_start ( &http_xfer_profiler );
  388. if ( ( rc = xfer_deliver ( &http->xfer, iob_disown ( iobuf ),
  389. meta ) ) != 0 )
  390. return rc;
  391. profile_stop ( &http_xfer_profiler );
  392. return 0;
  393. }
  394. /**
  395. * Get underlying data transfer buffer
  396. *
  397. * @v http HTTP transaction
  398. * @ret xferbuf Data transfer buffer, or NULL on error
  399. */
  400. static struct xfer_buffer *
  401. http_content_buffer ( struct http_transaction *http ) {
  402. /* Deny access to the data transfer buffer if this is anything
  403. * other than a successful transfer.
  404. */
  405. if ( http->response.rc != 0 )
  406. return NULL;
  407. /* Hand off to data transfer interface */
  408. return xfer_buffer ( &http->xfer );
  409. }
  410. /**
  411. * Read from block device (when HTTP block device support is not present)
  412. *
  413. * @v http HTTP transaction
  414. * @v data Data interface
  415. * @v lba Starting logical block address
  416. * @v count Number of logical blocks
  417. * @v buffer Data buffer
  418. * @v len Length of data buffer
  419. * @ret rc Return status code
  420. */
  421. __weak int http_block_read ( struct http_transaction *http __unused,
  422. struct interface *data __unused,
  423. uint64_t lba __unused, unsigned int count __unused,
  424. userptr_t buffer __unused, size_t len __unused ) {
  425. return -ENOTSUP;
  426. }
  427. /**
  428. * Read block device capacity (when HTTP block device support is not present)
  429. *
  430. * @v control Control interface
  431. * @v data Data interface
  432. * @ret rc Return status code
  433. */
  434. __weak int http_block_read_capacity ( struct http_transaction *http __unused,
  435. struct interface *data __unused ) {
  436. return -ENOTSUP;
  437. }
  438. /**
  439. * Describe device in ACPI table (when HTTP block device support is not present)
  440. *
  441. * @v http HTTP transaction
  442. * @v acpi ACPI table
  443. * @v len Length of ACPI table
  444. * @ret rc Return status code
  445. */
  446. __weak int http_acpi_describe ( struct http_transaction *http __unused,
  447. struct acpi_description_header *acpi __unused,
  448. size_t len __unused ) {
  449. return -ENOTSUP;
  450. }
  451. /** HTTP data transfer interface operations */
  452. static struct interface_operation http_xfer_operations[] = {
  453. INTF_OP ( block_read, struct http_transaction *, http_block_read ),
  454. INTF_OP ( block_read_capacity, struct http_transaction *,
  455. http_block_read_capacity ),
  456. INTF_OP ( acpi_describe, struct http_transaction *,
  457. http_acpi_describe ),
  458. INTF_OP ( xfer_window_changed, struct http_transaction *, http_step ),
  459. INTF_OP ( intf_close, struct http_transaction *, http_close ),
  460. };
  461. /** HTTP data transfer interface descriptor */
  462. static struct interface_descriptor http_xfer_desc =
  463. INTF_DESC_PASSTHRU ( struct http_transaction, xfer,
  464. http_xfer_operations, content );
  465. /** HTTP content-decoded interface operations */
  466. static struct interface_operation http_content_operations[] = {
  467. INTF_OP ( xfer_deliver, struct http_transaction *,
  468. http_content_deliver ),
  469. INTF_OP ( xfer_buffer, struct http_transaction *, http_content_buffer ),
  470. INTF_OP ( intf_close, struct http_transaction *, http_close ),
  471. };
  472. /** HTTP content-decoded interface descriptor */
  473. static struct interface_descriptor http_content_desc =
  474. INTF_DESC_PASSTHRU ( struct http_transaction, content,
  475. http_content_operations, xfer );
  476. /** HTTP transfer-decoded interface operations */
  477. static struct interface_operation http_transfer_operations[] = {
  478. INTF_OP ( intf_close, struct http_transaction *, http_close ),
  479. };
  480. /** HTTP transfer-decoded interface descriptor */
  481. static struct interface_descriptor http_transfer_desc =
  482. INTF_DESC_PASSTHRU ( struct http_transaction, transfer,
  483. http_transfer_operations, conn );
  484. /** HTTP server connection interface operations */
  485. static struct interface_operation http_conn_operations[] = {
  486. INTF_OP ( xfer_deliver, struct http_transaction *, http_conn_deliver ),
  487. INTF_OP ( xfer_window_changed, struct http_transaction *, http_step ),
  488. INTF_OP ( pool_reopen, struct http_transaction *, http_reopen ),
  489. INTF_OP ( intf_close, struct http_transaction *, http_conn_close ),
  490. };
  491. /** HTTP server connection interface descriptor */
  492. static struct interface_descriptor http_conn_desc =
  493. INTF_DESC_PASSTHRU ( struct http_transaction, conn,
  494. http_conn_operations, transfer );
  495. /** HTTP process descriptor */
  496. static struct process_descriptor http_process_desc =
  497. PROC_DESC_ONCE ( struct http_transaction, process, http_step );
  498. /**
  499. * Open HTTP transaction
  500. *
  501. * @v xfer Data transfer interface
  502. * @v method Request method
  503. * @v uri Request URI
  504. * @v range Content range (if any)
  505. * @v content Request content (if any)
  506. * @ret rc Return status code
  507. */
  508. int http_open ( struct interface *xfer, struct http_method *method,
  509. struct uri *uri, struct http_request_range *range,
  510. struct http_request_content *content ) {
  511. struct http_transaction *http;
  512. struct uri request_uri;
  513. struct uri request_host;
  514. size_t request_uri_len;
  515. size_t request_host_len;
  516. size_t content_len;
  517. char *request_uri_string;
  518. char *request_host_string;
  519. void *content_data;
  520. int rc;
  521. /* Calculate request URI length */
  522. memset ( &request_uri, 0, sizeof ( request_uri ) );
  523. request_uri.path = ( uri->path ? uri->path : "/" );
  524. request_uri.query = uri->query;
  525. request_uri_len =
  526. ( format_uri ( &request_uri, NULL, 0 ) + 1 /* NUL */);
  527. /* Calculate host name length */
  528. memset ( &request_host, 0, sizeof ( request_host ) );
  529. request_host.host = uri->host;
  530. request_host.port = uri->port;
  531. request_host_len =
  532. ( format_uri ( &request_host, NULL, 0 ) + 1 /* NUL */ );
  533. /* Calculate request content length */
  534. content_len = ( content ? content->len : 0 );
  535. /* Allocate and initialise structure */
  536. http = zalloc ( sizeof ( *http ) + request_uri_len + request_host_len +
  537. content_len );
  538. if ( ! http ) {
  539. rc = -ENOMEM;
  540. goto err_alloc;
  541. }
  542. request_uri_string = ( ( ( void * ) http ) + sizeof ( *http ) );
  543. request_host_string = ( request_uri_string + request_uri_len );
  544. content_data = ( request_host_string + request_host_len );
  545. format_uri ( &request_uri, request_uri_string, request_uri_len );
  546. format_uri ( &request_host, request_host_string, request_host_len );
  547. ref_init ( &http->refcnt, http_free );
  548. intf_init ( &http->xfer, &http_xfer_desc, &http->refcnt );
  549. intf_init ( &http->content, &http_content_desc, &http->refcnt );
  550. intf_init ( &http->transfer, &http_transfer_desc, &http->refcnt );
  551. intf_init ( &http->conn, &http_conn_desc, &http->refcnt );
  552. intf_plug_plug ( &http->transfer, &http->content );
  553. process_init ( &http->process, &http_process_desc, &http->refcnt );
  554. timer_init ( &http->timer, http_expired, &http->refcnt );
  555. http->uri = uri_get ( uri );
  556. http->request.method = method;
  557. http->request.uri = request_uri_string;
  558. http->request.host = request_host_string;
  559. if ( range ) {
  560. memcpy ( &http->request.range, range,
  561. sizeof ( http->request.range ) );
  562. }
  563. if ( content ) {
  564. http->request.content.type = content->type;
  565. http->request.content.data = content_data;
  566. http->request.content.len = content_len;
  567. memcpy ( content_data, content->data, content_len );
  568. }
  569. http->state = &http_request;
  570. DBGC2 ( http, "HTTP %p %s://%s%s\n", http, http->uri->scheme,
  571. http->request.host, http->request.uri );
  572. /* Open connection */
  573. if ( ( rc = http_connect ( &http->conn, uri ) ) != 0 ) {
  574. DBGC ( http, "HTTP %p could not connect: %s\n",
  575. http, strerror ( rc ) );
  576. goto err_connect;
  577. }
  578. /* Attach to parent interface, mortalise self, and return */
  579. intf_plug_plug ( &http->xfer, xfer );
  580. ref_put ( &http->refcnt );
  581. return 0;
  582. err_connect:
  583. http_close ( http, rc );
  584. ref_put ( &http->refcnt );
  585. err_alloc:
  586. return rc;
  587. }
  588. /**
  589. * Redirect HTTP transaction
  590. *
  591. * @v http HTTP transaction
  592. * @v location New location
  593. * @ret rc Return status code
  594. */
  595. static int http_redirect ( struct http_transaction *http,
  596. const char *location ) {
  597. struct uri *location_uri;
  598. struct uri *resolved_uri;
  599. int rc;
  600. DBGC2 ( http, "HTTP %p redirecting to \"%s\"\n", http, location );
  601. /* Parse location URI */
  602. location_uri = parse_uri ( location );
  603. if ( ! location_uri ) {
  604. rc = -ENOMEM;
  605. goto err_parse_uri;
  606. }
  607. /* Resolve as relative to original URI */
  608. resolved_uri = resolve_uri ( http->uri, location_uri );
  609. if ( ! resolved_uri ) {
  610. rc = -ENOMEM;
  611. goto err_resolve_uri;
  612. }
  613. /* Redirect to new URI */
  614. if ( ( rc = xfer_redirect ( &http->xfer, LOCATION_URI,
  615. resolved_uri ) ) != 0 ) {
  616. DBGC ( http, "HTTP %p could not redirect: %s\n",
  617. http, strerror ( rc ) );
  618. goto err_redirect;
  619. }
  620. err_redirect:
  621. uri_put ( resolved_uri );
  622. err_resolve_uri:
  623. uri_put ( location_uri );
  624. err_parse_uri:
  625. return rc;
  626. }
  627. /**
  628. * Handle successful transfer completion
  629. *
  630. * @v http HTTP transaction
  631. * @ret rc Return status code
  632. */
  633. static int http_transfer_complete ( struct http_transaction *http ) {
  634. struct http_authentication *auth;
  635. const char *location;
  636. int rc;
  637. /* Keep connection alive if applicable */
  638. if ( http->response.flags & HTTP_RESPONSE_KEEPALIVE )
  639. pool_recycle ( &http->conn );
  640. /* Restart server connection interface */
  641. intf_restart ( &http->conn, 0 );
  642. /* No more data is expected */
  643. http->state = NULL;
  644. /* If transaction is successful, then close the
  645. * transfer-decoded interface. The content encoding may
  646. * choose whether or not to immediately terminate the
  647. * transaction.
  648. */
  649. if ( http->response.rc == 0 ) {
  650. intf_shutdown ( &http->transfer, 0 );
  651. return 0;
  652. }
  653. /* Perform redirection, if applicable */
  654. if ( ( location = http->response.location ) ) {
  655. if ( ( rc = http_redirect ( http, location ) ) != 0 )
  656. return rc;
  657. http_close ( http, 0 );
  658. return 0;
  659. }
  660. /* Fail unless a retry is permitted */
  661. if ( ! ( http->response.flags & HTTP_RESPONSE_RETRY ) )
  662. return http->response.rc;
  663. /* Perform authentication, if applicable */
  664. if ( ( auth = http->response.auth.auth ) ) {
  665. http->request.auth.auth = auth;
  666. DBGC2 ( http, "HTTP %p performing %s authentication\n",
  667. http, auth->name );
  668. if ( ( rc = auth->authenticate ( http ) ) != 0 ) {
  669. DBGC ( http, "HTTP %p could not authenticate: %s\n",
  670. http, strerror ( rc ) );
  671. return rc;
  672. }
  673. }
  674. /* Restart content decoding interfaces (which may be attached
  675. * to the same object).
  676. */
  677. intf_nullify ( &http->transfer ); /* avoid potential loops */
  678. intf_restart ( &http->content, http->response.rc );
  679. intf_restart ( &http->transfer, http->response.rc );
  680. intf_plug_plug ( &http->transfer, &http->content );
  681. http->len = 0;
  682. assert ( http->remaining == 0 );
  683. /* Start timer to initiate retry */
  684. DBGC2 ( http, "HTTP %p retrying after %d seconds\n",
  685. http, http->response.retry_after );
  686. start_timer_fixed ( &http->timer,
  687. ( http->response.retry_after * TICKS_PER_SEC ) );
  688. return 0;
  689. }
  690. /******************************************************************************
  691. *
  692. * Requests
  693. *
  694. ******************************************************************************
  695. */
  696. /**
  697. * Construct HTTP request headers
  698. *
  699. * @v http HTTP transaction
  700. * @v buf Buffer
  701. * @v len Length of buffer
  702. * @ret len Length, or negative error
  703. */
  704. static int http_format_headers ( struct http_transaction *http, char *buf,
  705. size_t len ) {
  706. struct http_request_header *header;
  707. size_t used;
  708. size_t remaining;
  709. char *line;
  710. int value_len;
  711. int rc;
  712. /* Construct request line */
  713. used = ssnprintf ( buf, len, "%s %s HTTP/1.1",
  714. http->request.method->name, http->request.uri );
  715. if ( used < len )
  716. DBGC2 ( http, "HTTP %p TX %s\n", http, buf );
  717. used += ssnprintf ( ( buf + used ), ( len - used ), "\r\n" );
  718. /* Construct all headers */
  719. for_each_table_entry ( header, HTTP_REQUEST_HEADERS ) {
  720. /* Determine header value length */
  721. value_len = header->format ( http, NULL, 0 );
  722. if ( value_len < 0 ) {
  723. rc = value_len;
  724. return rc;
  725. }
  726. /* Skip zero-length headers */
  727. if ( ! value_len )
  728. continue;
  729. /* Construct header */
  730. line = ( buf + used );
  731. used += ssnprintf ( ( buf + used ), ( len - used ), "%s: ",
  732. header->name );
  733. remaining = ( ( used < len ) ? ( len - used ) : 0 );
  734. used += header->format ( http, ( buf + used ), remaining );
  735. if ( used < len )
  736. DBGC2 ( http, "HTTP %p TX %s\n", http, line );
  737. used += ssnprintf ( ( buf + used ), ( len - used ), "\r\n" );
  738. }
  739. /* Construct terminating newline */
  740. used += ssnprintf ( ( buf + used ), ( len - used ), "\r\n" );
  741. return used;
  742. }
  743. /**
  744. * Construct HTTP "Host" header
  745. *
  746. * @v http HTTP transaction
  747. * @v buf Buffer
  748. * @v len Length of buffer
  749. * @ret len Length of header value, or negative error
  750. */
  751. static int http_format_host ( struct http_transaction *http, char *buf,
  752. size_t len ) {
  753. /* Construct host URI */
  754. return snprintf ( buf, len, "%s", http->request.host );
  755. }
  756. /** HTTP "Host" header "*/
  757. struct http_request_header http_request_host __http_request_header = {
  758. .name = "Host",
  759. .format = http_format_host,
  760. };
  761. /**
  762. * Construct HTTP "User-Agent" header
  763. *
  764. * @v http HTTP transaction
  765. * @v buf Buffer
  766. * @v len Length of buffer
  767. * @ret len Length of header value, or negative error
  768. */
  769. static int http_format_user_agent ( struct http_transaction *http __unused,
  770. char *buf, size_t len ) {
  771. /* Construct user agent */
  772. return snprintf ( buf, len, "iPXE/%s", product_version );
  773. }
  774. /** HTTP "User-Agent" header */
  775. struct http_request_header http_request_user_agent __http_request_header = {
  776. .name = "User-Agent",
  777. .format = http_format_user_agent,
  778. };
  779. /**
  780. * Construct HTTP "Connection" header
  781. *
  782. * @v http HTTP transaction
  783. * @v buf Buffer
  784. * @v len Length of buffer
  785. * @ret len Length of header value, or negative error
  786. */
  787. static int http_format_connection ( struct http_transaction *http __unused,
  788. char *buf, size_t len ) {
  789. /* Always request keep-alive */
  790. return snprintf ( buf, len, "keep-alive" );
  791. }
  792. /** HTTP "Connection" header */
  793. struct http_request_header http_request_connection __http_request_header = {
  794. .name = "Connection",
  795. .format = http_format_connection,
  796. };
  797. /**
  798. * Construct HTTP "Range" header
  799. *
  800. * @v http HTTP transaction
  801. * @v buf Buffer
  802. * @v len Length of buffer
  803. * @ret len Length of header value, or negative error
  804. */
  805. static int http_format_range ( struct http_transaction *http,
  806. char *buf, size_t len ) {
  807. /* Construct range, if applicable */
  808. if ( http->request.range.len ) {
  809. return snprintf ( buf, len, "bytes=%zd-%zd",
  810. http->request.range.start,
  811. ( http->request.range.start +
  812. http->request.range.len - 1 ) );
  813. } else {
  814. return 0;
  815. }
  816. }
  817. /** HTTP "Range" header */
  818. struct http_request_header http_request_range __http_request_header = {
  819. .name = "Range",
  820. .format = http_format_range,
  821. };
  822. /**
  823. * Construct HTTP "Content-Type" header
  824. *
  825. * @v http HTTP transaction
  826. * @v buf Buffer
  827. * @v len Length of buffer
  828. * @ret len Length of header value, or negative error
  829. */
  830. static int http_format_content_type ( struct http_transaction *http,
  831. char *buf, size_t len ) {
  832. /* Construct content type, if applicable */
  833. if ( http->request.content.type ) {
  834. return snprintf ( buf, len, "%s", http->request.content.type );
  835. } else {
  836. return 0;
  837. }
  838. }
  839. /** HTTP "Content-Type" header */
  840. struct http_request_header http_request_content_type __http_request_header = {
  841. .name = "Content-Type",
  842. .format = http_format_content_type,
  843. };
  844. /**
  845. * Construct HTTP "Content-Length" header
  846. *
  847. * @v http HTTP transaction
  848. * @v buf Buffer
  849. * @v len Length of buffer
  850. * @ret len Length of header value, or negative error
  851. */
  852. static int http_format_content_length ( struct http_transaction *http,
  853. char *buf, size_t len ) {
  854. /* Construct content length, if applicable */
  855. if ( http->request.content.len ) {
  856. return snprintf ( buf, len, "%zd", http->request.content.len );
  857. } else {
  858. return 0;
  859. }
  860. }
  861. /** HTTP "Content-Length" header */
  862. struct http_request_header http_request_content_length __http_request_header = {
  863. .name = "Content-Length",
  864. .format = http_format_content_length,
  865. };
  866. /**
  867. * Construct HTTP "Accept-Encoding" header
  868. *
  869. * @v http HTTP transaction
  870. * @v buf Buffer
  871. * @v len Length of buffer
  872. * @ret len Length of header value, or negative error
  873. */
  874. static int http_format_accept_encoding ( struct http_transaction *http,
  875. char *buf, size_t len ) {
  876. struct http_content_encoding *encoding;
  877. const char *sep = "";
  878. size_t used = 0;
  879. /* Construct list of content encodings */
  880. for_each_table_entry ( encoding, HTTP_CONTENT_ENCODINGS ) {
  881. if ( encoding->supported && ( ! encoding->supported ( http ) ) )
  882. continue;
  883. used += ssnprintf ( ( buf + used ), ( len - used ),
  884. "%s%s", sep, encoding->name );
  885. sep = ", ";
  886. }
  887. return used;
  888. }
  889. /** HTTP "Accept-Encoding" header */
  890. struct http_request_header http_request_accept_encoding __http_request_header ={
  891. .name = "Accept-Encoding",
  892. .format = http_format_accept_encoding,
  893. };
  894. /**
  895. * Transmit request
  896. *
  897. * @v http HTTP transaction
  898. * @ret rc Return status code
  899. */
  900. static int http_tx_request ( struct http_transaction *http ) {
  901. struct io_buffer *iobuf;
  902. int len;
  903. int check_len;
  904. int rc;
  905. /* Calculate request length */
  906. len = http_format_headers ( http, NULL, 0 );
  907. if ( len < 0 ) {
  908. rc = len;
  909. DBGC ( http, "HTTP %p could not construct request: %s\n",
  910. http, strerror ( rc ) );
  911. goto err_len;
  912. }
  913. /* Allocate I/O buffer */
  914. iobuf = alloc_iob ( len + 1 /* NUL */ + http->request.content.len );
  915. if ( ! iobuf ) {
  916. rc = -ENOMEM;
  917. goto err_alloc;
  918. }
  919. /* Construct request */
  920. check_len = http_format_headers ( http, iob_put ( iobuf, len ),
  921. ( len + 1 /* NUL */ ) );
  922. assert ( check_len == len );
  923. memcpy ( iob_put ( iobuf, http->request.content.len ),
  924. http->request.content.data, http->request.content.len );
  925. /* Deliver request */
  926. if ( ( rc = xfer_deliver_iob ( &http->conn,
  927. iob_disown ( iobuf ) ) ) != 0 ) {
  928. DBGC ( http, "HTTP %p could not deliver request: %s\n",
  929. http, strerror ( rc ) );
  930. goto err_deliver;
  931. }
  932. /* Clear any previous response */
  933. empty_line_buffer ( &http->response.headers );
  934. memset ( &http->response, 0, sizeof ( http->response ) );
  935. /* Move to response headers state */
  936. http->state = &http_headers;
  937. return 0;
  938. err_deliver:
  939. free_iob ( iobuf );
  940. err_alloc:
  941. err_len:
  942. return rc;
  943. }
  944. /** HTTP request state */
  945. static struct http_state http_request = {
  946. .tx = http_tx_request,
  947. .close = http_close_error,
  948. };
  949. /******************************************************************************
  950. *
  951. * Response headers
  952. *
  953. ******************************************************************************
  954. */
  955. /**
  956. * Parse HTTP status line
  957. *
  958. * @v http HTTP transaction
  959. * @v line Status line
  960. * @ret rc Return status code
  961. */
  962. static int http_parse_status ( struct http_transaction *http, char *line ) {
  963. char *endp;
  964. char *version;
  965. char *vernum;
  966. char *status;
  967. int response_rc;
  968. DBGC2 ( http, "HTTP %p RX %s\n", http, line );
  969. /* Parse HTTP version */
  970. version = http_token ( &line, NULL );
  971. if ( ( ! version ) || ( strncmp ( version, "HTTP/", 5 ) != 0 ) ) {
  972. DBGC ( http, "HTTP %p malformed version \"%s\"\n", http, line );
  973. return -EINVAL_STATUS;
  974. }
  975. /* Keepalive is enabled by default for anything newer than HTTP/1.0 */
  976. vernum = ( version + 5 /* "HTTP/" (presence already checked) */ );
  977. if ( vernum[0] == '0' ) {
  978. /* HTTP/0.x : keepalive not enabled by default */
  979. } else if ( strncmp ( vernum, "1.0", 3 ) == 0 ) {
  980. /* HTTP/1.0 : keepalive not enabled by default */
  981. } else {
  982. /* HTTP/1.1 or newer: keepalive enabled by default */
  983. http->response.flags |= HTTP_RESPONSE_KEEPALIVE;
  984. }
  985. /* Parse status code */
  986. status = line;
  987. http->response.status = strtoul ( status, &endp, 10 );
  988. if ( *endp != ' ' ) {
  989. DBGC ( http, "HTTP %p malformed status code \"%s\"\n",
  990. http, status );
  991. return -EINVAL_STATUS;
  992. }
  993. /* Convert HTTP status code to iPXE return status code */
  994. if ( status[0] == '2' ) {
  995. /* 2xx Success */
  996. response_rc = 0;
  997. } else if ( status[0] == '3' ) {
  998. /* 3xx Redirection */
  999. response_rc = -EXDEV;
  1000. } else if ( http->response.status == 401 ) {
  1001. /* 401 Unauthorized */
  1002. response_rc = -EACCES_401;
  1003. } else if ( http->response.status == 403 ) {
  1004. /* 403 Forbidden */
  1005. response_rc = -EPERM_403;
  1006. } else if ( http->response.status == 404 ) {
  1007. /* 404 Not Found */
  1008. response_rc = -ENOENT_404;
  1009. } else if ( status[0] == '4' ) {
  1010. /* 4xx Client Error (not already specified) */
  1011. response_rc = -EIO_4XX;
  1012. } else if ( status[0] == '5' ) {
  1013. /* 5xx Server Error */
  1014. response_rc = -EIO_5XX;
  1015. } else {
  1016. /* Unrecognised */
  1017. response_rc = -EIO_OTHER;
  1018. }
  1019. http->response.rc = response_rc;
  1020. return 0;
  1021. }
  1022. /**
  1023. * Parse HTTP header
  1024. *
  1025. * @v http HTTP transaction
  1026. * @v line Header line
  1027. * @ret rc Return status code
  1028. */
  1029. static int http_parse_header ( struct http_transaction *http, char *line ) {
  1030. struct http_response_header *header;
  1031. char *name = line;
  1032. char *sep;
  1033. DBGC2 ( http, "HTTP %p RX %s\n", http, line );
  1034. /* Extract header name */
  1035. sep = strchr ( line, ':' );
  1036. if ( ! sep ) {
  1037. DBGC ( http, "HTTP %p malformed header \"%s\"\n", http, line );
  1038. return -EINVAL_HEADER;
  1039. }
  1040. *sep = '\0';
  1041. /* Extract remainder of line */
  1042. line = ( sep + 1 );
  1043. while ( isspace ( *line ) )
  1044. line++;
  1045. /* Process header, if recognised */
  1046. for_each_table_entry ( header, HTTP_RESPONSE_HEADERS ) {
  1047. if ( strcasecmp ( name, header->name ) == 0 )
  1048. return header->parse ( http, line );
  1049. }
  1050. /* Unrecognised headers should be ignored */
  1051. return 0;
  1052. }
  1053. /**
  1054. * Parse HTTP response headers
  1055. *
  1056. * @v http HTTP transaction
  1057. * @ret rc Return status code
  1058. */
  1059. static int http_parse_headers ( struct http_transaction *http ) {
  1060. char *line;
  1061. char *next;
  1062. int rc;
  1063. /* Get status line */
  1064. line = http->response.headers.data;
  1065. assert ( line != NULL );
  1066. next = ( line + strlen ( line ) + 1 /* NUL */ );
  1067. /* Parse status line */
  1068. if ( ( rc = http_parse_status ( http, line ) ) != 0 )
  1069. return rc;
  1070. /* Process header lines */
  1071. while ( 1 ) {
  1072. /* Move to next line */
  1073. line = next;
  1074. next = ( line + strlen ( line ) + 1 /* NUL */ );
  1075. /* Stop on terminating blank line */
  1076. if ( ! line[0] )
  1077. return 0;
  1078. /* Process header line */
  1079. if ( ( rc = http_parse_header ( http, line ) ) != 0 )
  1080. return rc;
  1081. }
  1082. }
  1083. /**
  1084. * Parse HTTP "Location" header
  1085. *
  1086. * @v http HTTP transaction
  1087. * @v line Remaining header line
  1088. * @ret rc Return status code
  1089. */
  1090. static int http_parse_location ( struct http_transaction *http, char *line ) {
  1091. /* Store location */
  1092. http->response.location = line;
  1093. return 0;
  1094. }
  1095. /** HTTP "Location" header */
  1096. struct http_response_header http_response_location __http_response_header = {
  1097. .name = "Location",
  1098. .parse = http_parse_location,
  1099. };
  1100. /**
  1101. * Parse HTTP "Transfer-Encoding" header
  1102. *
  1103. * @v http HTTP transaction
  1104. * @v line Remaining header line
  1105. * @ret rc Return status code
  1106. */
  1107. static int http_parse_transfer_encoding ( struct http_transaction *http,
  1108. char *line ) {
  1109. struct http_transfer_encoding *encoding;
  1110. /* Check for known transfer encodings */
  1111. for_each_table_entry ( encoding, HTTP_TRANSFER_ENCODINGS ) {
  1112. if ( strcasecmp ( line, encoding->name ) == 0 ) {
  1113. http->response.transfer.encoding = encoding;
  1114. return 0;
  1115. }
  1116. }
  1117. DBGC ( http, "HTTP %p unrecognised Transfer-Encoding \"%s\"\n",
  1118. http, line );
  1119. return -ENOTSUP_TRANSFER;
  1120. }
  1121. /** HTTP "Transfer-Encoding" header */
  1122. struct http_response_header
  1123. http_response_transfer_encoding __http_response_header = {
  1124. .name = "Transfer-Encoding",
  1125. .parse = http_parse_transfer_encoding,
  1126. };
  1127. /**
  1128. * Parse HTTP "Connection" header
  1129. *
  1130. * @v http HTTP transaction
  1131. * @v line Remaining header line
  1132. * @ret rc Return status code
  1133. */
  1134. static int http_parse_connection ( struct http_transaction *http, char *line ) {
  1135. char *token;
  1136. /* Check for known connection intentions */
  1137. while ( ( token = http_token ( &line, NULL ) ) ) {
  1138. if ( strcasecmp ( token, "keep-alive" ) == 0 )
  1139. http->response.flags |= HTTP_RESPONSE_KEEPALIVE;
  1140. if ( strcasecmp ( token, "close" ) == 0 )
  1141. http->response.flags &= ~HTTP_RESPONSE_KEEPALIVE;
  1142. }
  1143. return 0;
  1144. }
  1145. /** HTTP "Connection" header */
  1146. struct http_response_header http_response_connection __http_response_header = {
  1147. .name = "Connection",
  1148. .parse = http_parse_connection,
  1149. };
  1150. /**
  1151. * Parse HTTP "Content-Length" header
  1152. *
  1153. * @v http HTTP transaction
  1154. * @v line Remaining header line
  1155. * @ret rc Return status code
  1156. */
  1157. static int http_parse_content_length ( struct http_transaction *http,
  1158. char *line ) {
  1159. char *endp;
  1160. /* Parse length */
  1161. http->response.content.len = strtoul ( line, &endp, 10 );
  1162. if ( *endp != '\0' ) {
  1163. DBGC ( http, "HTTP %p invalid Content-Length \"%s\"\n",
  1164. http, line );
  1165. return -EINVAL_CONTENT_LENGTH;
  1166. }
  1167. /* Record that we have a content length (since it may be zero) */
  1168. http->response.flags |= HTTP_RESPONSE_CONTENT_LEN;
  1169. return 0;
  1170. }
  1171. /** HTTP "Content-Length" header */
  1172. struct http_response_header
  1173. http_response_content_length __http_response_header = {
  1174. .name = "Content-Length",
  1175. .parse = http_parse_content_length,
  1176. };
  1177. /**
  1178. * Parse HTTP "Content-Encoding" header
  1179. *
  1180. * @v http HTTP transaction
  1181. * @v line Remaining header line
  1182. * @ret rc Return status code
  1183. */
  1184. static int http_parse_content_encoding ( struct http_transaction *http,
  1185. char *line ) {
  1186. struct http_content_encoding *encoding;
  1187. /* Check for known content encodings */
  1188. for_each_table_entry ( encoding, HTTP_CONTENT_ENCODINGS ) {
  1189. if ( encoding->supported && ( ! encoding->supported ( http ) ) )
  1190. continue;
  1191. if ( strcasecmp ( line, encoding->name ) == 0 ) {
  1192. http->response.content.encoding = encoding;
  1193. return 0;
  1194. }
  1195. }
  1196. /* Some servers (e.g. Apache) have a habit of specifying
  1197. * unwarranted content encodings. For example, if Apache
  1198. * detects (via /etc/httpd/conf/magic) that a file's contents
  1199. * are gzip-compressed, it will set "Content-Encoding: x-gzip"
  1200. * regardless of the client's Accept-Encoding header. The
  1201. * only viable way to handle such servers is to treat unknown
  1202. * content encodings as equivalent to "identity".
  1203. */
  1204. DBGC ( http, "HTTP %p unrecognised Content-Encoding \"%s\"\n",
  1205. http, line );
  1206. return 0;
  1207. }
  1208. /** HTTP "Content-Encoding" header */
  1209. struct http_response_header
  1210. http_response_content_encoding __http_response_header = {
  1211. .name = "Content-Encoding",
  1212. .parse = http_parse_content_encoding,
  1213. };
  1214. /**
  1215. * Parse HTTP "Retry-After" header
  1216. *
  1217. * @v http HTTP transaction
  1218. * @v line Remaining header line
  1219. * @ret rc Return status code
  1220. */
  1221. static int http_parse_retry_after ( struct http_transaction *http,
  1222. char *line ) {
  1223. char *endp;
  1224. /* Try to parse value as a simple number of seconds */
  1225. http->response.retry_after = strtoul ( line, &endp, 10 );
  1226. if ( *endp != '\0' ) {
  1227. /* For any value which is not a simple number of
  1228. * seconds (e.g. a full HTTP date), just retry after a
  1229. * fixed delay, since we don't have code able to parse
  1230. * full HTTP dates.
  1231. */
  1232. http->response.retry_after = HTTP_RETRY_SECONDS;
  1233. DBGC ( http, "HTTP %p cannot understand Retry-After \"%s\"; "
  1234. "using %d seconds\n", http, line, HTTP_RETRY_SECONDS );
  1235. }
  1236. /* Allow HTTP request to be retried after specified delay */
  1237. http->response.flags |= HTTP_RESPONSE_RETRY;
  1238. return 0;
  1239. }
  1240. /** HTTP "Retry-After" header */
  1241. struct http_response_header http_response_retry_after __http_response_header = {
  1242. .name = "Retry-After",
  1243. .parse = http_parse_retry_after,
  1244. };
  1245. /**
  1246. * Handle received HTTP headers
  1247. *
  1248. * @v http HTTP transaction
  1249. * @v iobuf I/O buffer (may be claimed)
  1250. * @ret rc Return status code
  1251. */
  1252. static int http_rx_headers ( struct http_transaction *http,
  1253. struct io_buffer **iobuf ) {
  1254. struct http_transfer_encoding *transfer;
  1255. struct http_content_encoding *content;
  1256. char *line;
  1257. int rc;
  1258. /* Buffer header line */
  1259. if ( ( rc = http_rx_linebuf ( http, *iobuf,
  1260. &http->response.headers ) ) != 0 )
  1261. return rc;
  1262. /* Wait until we see the empty line marking end of headers */
  1263. line = buffered_line ( &http->response.headers );
  1264. if ( ( line == NULL ) || ( line[0] != '\0' ) )
  1265. return 0;
  1266. /* Process headers */
  1267. if ( ( rc = http_parse_headers ( http ) ) != 0 )
  1268. return rc;
  1269. /* Initialise content encoding, if applicable */
  1270. if ( ( content = http->response.content.encoding ) &&
  1271. ( ( rc = content->init ( http ) ) != 0 ) ) {
  1272. DBGC ( http, "HTTP %p could not initialise %s content "
  1273. "encoding: %s\n", http, content->name, strerror ( rc ) );
  1274. return rc;
  1275. }
  1276. /* Presize receive buffer, if we have a content length */
  1277. if ( http->response.content.len ) {
  1278. xfer_seek ( &http->transfer, http->response.content.len );
  1279. xfer_seek ( &http->transfer, 0 );
  1280. }
  1281. /* Complete transfer if this is a HEAD request */
  1282. if ( http->request.method == &http_head ) {
  1283. if ( ( rc = http_transfer_complete ( http ) ) != 0 )
  1284. return rc;
  1285. return 0;
  1286. }
  1287. /* Default to identity transfer encoding, if none specified */
  1288. if ( ! http->response.transfer.encoding )
  1289. http->response.transfer.encoding = &http_transfer_identity;
  1290. /* Move to transfer encoding-specific data state */
  1291. transfer = http->response.transfer.encoding;
  1292. http->state = &transfer->state;
  1293. /* Initialise transfer encoding */
  1294. if ( ( rc = transfer->init ( http ) ) != 0 ) {
  1295. DBGC ( http, "HTTP %p could not initialise %s transfer "
  1296. "encoding: %s\n", http, transfer->name, strerror ( rc ));
  1297. return rc;
  1298. }
  1299. return 0;
  1300. }
  1301. /** HTTP response headers state */
  1302. static struct http_state http_headers = {
  1303. .rx = http_rx_headers,
  1304. .close = http_close_error,
  1305. };
  1306. /******************************************************************************
  1307. *
  1308. * Identity transfer encoding
  1309. *
  1310. ******************************************************************************
  1311. */
  1312. /**
  1313. * Initialise transfer encoding
  1314. *
  1315. * @v http HTTP transaction
  1316. * @ret rc Return status code
  1317. */
  1318. static int http_init_transfer_identity ( struct http_transaction *http ) {
  1319. int rc;
  1320. /* Complete transfer immediately if we have a zero content length */
  1321. if ( ( http->response.flags & HTTP_RESPONSE_CONTENT_LEN ) &&
  1322. ( http->response.content.len == 0 ) &&
  1323. ( ( rc = http_transfer_complete ( http ) ) != 0 ) )
  1324. return rc;
  1325. return 0;
  1326. }
  1327. /**
  1328. * Handle received data
  1329. *
  1330. * @v http HTTP transaction
  1331. * @v iobuf I/O buffer (may be claimed)
  1332. * @ret rc Return status code
  1333. */
  1334. static int http_rx_transfer_identity ( struct http_transaction *http,
  1335. struct io_buffer **iobuf ) {
  1336. size_t len = iob_len ( *iobuf );
  1337. int rc;
  1338. /* Update lengths */
  1339. http->len += len;
  1340. /* Fail if this transfer would overrun the expected content
  1341. * length (if any).
  1342. */
  1343. if ( ( http->response.flags & HTTP_RESPONSE_CONTENT_LEN ) &&
  1344. ( http->len > http->response.content.len ) ) {
  1345. DBGC ( http, "HTTP %p content length overrun\n", http );
  1346. return -EIO_CONTENT_LENGTH;
  1347. }
  1348. /* Hand off to content encoding */
  1349. if ( ( rc = xfer_deliver_iob ( &http->transfer,
  1350. iob_disown ( *iobuf ) ) ) != 0 )
  1351. return rc;
  1352. /* Complete transfer if we have received the expected content
  1353. * length (if any).
  1354. */
  1355. if ( ( http->response.flags & HTTP_RESPONSE_CONTENT_LEN ) &&
  1356. ( http->len == http->response.content.len ) &&
  1357. ( ( rc = http_transfer_complete ( http ) ) != 0 ) )
  1358. return rc;
  1359. return 0;
  1360. }
  1361. /**
  1362. * Handle server connection close
  1363. *
  1364. * @v http HTTP transaction
  1365. * @v rc Reason for close
  1366. */
  1367. static void http_close_transfer_identity ( struct http_transaction *http,
  1368. int rc ) {
  1369. /* Fail if any error occurred */
  1370. if ( rc != 0 )
  1371. goto err;
  1372. /* Fail if we have a content length (since we would have
  1373. * already closed the connection if we had received the
  1374. * correct content length).
  1375. */
  1376. if ( http->response.flags & HTTP_RESPONSE_CONTENT_LEN ) {
  1377. DBGC ( http, "HTTP %p content length underrun\n", http );
  1378. rc = EIO_CONTENT_LENGTH;
  1379. goto err;
  1380. }
  1381. /* Indicate that transfer is complete */
  1382. if ( ( rc = http_transfer_complete ( http ) ) != 0 )
  1383. goto err;
  1384. return;
  1385. err:
  1386. http_close ( http, rc );
  1387. }
  1388. /** Identity transfer encoding */
  1389. static struct http_transfer_encoding http_transfer_identity = {
  1390. .name = "identity",
  1391. .init = http_init_transfer_identity,
  1392. .state = {
  1393. .rx = http_rx_transfer_identity,
  1394. .close = http_close_transfer_identity,
  1395. },
  1396. };
  1397. /******************************************************************************
  1398. *
  1399. * Chunked transfer encoding
  1400. *
  1401. ******************************************************************************
  1402. */
  1403. /**
  1404. * Initialise transfer encoding
  1405. *
  1406. * @v http HTTP transaction
  1407. * @ret rc Return status code
  1408. */
  1409. static int http_init_transfer_chunked ( struct http_transaction *http ) {
  1410. /* Sanity checks */
  1411. assert ( http->remaining == 0 );
  1412. assert ( http->linebuf.len == 0 );
  1413. return 0;
  1414. }
  1415. /**
  1416. * Handle received chunk length
  1417. *
  1418. * @v http HTTP transaction
  1419. * @v iobuf I/O buffer (may be claimed)
  1420. * @ret rc Return status code
  1421. */
  1422. static int http_rx_chunk_len ( struct http_transaction *http,
  1423. struct io_buffer **iobuf ) {
  1424. char *line;
  1425. char *endp;
  1426. size_t len;
  1427. int rc;
  1428. /* Receive into temporary line buffer */
  1429. if ( ( rc = http_rx_linebuf ( http, *iobuf, &http->linebuf ) ) != 0 )
  1430. return rc;
  1431. /* Wait until we receive a non-empty line */
  1432. line = buffered_line ( &http->linebuf );
  1433. if ( ( line == NULL ) || ( line[0] == '\0' ) )
  1434. return 0;
  1435. /* Parse chunk length */
  1436. http->remaining = strtoul ( line, &endp, 16 );
  1437. if ( *endp != '\0' ) {
  1438. DBGC ( http, "HTTP %p invalid chunk length \"%s\"\n",
  1439. http, line );
  1440. return -EINVAL_CHUNK_LENGTH;
  1441. }
  1442. /* Empty line buffer */
  1443. empty_line_buffer ( &http->linebuf );
  1444. /* Update expected length */
  1445. len = ( http->len + http->remaining );
  1446. xfer_seek ( &http->transfer, len );
  1447. xfer_seek ( &http->transfer, http->len );
  1448. /* If chunk length is zero, then move to response trailers state */
  1449. if ( ! http->remaining )
  1450. http->state = &http_trailers;
  1451. return 0;
  1452. }
  1453. /**
  1454. * Handle received chunk data
  1455. *
  1456. * @v http HTTP transaction
  1457. * @v iobuf I/O buffer (may be claimed)
  1458. * @ret rc Return status code
  1459. */
  1460. static int http_rx_chunk_data ( struct http_transaction *http,
  1461. struct io_buffer **iobuf ) {
  1462. struct io_buffer *payload;
  1463. uint8_t *crlf;
  1464. size_t len;
  1465. int rc;
  1466. /* In the common case of a final chunk in a packet which also
  1467. * includes the terminating CRLF, strip the terminating CRLF
  1468. * (which we would ignore anyway) and hence avoid
  1469. * unnecessarily copying the data.
  1470. */
  1471. if ( iob_len ( *iobuf ) == ( http->remaining + 2 /* CRLF */ ) ) {
  1472. crlf = ( (*iobuf)->data + http->remaining );
  1473. if ( ( crlf[0] == '\r' ) && ( crlf[1] == '\n' ) )
  1474. iob_unput ( (*iobuf), 2 /* CRLF */ );
  1475. }
  1476. len = iob_len ( *iobuf );
  1477. /* Use whole/partial buffer as applicable */
  1478. if ( len <= http->remaining ) {
  1479. /* Whole buffer is to be consumed: decrease remaining
  1480. * length and use original I/O buffer as payload.
  1481. */
  1482. payload = iob_disown ( *iobuf );
  1483. http->len += len;
  1484. http->remaining -= len;
  1485. } else {
  1486. /* Partial buffer is to be consumed: copy data to a
  1487. * temporary I/O buffer.
  1488. */
  1489. payload = alloc_iob ( http->remaining );
  1490. if ( ! payload ) {
  1491. rc = -ENOMEM;
  1492. goto err;
  1493. }
  1494. memcpy ( iob_put ( payload, http->remaining ), (*iobuf)->data,
  1495. http->remaining );
  1496. iob_pull ( *iobuf, http->remaining );
  1497. http->len += http->remaining;
  1498. http->remaining = 0;
  1499. }
  1500. /* Hand off to content encoding */
  1501. if ( ( rc = xfer_deliver_iob ( &http->transfer,
  1502. iob_disown ( payload ) ) ) != 0 )
  1503. goto err;
  1504. return 0;
  1505. err:
  1506. assert ( payload == NULL );
  1507. return rc;
  1508. }
  1509. /**
  1510. * Handle received chunked data
  1511. *
  1512. * @v http HTTP transaction
  1513. * @v iobuf I/O buffer (may be claimed)
  1514. * @ret rc Return status code
  1515. */
  1516. static int http_rx_transfer_chunked ( struct http_transaction *http,
  1517. struct io_buffer **iobuf ) {
  1518. /* Handle as chunk length or chunk data as appropriate */
  1519. if ( http->remaining ) {
  1520. return http_rx_chunk_data ( http, iobuf );
  1521. } else {
  1522. return http_rx_chunk_len ( http, iobuf );
  1523. }
  1524. }
  1525. /** Chunked transfer encoding */
  1526. struct http_transfer_encoding http_transfer_chunked __http_transfer_encoding = {
  1527. .name = "chunked",
  1528. .init = http_init_transfer_chunked,
  1529. .state = {
  1530. .rx = http_rx_transfer_chunked,
  1531. .close = http_close_error,
  1532. },
  1533. };
  1534. /******************************************************************************
  1535. *
  1536. * Response trailers
  1537. *
  1538. ******************************************************************************
  1539. */
  1540. /**
  1541. * Handle received HTTP trailer
  1542. *
  1543. * @v http HTTP transaction
  1544. * @v iobuf I/O buffer (may be claimed)
  1545. * @ret rc Return status code
  1546. */
  1547. static int http_rx_trailers ( struct http_transaction *http,
  1548. struct io_buffer **iobuf ) {
  1549. char *line;
  1550. int rc;
  1551. /* Buffer trailer line */
  1552. if ( ( rc = http_rx_linebuf ( http, *iobuf, &http->linebuf ) ) != 0 )
  1553. return rc;
  1554. /* Wait until we see the empty line marking end of trailers */
  1555. line = buffered_line ( &http->linebuf );
  1556. if ( ( line == NULL ) || ( line[0] != '\0' ) )
  1557. return 0;
  1558. /* Empty line buffer */
  1559. empty_line_buffer ( &http->linebuf );
  1560. /* Transfer is complete */
  1561. if ( ( rc = http_transfer_complete ( http ) ) != 0 )
  1562. return rc;
  1563. return 0;
  1564. }
  1565. /** HTTP response trailers state */
  1566. static struct http_state http_trailers = {
  1567. .rx = http_rx_trailers,
  1568. .close = http_close_error,
  1569. };
  1570. /******************************************************************************
  1571. *
  1572. * Simple URI openers
  1573. *
  1574. ******************************************************************************
  1575. */
  1576. /**
  1577. * Construct HTTP parameter list
  1578. *
  1579. * @v params Parameter list
  1580. * @v buf Buffer to contain HTTP POST parameters
  1581. * @v len Length of buffer
  1582. * @ret len Length of parameter list (excluding terminating NUL)
  1583. */
  1584. static size_t http_params ( struct parameters *params, char *buf, size_t len ) {
  1585. struct parameter *param;
  1586. ssize_t remaining = len;
  1587. size_t frag_len;
  1588. /* Add each parameter in the form "key=value", joined with "&" */
  1589. len = 0;
  1590. for_each_param ( param, params ) {
  1591. /* Add the "&", if applicable */
  1592. if ( len ) {
  1593. if ( remaining > 0 )
  1594. *buf = '&';
  1595. buf++;
  1596. len++;
  1597. remaining--;
  1598. }
  1599. /* URI-encode the key */
  1600. frag_len = uri_encode_string ( 0, param->key, buf, remaining );
  1601. buf += frag_len;
  1602. len += frag_len;
  1603. remaining -= frag_len;
  1604. /* Add the "=" */
  1605. if ( remaining > 0 )
  1606. *buf = '=';
  1607. buf++;
  1608. len++;
  1609. remaining--;
  1610. /* URI-encode the value */
  1611. frag_len = uri_encode_string ( 0, param->value, buf, remaining);
  1612. buf += frag_len;
  1613. len += frag_len;
  1614. remaining -= frag_len;
  1615. }
  1616. /* Ensure string is NUL-terminated even if no parameters are present */
  1617. if ( remaining > 0 )
  1618. *buf = '\0';
  1619. return len;
  1620. }
  1621. /**
  1622. * Open HTTP transaction for simple GET URI
  1623. *
  1624. * @v xfer Data transfer interface
  1625. * @v uri Request URI
  1626. * @ret rc Return status code
  1627. */
  1628. static int http_open_get_uri ( struct interface *xfer, struct uri *uri ) {
  1629. return http_open ( xfer, &http_get, uri, NULL, NULL );
  1630. }
  1631. /**
  1632. * Open HTTP transaction for simple POST URI
  1633. *
  1634. * @v xfer Data transfer interface
  1635. * @v uri Request URI
  1636. * @ret rc Return status code
  1637. */
  1638. static int http_open_post_uri ( struct interface *xfer, struct uri *uri ) {
  1639. struct parameters *params = uri->params;
  1640. struct http_request_content content;
  1641. void *data;
  1642. size_t len;
  1643. size_t check_len;
  1644. int rc;
  1645. /* Calculate length of parameter list */
  1646. len = http_params ( params, NULL, 0 );
  1647. /* Allocate temporary parameter list */
  1648. data = zalloc ( len + 1 /* NUL */ );
  1649. if ( ! data ) {
  1650. rc = -ENOMEM;
  1651. goto err_alloc;
  1652. }
  1653. /* Construct temporary parameter list */
  1654. check_len = http_params ( params, data, ( len + 1 /* NUL */ ) );
  1655. assert ( check_len == len );
  1656. /* Construct request content */
  1657. content.type = "application/x-www-form-urlencoded";
  1658. content.data = data;
  1659. content.len = len;
  1660. /* Open HTTP transaction */
  1661. if ( ( rc = http_open ( xfer, &http_post, uri, NULL, &content ) ) != 0 )
  1662. goto err_open;
  1663. err_open:
  1664. free ( data );
  1665. err_alloc:
  1666. return rc;
  1667. }
  1668. /**
  1669. * Open HTTP transaction for simple URI
  1670. *
  1671. * @v xfer Data transfer interface
  1672. * @v uri Request URI
  1673. * @ret rc Return status code
  1674. */
  1675. int http_open_uri ( struct interface *xfer, struct uri *uri ) {
  1676. /* Open GET/POST URI as applicable */
  1677. if ( uri->params ) {
  1678. return http_open_post_uri ( xfer, uri );
  1679. } else {
  1680. return http_open_get_uri ( xfer, uri );
  1681. }
  1682. }
  1683. /* Drag in HTTP extensions */
  1684. REQUIRING_SYMBOL ( http_open );
  1685. REQUIRE_OBJECT ( config_http );