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

httpcore.c 50KB

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