Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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