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

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