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

httpcore.c 50KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930
  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 */
  173. while ( isspace ( **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 */
  182. if ( isspace ( 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. * Handle successful transfer completion
  590. *
  591. * @v http HTTP transaction
  592. * @ret rc Return status code
  593. */
  594. static int http_transfer_complete ( struct http_transaction *http ) {
  595. struct http_authentication *auth;
  596. const char *location;
  597. int rc;
  598. /* Keep connection alive if applicable */
  599. if ( http->response.flags & HTTP_RESPONSE_KEEPALIVE )
  600. pool_recycle ( &http->conn );
  601. /* Restart server connection interface */
  602. intf_restart ( &http->conn, 0 );
  603. /* No more data is expected */
  604. http->state = NULL;
  605. /* If transaction is successful, then close the
  606. * transfer-decoded interface. The content encoding may
  607. * choose whether or not to immediately terminate the
  608. * transaction.
  609. */
  610. if ( http->response.rc == 0 ) {
  611. intf_shutdown ( &http->transfer, 0 );
  612. return 0;
  613. }
  614. /* Perform redirection, if applicable */
  615. if ( ( location = http->response.location ) ) {
  616. DBGC2 ( http, "HTTP %p redirecting to \"%s\"\n",
  617. http, location );
  618. if ( ( rc = xfer_redirect ( &http->xfer, LOCATION_URI_STRING,
  619. location ) ) != 0 ) {
  620. DBGC ( http, "HTTP %p could not redirect: %s\n",
  621. http, strerror ( rc ) );
  622. return rc;
  623. }
  624. http_close ( http, 0 );
  625. return 0;
  626. }
  627. /* Fail unless a retry is permitted */
  628. if ( ! ( http->response.flags & HTTP_RESPONSE_RETRY ) )
  629. return http->response.rc;
  630. /* Perform authentication, if applicable */
  631. if ( ( auth = http->response.auth.auth ) ) {
  632. http->request.auth.auth = auth;
  633. DBGC2 ( http, "HTTP %p performing %s authentication\n",
  634. http, auth->name );
  635. if ( ( rc = auth->authenticate ( http ) ) != 0 ) {
  636. DBGC ( http, "HTTP %p could not authenticate: %s\n",
  637. http, strerror ( rc ) );
  638. return rc;
  639. }
  640. }
  641. /* Restart content decoding interfaces (which may be attached
  642. * to the same object).
  643. */
  644. intf_nullify ( &http->content );
  645. intf_nullify ( &http->transfer );
  646. intf_restart ( &http->content, http->response.rc );
  647. intf_restart ( &http->transfer, http->response.rc );
  648. http->content.desc = &http_content_desc;
  649. http->transfer.desc = &http_transfer_desc;
  650. intf_plug_plug ( &http->transfer, &http->content );
  651. http->len = 0;
  652. assert ( http->remaining == 0 );
  653. /* Start timer to initiate retry */
  654. DBGC2 ( http, "HTTP %p retrying after %d seconds\n",
  655. http, http->response.retry_after );
  656. start_timer_fixed ( &http->timer,
  657. ( http->response.retry_after * TICKS_PER_SEC ) );
  658. return 0;
  659. }
  660. /******************************************************************************
  661. *
  662. * Requests
  663. *
  664. ******************************************************************************
  665. */
  666. /**
  667. * Construct HTTP request headers
  668. *
  669. * @v http HTTP transaction
  670. * @v buf Buffer
  671. * @v len Length of buffer
  672. * @ret len Length, or negative error
  673. */
  674. static int http_format_headers ( struct http_transaction *http, char *buf,
  675. size_t len ) {
  676. struct http_request_header *header;
  677. size_t used;
  678. size_t remaining;
  679. char *line;
  680. int value_len;
  681. int rc;
  682. /* Construct request line */
  683. used = ssnprintf ( buf, len, "%s %s HTTP/1.1",
  684. http->request.method->name, http->request.uri );
  685. if ( used < len )
  686. DBGC2 ( http, "HTTP %p TX %s\n", http, buf );
  687. used += ssnprintf ( ( buf + used ), ( len - used ), "\r\n" );
  688. /* Construct all headers */
  689. for_each_table_entry ( header, HTTP_REQUEST_HEADERS ) {
  690. /* Determine header value length */
  691. value_len = header->format ( http, NULL, 0 );
  692. if ( value_len < 0 ) {
  693. rc = value_len;
  694. return rc;
  695. }
  696. /* Skip zero-length headers */
  697. if ( ! value_len )
  698. continue;
  699. /* Construct header */
  700. line = ( buf + used );
  701. used += ssnprintf ( ( buf + used ), ( len - used ), "%s: ",
  702. header->name );
  703. remaining = ( ( used < len ) ? ( len - used ) : 0 );
  704. used += header->format ( http, ( buf + used ), remaining );
  705. if ( used < len )
  706. DBGC2 ( http, "HTTP %p TX %s\n", http, line );
  707. used += ssnprintf ( ( buf + used ), ( len - used ), "\r\n" );
  708. }
  709. /* Construct terminating newline */
  710. used += ssnprintf ( ( buf + used ), ( len - used ), "\r\n" );
  711. return used;
  712. }
  713. /**
  714. * Construct HTTP "Host" header
  715. *
  716. * @v http HTTP transaction
  717. * @v buf Buffer
  718. * @v len Length of buffer
  719. * @ret len Length of header value, or negative error
  720. */
  721. static int http_format_host ( struct http_transaction *http, char *buf,
  722. size_t len ) {
  723. /* Construct host URI */
  724. return snprintf ( buf, len, "%s", http->request.host );
  725. }
  726. /** HTTP "Host" header "*/
  727. struct http_request_header http_request_host __http_request_header = {
  728. .name = "Host",
  729. .format = http_format_host,
  730. };
  731. /**
  732. * Construct HTTP "User-Agent" header
  733. *
  734. * @v http HTTP transaction
  735. * @v buf Buffer
  736. * @v len Length of buffer
  737. * @ret len Length of header value, or negative error
  738. */
  739. static int http_format_user_agent ( struct http_transaction *http __unused,
  740. char *buf, size_t len ) {
  741. /* Construct user agent */
  742. return snprintf ( buf, len, "iPXE/%s", product_version );
  743. }
  744. /** HTTP "User-Agent" header */
  745. struct http_request_header http_request_user_agent __http_request_header = {
  746. .name = "User-Agent",
  747. .format = http_format_user_agent,
  748. };
  749. /**
  750. * Construct HTTP "Connection" header
  751. *
  752. * @v http HTTP transaction
  753. * @v buf Buffer
  754. * @v len Length of buffer
  755. * @ret len Length of header value, or negative error
  756. */
  757. static int http_format_connection ( struct http_transaction *http __unused,
  758. char *buf, size_t len ) {
  759. /* Always request keep-alive */
  760. return snprintf ( buf, len, "keep-alive" );
  761. }
  762. /** HTTP "Connection" header */
  763. struct http_request_header http_request_connection __http_request_header = {
  764. .name = "Connection",
  765. .format = http_format_connection,
  766. };
  767. /**
  768. * Construct HTTP "Range" header
  769. *
  770. * @v http HTTP transaction
  771. * @v buf Buffer
  772. * @v len Length of buffer
  773. * @ret len Length of header value, or negative error
  774. */
  775. static int http_format_range ( struct http_transaction *http,
  776. char *buf, size_t len ) {
  777. /* Construct range, if applicable */
  778. if ( http->request.range.len ) {
  779. return snprintf ( buf, len, "bytes=%zd-%zd",
  780. http->request.range.start,
  781. ( http->request.range.start +
  782. http->request.range.len - 1 ) );
  783. } else {
  784. return 0;
  785. }
  786. }
  787. /** HTTP "Range" header */
  788. struct http_request_header http_request_range __http_request_header = {
  789. .name = "Range",
  790. .format = http_format_range,
  791. };
  792. /**
  793. * Construct HTTP "Content-Type" header
  794. *
  795. * @v http HTTP transaction
  796. * @v buf Buffer
  797. * @v len Length of buffer
  798. * @ret len Length of header value, or negative error
  799. */
  800. static int http_format_content_type ( struct http_transaction *http,
  801. char *buf, size_t len ) {
  802. /* Construct content type, if applicable */
  803. if ( http->request.content.type ) {
  804. return snprintf ( buf, len, "%s", http->request.content.type );
  805. } else {
  806. return 0;
  807. }
  808. }
  809. /** HTTP "Content-Type" header */
  810. struct http_request_header http_request_content_type __http_request_header = {
  811. .name = "Content-Type",
  812. .format = http_format_content_type,
  813. };
  814. /**
  815. * Construct HTTP "Content-Length" header
  816. *
  817. * @v http HTTP transaction
  818. * @v buf Buffer
  819. * @v len Length of buffer
  820. * @ret len Length of header value, or negative error
  821. */
  822. static int http_format_content_length ( struct http_transaction *http,
  823. char *buf, size_t len ) {
  824. /* Construct content length, if applicable */
  825. if ( http->request.content.len ) {
  826. return snprintf ( buf, len, "%zd", http->request.content.len );
  827. } else {
  828. return 0;
  829. }
  830. }
  831. /** HTTP "Content-Length" header */
  832. struct http_request_header http_request_content_length __http_request_header = {
  833. .name = "Content-Length",
  834. .format = http_format_content_length,
  835. };
  836. /**
  837. * Construct HTTP "Accept-Encoding" header
  838. *
  839. * @v http HTTP transaction
  840. * @v buf Buffer
  841. * @v len Length of buffer
  842. * @ret len Length of header value, or negative error
  843. */
  844. static int http_format_accept_encoding ( struct http_transaction *http,
  845. char *buf, size_t len ) {
  846. struct http_content_encoding *encoding;
  847. const char *sep = "";
  848. size_t used = 0;
  849. /* Construct list of content encodings */
  850. for_each_table_entry ( encoding, HTTP_CONTENT_ENCODINGS ) {
  851. if ( encoding->supported && ( ! encoding->supported ( http ) ) )
  852. continue;
  853. used += ssnprintf ( ( buf + used ), ( len - used ),
  854. "%s%s", sep, encoding->name );
  855. sep = ", ";
  856. }
  857. return used;
  858. }
  859. /** HTTP "Accept-Encoding" header */
  860. struct http_request_header http_request_accept_encoding __http_request_header ={
  861. .name = "Accept-Encoding",
  862. .format = http_format_accept_encoding,
  863. };
  864. /**
  865. * Transmit request
  866. *
  867. * @v http HTTP transaction
  868. * @ret rc Return status code
  869. */
  870. static int http_tx_request ( struct http_transaction *http ) {
  871. struct io_buffer *iobuf;
  872. int len;
  873. int check_len;
  874. int rc;
  875. /* Calculate request length */
  876. len = http_format_headers ( http, NULL, 0 );
  877. if ( len < 0 ) {
  878. rc = len;
  879. DBGC ( http, "HTTP %p could not construct request: %s\n",
  880. http, strerror ( rc ) );
  881. goto err_len;
  882. }
  883. /* Allocate I/O buffer */
  884. iobuf = alloc_iob ( len + 1 /* NUL */ + http->request.content.len );
  885. if ( ! iobuf ) {
  886. rc = -ENOMEM;
  887. goto err_alloc;
  888. }
  889. /* Construct request */
  890. check_len = http_format_headers ( http, iob_put ( iobuf, len ),
  891. ( len + 1 /* NUL */ ) );
  892. assert ( check_len == len );
  893. memcpy ( iob_put ( iobuf, http->request.content.len ),
  894. http->request.content.data, http->request.content.len );
  895. /* Deliver request */
  896. if ( ( rc = xfer_deliver_iob ( &http->conn,
  897. iob_disown ( iobuf ) ) ) != 0 ) {
  898. DBGC ( http, "HTTP %p could not deliver request: %s\n",
  899. http, strerror ( rc ) );
  900. goto err_deliver;
  901. }
  902. /* Clear any previous response */
  903. empty_line_buffer ( &http->response.headers );
  904. memset ( &http->response, 0, sizeof ( http->response ) );
  905. /* Move to response headers state */
  906. http->state = &http_headers;
  907. return 0;
  908. err_deliver:
  909. free_iob ( iobuf );
  910. err_alloc:
  911. err_len:
  912. return rc;
  913. }
  914. /** HTTP request state */
  915. static struct http_state http_request = {
  916. .tx = http_tx_request,
  917. .close = http_close_error,
  918. };
  919. /******************************************************************************
  920. *
  921. * Response headers
  922. *
  923. ******************************************************************************
  924. */
  925. /**
  926. * Parse HTTP status line
  927. *
  928. * @v http HTTP transaction
  929. * @v line Status line
  930. * @ret rc Return status code
  931. */
  932. static int http_parse_status ( struct http_transaction *http, char *line ) {
  933. char *endp;
  934. char *version;
  935. char *vernum;
  936. char *status;
  937. int response_rc;
  938. DBGC2 ( http, "HTTP %p RX %s\n", http, line );
  939. /* Parse HTTP version */
  940. version = http_token ( &line, NULL );
  941. if ( ( ! version ) || ( strncmp ( version, "HTTP/", 5 ) != 0 ) ) {
  942. DBGC ( http, "HTTP %p malformed version \"%s\"\n", http, line );
  943. return -EINVAL_STATUS;
  944. }
  945. /* Keepalive is enabled by default for anything newer than HTTP/1.0 */
  946. vernum = ( version + 5 /* "HTTP/" (presence already checked) */ );
  947. if ( vernum[0] == '0' ) {
  948. /* HTTP/0.x : keepalive not enabled by default */
  949. } else if ( strncmp ( vernum, "1.0", 3 ) == 0 ) {
  950. /* HTTP/1.0 : keepalive not enabled by default */
  951. } else {
  952. /* HTTP/1.1 or newer: keepalive enabled by default */
  953. http->response.flags |= HTTP_RESPONSE_KEEPALIVE;
  954. }
  955. /* Parse status code */
  956. status = line;
  957. http->response.status = strtoul ( status, &endp, 10 );
  958. if ( *endp != ' ' ) {
  959. DBGC ( http, "HTTP %p malformed status code \"%s\"\n",
  960. http, status );
  961. return -EINVAL_STATUS;
  962. }
  963. /* Convert HTTP status code to iPXE return status code */
  964. if ( status[0] == '2' ) {
  965. /* 2xx Success */
  966. response_rc = 0;
  967. } else if ( status[0] == '3' ) {
  968. /* 3xx Redirection */
  969. response_rc = -EXDEV;
  970. } else if ( http->response.status == 401 ) {
  971. /* 401 Unauthorized */
  972. response_rc = -EACCES_401;
  973. } else if ( http->response.status == 403 ) {
  974. /* 403 Forbidden */
  975. response_rc = -EPERM_403;
  976. } else if ( http->response.status == 404 ) {
  977. /* 404 Not Found */
  978. response_rc = -ENOENT_404;
  979. } else if ( status[0] == '4' ) {
  980. /* 4xx Client Error (not already specified) */
  981. response_rc = -EIO_4XX;
  982. } else if ( status[0] == '5' ) {
  983. /* 5xx Server Error */
  984. response_rc = -EIO_5XX;
  985. } else {
  986. /* Unrecognised */
  987. response_rc = -EIO_OTHER;
  988. }
  989. http->response.rc = response_rc;
  990. return 0;
  991. }
  992. /**
  993. * Parse HTTP header
  994. *
  995. * @v http HTTP transaction
  996. * @v line Header line
  997. * @ret rc Return status code
  998. */
  999. static int http_parse_header ( struct http_transaction *http, char *line ) {
  1000. struct http_response_header *header;
  1001. char *name = line;
  1002. char *sep;
  1003. DBGC2 ( http, "HTTP %p RX %s\n", http, line );
  1004. /* Extract header name */
  1005. sep = strstr ( line, ": " );
  1006. if ( ! sep ) {
  1007. DBGC ( http, "HTTP %p malformed header \"%s\"\n", http, line );
  1008. return -EINVAL_HEADER;
  1009. }
  1010. *sep = '\0';
  1011. line = ( sep + 2 /* ": " */ );
  1012. /* Process header, if recognised */
  1013. for_each_table_entry ( header, HTTP_RESPONSE_HEADERS ) {
  1014. if ( strcasecmp ( name, header->name ) == 0 )
  1015. return header->parse ( http, line );
  1016. }
  1017. /* Unrecognised headers should be ignored */
  1018. return 0;
  1019. }
  1020. /**
  1021. * Parse HTTP response headers
  1022. *
  1023. * @v http HTTP transaction
  1024. * @ret rc Return status code
  1025. */
  1026. static int http_parse_headers ( struct http_transaction *http ) {
  1027. char *line;
  1028. char *next;
  1029. int rc;
  1030. /* Get status line */
  1031. line = http->response.headers.data;
  1032. assert ( line != NULL );
  1033. next = ( line + strlen ( line ) + 1 /* NUL */ );
  1034. /* Parse status line */
  1035. if ( ( rc = http_parse_status ( http, line ) ) != 0 )
  1036. return rc;
  1037. /* Process header lines */
  1038. while ( 1 ) {
  1039. /* Move to next line */
  1040. line = next;
  1041. next = ( line + strlen ( line ) + 1 /* NUL */ );
  1042. /* Stop on terminating blank line */
  1043. if ( ! line[0] )
  1044. return 0;
  1045. /* Process header line */
  1046. if ( ( rc = http_parse_header ( http, line ) ) != 0 )
  1047. return rc;
  1048. }
  1049. }
  1050. /**
  1051. * Parse HTTP "Location" header
  1052. *
  1053. * @v http HTTP transaction
  1054. * @v line Remaining header line
  1055. * @ret rc Return status code
  1056. */
  1057. static int http_parse_location ( struct http_transaction *http, char *line ) {
  1058. /* Store location */
  1059. http->response.location = line;
  1060. return 0;
  1061. }
  1062. /** HTTP "Location" header */
  1063. struct http_response_header http_response_location __http_response_header = {
  1064. .name = "Location",
  1065. .parse = http_parse_location,
  1066. };
  1067. /**
  1068. * Parse HTTP "Transfer-Encoding" header
  1069. *
  1070. * @v http HTTP transaction
  1071. * @v line Remaining header line
  1072. * @ret rc Return status code
  1073. */
  1074. static int http_parse_transfer_encoding ( struct http_transaction *http,
  1075. char *line ) {
  1076. struct http_transfer_encoding *encoding;
  1077. /* Check for known transfer encodings */
  1078. for_each_table_entry ( encoding, HTTP_TRANSFER_ENCODINGS ) {
  1079. if ( strcasecmp ( line, encoding->name ) == 0 ) {
  1080. http->response.transfer.encoding = encoding;
  1081. return 0;
  1082. }
  1083. }
  1084. DBGC ( http, "HTTP %p unrecognised Transfer-Encoding \"%s\"\n",
  1085. http, line );
  1086. return -ENOTSUP_TRANSFER;
  1087. }
  1088. /** HTTP "Transfer-Encoding" header */
  1089. struct http_response_header
  1090. http_response_transfer_encoding __http_response_header = {
  1091. .name = "Transfer-Encoding",
  1092. .parse = http_parse_transfer_encoding,
  1093. };
  1094. /**
  1095. * Parse HTTP "Connection" header
  1096. *
  1097. * @v http HTTP transaction
  1098. * @v line Remaining header line
  1099. * @ret rc Return status code
  1100. */
  1101. static int http_parse_connection ( struct http_transaction *http, char *line ) {
  1102. /* Check for known connection intentions */
  1103. if ( strcasecmp ( line, "keep-alive" ) == 0 ) {
  1104. http->response.flags |= HTTP_RESPONSE_KEEPALIVE;
  1105. return 0;
  1106. }
  1107. if ( strcasecmp ( line, "close" ) == 0 ) {
  1108. http->response.flags &= ~HTTP_RESPONSE_KEEPALIVE;
  1109. return 0;
  1110. }
  1111. DBGC ( http, "HTTP %p unrecognised Connection \"%s\"\n", http, line );
  1112. return -ENOTSUP_CONNECTION;
  1113. }
  1114. /** HTTP "Connection" header */
  1115. struct http_response_header http_response_connection __http_response_header = {
  1116. .name = "Connection",
  1117. .parse = http_parse_connection,
  1118. };
  1119. /**
  1120. * Parse HTTP "Content-Length" header
  1121. *
  1122. * @v http HTTP transaction
  1123. * @v line Remaining header line
  1124. * @ret rc Return status code
  1125. */
  1126. static int http_parse_content_length ( struct http_transaction *http,
  1127. char *line ) {
  1128. char *endp;
  1129. /* Parse length */
  1130. http->response.content.len = strtoul ( line, &endp, 10 );
  1131. if ( *endp != '\0' ) {
  1132. DBGC ( http, "HTTP %p invalid Content-Length \"%s\"\n",
  1133. http, line );
  1134. return -EINVAL_CONTENT_LENGTH;
  1135. }
  1136. /* Record that we have a content length (since it may be zero) */
  1137. http->response.flags |= HTTP_RESPONSE_CONTENT_LEN;
  1138. return 0;
  1139. }
  1140. /** HTTP "Content-Length" header */
  1141. struct http_response_header
  1142. http_response_content_length __http_response_header = {
  1143. .name = "Content-Length",
  1144. .parse = http_parse_content_length,
  1145. };
  1146. /**
  1147. * Parse HTTP "Content-Encoding" header
  1148. *
  1149. * @v http HTTP transaction
  1150. * @v line Remaining header line
  1151. * @ret rc Return status code
  1152. */
  1153. static int http_parse_content_encoding ( struct http_transaction *http,
  1154. char *line ) {
  1155. struct http_content_encoding *encoding;
  1156. /* Check for known content encodings */
  1157. for_each_table_entry ( encoding, HTTP_CONTENT_ENCODINGS ) {
  1158. if ( encoding->supported && ( ! encoding->supported ( http ) ) )
  1159. continue;
  1160. if ( strcasecmp ( line, encoding->name ) == 0 ) {
  1161. http->response.content.encoding = encoding;
  1162. return 0;
  1163. }
  1164. }
  1165. /* Some servers (e.g. Apache) have a habit of specifying
  1166. * unwarranted content encodings. For example, if Apache
  1167. * detects (via /etc/httpd/conf/magic) that a file's contents
  1168. * are gzip-compressed, it will set "Content-Encoding: x-gzip"
  1169. * regardless of the client's Accept-Encoding header. The
  1170. * only viable way to handle such servers is to treat unknown
  1171. * content encodings as equivalent to "identity".
  1172. */
  1173. DBGC ( http, "HTTP %p unrecognised Content-Encoding \"%s\"\n",
  1174. http, line );
  1175. return 0;
  1176. }
  1177. /** HTTP "Content-Encoding" header */
  1178. struct http_response_header
  1179. http_response_content_encoding __http_response_header = {
  1180. .name = "Content-Encoding",
  1181. .parse = http_parse_content_encoding,
  1182. };
  1183. /**
  1184. * Parse HTTP "Retry-After" header
  1185. *
  1186. * @v http HTTP transaction
  1187. * @v line Remaining header line
  1188. * @ret rc Return status code
  1189. */
  1190. static int http_parse_retry_after ( struct http_transaction *http,
  1191. char *line ) {
  1192. char *endp;
  1193. /* Try to parse value as a simple number of seconds */
  1194. http->response.retry_after = strtoul ( line, &endp, 10 );
  1195. if ( *endp != '\0' ) {
  1196. /* For any value which is not a simple number of
  1197. * seconds (e.g. a full HTTP date), just retry after a
  1198. * fixed delay, since we don't have code able to parse
  1199. * full HTTP dates.
  1200. */
  1201. http->response.retry_after = HTTP_RETRY_SECONDS;
  1202. DBGC ( http, "HTTP %p cannot understand Retry-After \"%s\"; "
  1203. "using %d seconds\n", http, line, HTTP_RETRY_SECONDS );
  1204. }
  1205. /* Allow HTTP request to be retried after specified delay */
  1206. http->response.flags |= HTTP_RESPONSE_RETRY;
  1207. return 0;
  1208. }
  1209. /** HTTP "Retry-After" header */
  1210. struct http_response_header http_response_retry_after __http_response_header = {
  1211. .name = "Retry-After",
  1212. .parse = http_parse_retry_after,
  1213. };
  1214. /**
  1215. * Handle received HTTP headers
  1216. *
  1217. * @v http HTTP transaction
  1218. * @v iobuf I/O buffer (may be claimed)
  1219. * @ret rc Return status code
  1220. */
  1221. static int http_rx_headers ( struct http_transaction *http,
  1222. struct io_buffer **iobuf ) {
  1223. struct http_transfer_encoding *transfer;
  1224. struct http_content_encoding *content;
  1225. char *line;
  1226. int rc;
  1227. /* Buffer header line */
  1228. if ( ( rc = http_rx_linebuf ( http, *iobuf,
  1229. &http->response.headers ) ) != 0 )
  1230. return rc;
  1231. /* Wait until we see the empty line marking end of headers */
  1232. line = buffered_line ( &http->response.headers );
  1233. if ( ( line == NULL ) || ( line[0] != '\0' ) )
  1234. return 0;
  1235. /* Process headers */
  1236. if ( ( rc = http_parse_headers ( http ) ) != 0 )
  1237. return rc;
  1238. /* Initialise content encoding, if applicable */
  1239. if ( ( content = http->response.content.encoding ) &&
  1240. ( ( rc = content->init ( http ) ) != 0 ) ) {
  1241. DBGC ( http, "HTTP %p could not initialise %s content "
  1242. "encoding: %s\n", http, content->name, strerror ( rc ) );
  1243. return rc;
  1244. }
  1245. /* Presize receive buffer, if we have a content length */
  1246. if ( http->response.content.len ) {
  1247. xfer_seek ( &http->transfer, http->response.content.len );
  1248. xfer_seek ( &http->transfer, 0 );
  1249. }
  1250. /* Complete transfer if this is a HEAD request */
  1251. if ( http->request.method == &http_head ) {
  1252. if ( ( rc = http_transfer_complete ( http ) ) != 0 )
  1253. return rc;
  1254. return 0;
  1255. }
  1256. /* Default to identity transfer encoding, if none specified */
  1257. if ( ! http->response.transfer.encoding )
  1258. http->response.transfer.encoding = &http_transfer_identity;
  1259. /* Move to transfer encoding-specific data state */
  1260. transfer = http->response.transfer.encoding;
  1261. http->state = &transfer->state;
  1262. /* Initialise transfer encoding */
  1263. if ( ( rc = transfer->init ( http ) ) != 0 ) {
  1264. DBGC ( http, "HTTP %p could not initialise %s transfer "
  1265. "encoding: %s\n", http, transfer->name, strerror ( rc ));
  1266. return rc;
  1267. }
  1268. return 0;
  1269. }
  1270. /** HTTP response headers state */
  1271. static struct http_state http_headers = {
  1272. .rx = http_rx_headers,
  1273. .close = http_close_error,
  1274. };
  1275. /******************************************************************************
  1276. *
  1277. * Identity transfer encoding
  1278. *
  1279. ******************************************************************************
  1280. */
  1281. /**
  1282. * Initialise transfer encoding
  1283. *
  1284. * @v http HTTP transaction
  1285. * @ret rc Return status code
  1286. */
  1287. static int http_init_transfer_identity ( struct http_transaction *http ) {
  1288. int rc;
  1289. /* Complete transfer immediately if we have a zero content length */
  1290. if ( ( http->response.flags & HTTP_RESPONSE_CONTENT_LEN ) &&
  1291. ( http->response.content.len == 0 ) &&
  1292. ( ( rc = http_transfer_complete ( http ) ) != 0 ) )
  1293. return rc;
  1294. return 0;
  1295. }
  1296. /**
  1297. * Handle received data
  1298. *
  1299. * @v http HTTP transaction
  1300. * @v iobuf I/O buffer (may be claimed)
  1301. * @ret rc Return status code
  1302. */
  1303. static int http_rx_transfer_identity ( struct http_transaction *http,
  1304. struct io_buffer **iobuf ) {
  1305. size_t len = iob_len ( *iobuf );
  1306. int rc;
  1307. /* Update lengths */
  1308. http->len += len;
  1309. /* Fail if this transfer would overrun the expected content
  1310. * length (if any).
  1311. */
  1312. if ( ( http->response.flags & HTTP_RESPONSE_CONTENT_LEN ) &&
  1313. ( http->len > http->response.content.len ) ) {
  1314. DBGC ( http, "HTTP %p content length overrun\n", http );
  1315. return -EIO_CONTENT_LENGTH;
  1316. }
  1317. /* Hand off to content encoding */
  1318. if ( ( rc = xfer_deliver_iob ( &http->transfer,
  1319. iob_disown ( *iobuf ) ) ) != 0 )
  1320. return rc;
  1321. /* Complete transfer if we have received the expected content
  1322. * length (if any).
  1323. */
  1324. if ( ( http->response.flags & HTTP_RESPONSE_CONTENT_LEN ) &&
  1325. ( http->len == http->response.content.len ) &&
  1326. ( ( rc = http_transfer_complete ( http ) ) != 0 ) )
  1327. return rc;
  1328. return 0;
  1329. }
  1330. /**
  1331. * Handle server connection close
  1332. *
  1333. * @v http HTTP transaction
  1334. * @v rc Reason for close
  1335. */
  1336. static void http_close_transfer_identity ( struct http_transaction *http,
  1337. int rc ) {
  1338. /* Fail if any error occurred */
  1339. if ( rc != 0 )
  1340. goto err;
  1341. /* Fail if we have a content length (since we would have
  1342. * already closed the connection if we had received the
  1343. * correct content length).
  1344. */
  1345. if ( http->response.flags & HTTP_RESPONSE_CONTENT_LEN ) {
  1346. DBGC ( http, "HTTP %p content length underrun\n", http );
  1347. rc = EIO_CONTENT_LENGTH;
  1348. goto err;
  1349. }
  1350. /* Indicate that transfer is complete */
  1351. if ( ( rc = http_transfer_complete ( http ) ) != 0 )
  1352. goto err;
  1353. return;
  1354. err:
  1355. http_close ( http, rc );
  1356. }
  1357. /** Identity transfer encoding */
  1358. static struct http_transfer_encoding http_transfer_identity = {
  1359. .name = "identity",
  1360. .init = http_init_transfer_identity,
  1361. .state = {
  1362. .rx = http_rx_transfer_identity,
  1363. .close = http_close_transfer_identity,
  1364. },
  1365. };
  1366. /******************************************************************************
  1367. *
  1368. * Chunked transfer encoding
  1369. *
  1370. ******************************************************************************
  1371. */
  1372. /**
  1373. * Initialise transfer encoding
  1374. *
  1375. * @v http HTTP transaction
  1376. * @ret rc Return status code
  1377. */
  1378. static int http_init_transfer_chunked ( struct http_transaction *http ) {
  1379. /* Sanity checks */
  1380. assert ( http->remaining == 0 );
  1381. assert ( http->linebuf.len == 0 );
  1382. return 0;
  1383. }
  1384. /**
  1385. * Handle received chunk length
  1386. *
  1387. * @v http HTTP transaction
  1388. * @v iobuf I/O buffer (may be claimed)
  1389. * @ret rc Return status code
  1390. */
  1391. static int http_rx_chunk_len ( struct http_transaction *http,
  1392. struct io_buffer **iobuf ) {
  1393. char *line;
  1394. char *endp;
  1395. size_t len;
  1396. int rc;
  1397. /* Receive into temporary line buffer */
  1398. if ( ( rc = http_rx_linebuf ( http, *iobuf, &http->linebuf ) ) != 0 )
  1399. return rc;
  1400. /* Wait until we receive a non-empty line */
  1401. line = buffered_line ( &http->linebuf );
  1402. if ( ( line == NULL ) || ( line[0] == '\0' ) )
  1403. return 0;
  1404. /* Parse chunk length */
  1405. http->remaining = strtoul ( line, &endp, 16 );
  1406. if ( *endp != '\0' ) {
  1407. DBGC ( http, "HTTP %p invalid chunk length \"%s\"\n",
  1408. http, line );
  1409. return -EINVAL_CHUNK_LENGTH;
  1410. }
  1411. /* Empty line buffer */
  1412. empty_line_buffer ( &http->linebuf );
  1413. /* Update expected length */
  1414. len = ( http->len + http->remaining );
  1415. xfer_seek ( &http->transfer, len );
  1416. xfer_seek ( &http->transfer, http->len );
  1417. /* If chunk length is zero, then move to response trailers state */
  1418. if ( ! http->remaining )
  1419. http->state = &http_trailers;
  1420. return 0;
  1421. }
  1422. /**
  1423. * Handle received chunk data
  1424. *
  1425. * @v http HTTP transaction
  1426. * @v iobuf I/O buffer (may be claimed)
  1427. * @ret rc Return status code
  1428. */
  1429. static int http_rx_chunk_data ( struct http_transaction *http,
  1430. struct io_buffer **iobuf ) {
  1431. struct io_buffer *payload;
  1432. uint8_t *crlf;
  1433. size_t len;
  1434. int rc;
  1435. /* In the common case of a final chunk in a packet which also
  1436. * includes the terminating CRLF, strip the terminating CRLF
  1437. * (which we would ignore anyway) and hence avoid
  1438. * unnecessarily copying the data.
  1439. */
  1440. if ( iob_len ( *iobuf ) == ( http->remaining + 2 /* CRLF */ ) ) {
  1441. crlf = ( (*iobuf)->data + http->remaining );
  1442. if ( ( crlf[0] == '\r' ) && ( crlf[1] == '\n' ) )
  1443. iob_unput ( (*iobuf), 2 /* CRLF */ );
  1444. }
  1445. len = iob_len ( *iobuf );
  1446. /* Use whole/partial buffer as applicable */
  1447. if ( len <= http->remaining ) {
  1448. /* Whole buffer is to be consumed: decrease remaining
  1449. * length and use original I/O buffer as payload.
  1450. */
  1451. payload = iob_disown ( *iobuf );
  1452. http->len += len;
  1453. http->remaining -= len;
  1454. } else {
  1455. /* Partial buffer is to be consumed: copy data to a
  1456. * temporary I/O buffer.
  1457. */
  1458. payload = alloc_iob ( http->remaining );
  1459. if ( ! payload ) {
  1460. rc = -ENOMEM;
  1461. goto err;
  1462. }
  1463. memcpy ( iob_put ( payload, http->remaining ), (*iobuf)->data,
  1464. http->remaining );
  1465. iob_pull ( *iobuf, http->remaining );
  1466. http->len += http->remaining;
  1467. http->remaining = 0;
  1468. }
  1469. /* Hand off to content encoding */
  1470. if ( ( rc = xfer_deliver_iob ( &http->transfer,
  1471. iob_disown ( payload ) ) ) != 0 )
  1472. goto err;
  1473. return 0;
  1474. err:
  1475. assert ( payload == NULL );
  1476. return rc;
  1477. }
  1478. /**
  1479. * Handle received chunked data
  1480. *
  1481. * @v http HTTP transaction
  1482. * @v iobuf I/O buffer (may be claimed)
  1483. * @ret rc Return status code
  1484. */
  1485. static int http_rx_transfer_chunked ( struct http_transaction *http,
  1486. struct io_buffer **iobuf ) {
  1487. /* Handle as chunk length or chunk data as appropriate */
  1488. if ( http->remaining ) {
  1489. return http_rx_chunk_data ( http, iobuf );
  1490. } else {
  1491. return http_rx_chunk_len ( http, iobuf );
  1492. }
  1493. }
  1494. /** Chunked transfer encoding */
  1495. struct http_transfer_encoding http_transfer_chunked __http_transfer_encoding = {
  1496. .name = "chunked",
  1497. .init = http_init_transfer_chunked,
  1498. .state = {
  1499. .rx = http_rx_transfer_chunked,
  1500. .close = http_close_error,
  1501. },
  1502. };
  1503. /******************************************************************************
  1504. *
  1505. * Response trailers
  1506. *
  1507. ******************************************************************************
  1508. */
  1509. /**
  1510. * Handle received HTTP trailer
  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_trailers ( struct http_transaction *http,
  1517. struct io_buffer **iobuf ) {
  1518. char *line;
  1519. int rc;
  1520. /* Buffer trailer line */
  1521. if ( ( rc = http_rx_linebuf ( http, *iobuf, &http->linebuf ) ) != 0 )
  1522. return rc;
  1523. /* Wait until we see the empty line marking end of trailers */
  1524. line = buffered_line ( &http->linebuf );
  1525. if ( ( line == NULL ) || ( line[0] != '\0' ) )
  1526. return 0;
  1527. /* Empty line buffer */
  1528. empty_line_buffer ( &http->linebuf );
  1529. /* Transfer is complete */
  1530. if ( ( rc = http_transfer_complete ( http ) ) != 0 )
  1531. return rc;
  1532. return 0;
  1533. }
  1534. /** HTTP response trailers state */
  1535. static struct http_state http_trailers = {
  1536. .rx = http_rx_trailers,
  1537. .close = http_close_error,
  1538. };
  1539. /******************************************************************************
  1540. *
  1541. * Simple URI openers
  1542. *
  1543. ******************************************************************************
  1544. */
  1545. /**
  1546. * Construct HTTP parameter list
  1547. *
  1548. * @v params Parameter list
  1549. * @v buf Buffer to contain HTTP POST parameters
  1550. * @v len Length of buffer
  1551. * @ret len Length of parameter list (excluding terminating NUL)
  1552. */
  1553. static size_t http_params ( struct parameters *params, char *buf, size_t len ) {
  1554. struct parameter *param;
  1555. ssize_t remaining = len;
  1556. size_t frag_len;
  1557. /* Add each parameter in the form "key=value", joined with "&" */
  1558. len = 0;
  1559. for_each_param ( param, params ) {
  1560. /* Add the "&", if applicable */
  1561. if ( len ) {
  1562. if ( remaining > 0 )
  1563. *buf = '&';
  1564. buf++;
  1565. len++;
  1566. remaining--;
  1567. }
  1568. /* URI-encode the key */
  1569. frag_len = uri_encode ( param->key, 0, buf, remaining );
  1570. buf += frag_len;
  1571. len += frag_len;
  1572. remaining -= frag_len;
  1573. /* Add the "=" */
  1574. if ( remaining > 0 )
  1575. *buf = '=';
  1576. buf++;
  1577. len++;
  1578. remaining--;
  1579. /* URI-encode the value */
  1580. frag_len = uri_encode ( param->value, 0, buf, remaining );
  1581. buf += frag_len;
  1582. len += frag_len;
  1583. remaining -= frag_len;
  1584. }
  1585. /* Ensure string is NUL-terminated even if no parameters are present */
  1586. if ( remaining > 0 )
  1587. *buf = '\0';
  1588. return len;
  1589. }
  1590. /**
  1591. * Open HTTP transaction for simple GET URI
  1592. *
  1593. * @v xfer Data transfer interface
  1594. * @v uri Request URI
  1595. * @ret rc Return status code
  1596. */
  1597. static int http_open_get_uri ( struct interface *xfer, struct uri *uri ) {
  1598. return http_open ( xfer, &http_get, uri, NULL, NULL );
  1599. }
  1600. /**
  1601. * Open HTTP transaction for simple POST URI
  1602. *
  1603. * @v xfer Data transfer interface
  1604. * @v uri Request URI
  1605. * @ret rc Return status code
  1606. */
  1607. static int http_open_post_uri ( struct interface *xfer, struct uri *uri ) {
  1608. struct parameters *params = uri->params;
  1609. struct http_request_content content;
  1610. void *data;
  1611. size_t len;
  1612. size_t check_len;
  1613. int rc;
  1614. /* Calculate length of parameter list */
  1615. len = http_params ( params, NULL, 0 );
  1616. /* Allocate temporary parameter list */
  1617. data = zalloc ( len + 1 /* NUL */ );
  1618. if ( ! data ) {
  1619. rc = -ENOMEM;
  1620. goto err_alloc;
  1621. }
  1622. /* Construct temporary parameter list */
  1623. check_len = http_params ( params, data, ( len + 1 /* NUL */ ) );
  1624. assert ( check_len == len );
  1625. /* Construct request content */
  1626. content.type = "application/x-www-form-urlencoded";
  1627. content.data = data;
  1628. content.len = len;
  1629. /* Open HTTP transaction */
  1630. if ( ( rc = http_open ( xfer, &http_post, uri, NULL, &content ) ) != 0 )
  1631. goto err_open;
  1632. err_open:
  1633. free ( data );
  1634. err_alloc:
  1635. return rc;
  1636. }
  1637. /**
  1638. * Open HTTP transaction for simple URI
  1639. *
  1640. * @v xfer Data transfer interface
  1641. * @v uri Request URI
  1642. * @ret rc Return status code
  1643. */
  1644. int http_open_uri ( struct interface *xfer, struct uri *uri ) {
  1645. /* Open GET/POST URI as applicable */
  1646. if ( uri->params ) {
  1647. return http_open_post_uri ( xfer, uri );
  1648. } else {
  1649. return http_open_get_uri ( xfer, uri );
  1650. }
  1651. }
  1652. /* Drag in HTTP extensions */
  1653. REQUIRING_SYMBOL ( http_open );
  1654. REQUIRE_OBJECT ( config_http );