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

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