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.

peerblk.c 41KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379
  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 (at your option) 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. #include <stdlib.h>
  25. #include <stdio.h>
  26. #include <errno.h>
  27. #include <ipxe/http.h>
  28. #include <ipxe/iobuf.h>
  29. #include <ipxe/xfer.h>
  30. #include <ipxe/uri.h>
  31. #include <ipxe/timer.h>
  32. #include <ipxe/profile.h>
  33. #include <ipxe/fault.h>
  34. #include <ipxe/pccrr.h>
  35. #include <ipxe/peerblk.h>
  36. /** @file
  37. *
  38. * Peer Content Caching and Retrieval (PeerDist) protocol block downloads
  39. *
  40. */
  41. /** PeerDist decryption chunksize
  42. *
  43. * This is a policy decision.
  44. */
  45. #define PEERBLK_DECRYPT_CHUNKSIZE 2048
  46. /** PeerDist raw block download attempt initial progress timeout
  47. *
  48. * This is a policy decision.
  49. */
  50. #define PEERBLK_RAW_OPEN_TIMEOUT ( 10 * TICKS_PER_SEC )
  51. /** PeerDist raw block download attempt ongoing progress timeout
  52. *
  53. * This is a policy decision.
  54. */
  55. #define PEERBLK_RAW_RX_TIMEOUT ( 15 * TICKS_PER_SEC )
  56. /** PeerDist retrieval protocol block download attempt initial progress timeout
  57. *
  58. * This is a policy decision.
  59. */
  60. #define PEERBLK_RETRIEVAL_OPEN_TIMEOUT ( 3 * TICKS_PER_SEC )
  61. /** PeerDist retrieval protocol block download attempt ongoing progress timeout
  62. *
  63. * This is a policy decision.
  64. */
  65. #define PEERBLK_RETRIEVAL_RX_TIMEOUT ( 5 * TICKS_PER_SEC )
  66. /** PeerDist maximum number of full download attempt cycles
  67. *
  68. * This is the maximum number of times that we will try a full cycle
  69. * of download attempts (i.e. a retrieval protocol download attempt
  70. * from each discovered peer plus a raw download attempt from the
  71. * origin server).
  72. *
  73. * This is a policy decision.
  74. */
  75. #define PEERBLK_MAX_ATTEMPT_CYCLES 4
  76. /** PeerDist block download profiler */
  77. static struct profiler peerblk_download_profiler __profiler =
  78. { .name = "peerblk.download" };
  79. /** PeerDist block download attempt success profiler */
  80. static struct profiler peerblk_attempt_success_profiler __profiler =
  81. { .name = "peerblk.attempt.success" };
  82. /** PeerDist block download attempt failure profiler */
  83. static struct profiler peerblk_attempt_failure_profiler __profiler =
  84. { .name = "peerblk.attempt.failure" };
  85. /** PeerDist block download attempt timeout profiler */
  86. static struct profiler peerblk_attempt_timeout_profiler __profiler =
  87. { .name = "peerblk.attempt.timeout" };
  88. /** PeerDist block download discovery success profiler */
  89. static struct profiler peerblk_discovery_success_profiler __profiler =
  90. { .name = "peerblk.discovery.success" };
  91. /** PeerDist block download discovery timeout profiler */
  92. static struct profiler peerblk_discovery_timeout_profiler __profiler =
  93. { .name = "peerblk.discovery.timeout" };
  94. /**
  95. * Get profiling timestamp
  96. *
  97. * @ret timestamp Timestamp
  98. */
  99. static inline __attribute__ (( always_inline )) unsigned long
  100. peerblk_timestamp ( void ) {
  101. if ( PROFILING ) {
  102. return currticks();
  103. } else {
  104. return 0;
  105. }
  106. }
  107. /**
  108. * Free PeerDist block download
  109. *
  110. * @v refcnt Reference count
  111. */
  112. static void peerblk_free ( struct refcnt *refcnt ) {
  113. struct peerdist_block *peerblk =
  114. container_of ( refcnt, struct peerdist_block, refcnt );
  115. uri_put ( peerblk->uri );
  116. free ( peerblk->cipherctx );
  117. free ( peerblk );
  118. }
  119. /**
  120. * Reset PeerDist block download attempt
  121. *
  122. * @v peerblk PeerDist block download
  123. * @v rc Reason for reset
  124. */
  125. static void peerblk_reset ( struct peerdist_block *peerblk, int rc ) {
  126. /* Stop decryption process */
  127. process_del ( &peerblk->process );
  128. /* Stop timer */
  129. stop_timer ( &peerblk->timer );
  130. /* Abort any current download attempt */
  131. intf_restart ( &peerblk->raw, rc );
  132. intf_restart ( &peerblk->retrieval, rc );
  133. /* Empty received data buffer */
  134. xferbuf_free ( &peerblk->buffer );
  135. peerblk->pos = 0;
  136. /* Reset digest and free cipher context */
  137. digest_init ( peerblk->digest, peerblk->digestctx );
  138. free ( peerblk->cipherctx );
  139. peerblk->cipherctx = NULL;
  140. peerblk->cipher = NULL;
  141. /* Reset trim thresholds */
  142. peerblk->start = ( peerblk->trim.start - peerblk->range.start );
  143. peerblk->end = ( peerblk->trim.end - peerblk->range.start );
  144. assert ( peerblk->start <= peerblk->end );
  145. }
  146. /**
  147. * Close PeerDist block download
  148. *
  149. * @v peerblk PeerDist block download
  150. * @v rc Reason for close
  151. */
  152. static void peerblk_close ( struct peerdist_block *peerblk, int rc ) {
  153. unsigned long now = peerblk_timestamp();
  154. /* Profile overall block download */
  155. profile_custom ( &peerblk_download_profiler,
  156. ( now - peerblk->started ) );
  157. /* Reset download attempt */
  158. peerblk_reset ( peerblk, rc );
  159. /* Close discovery */
  160. peerdisc_close ( &peerblk->discovery );
  161. /* Shut down all interfaces */
  162. intf_shutdown ( &peerblk->retrieval, rc );
  163. intf_shutdown ( &peerblk->raw, rc );
  164. intf_shutdown ( &peerblk->xfer, rc );
  165. }
  166. /**
  167. * Calculate offset within overall download
  168. *
  169. * @v peerblk PeerDist block download
  170. * @v pos Position within incoming data stream
  171. * @ret offset Offset within overall download
  172. */
  173. static inline __attribute__ (( always_inline )) size_t
  174. peerblk_offset ( struct peerdist_block *peerblk, size_t pos ) {
  175. return ( ( pos - peerblk->start ) + peerblk->offset );
  176. }
  177. /**
  178. * Deliver download attempt data block
  179. *
  180. * @v peerblk PeerDist block download
  181. * @v iobuf I/O buffer
  182. * @v meta Original data transfer metadata
  183. * @v pos Position within incoming data stream
  184. * @ret rc Return status code
  185. */
  186. static int peerblk_deliver ( struct peerdist_block *peerblk,
  187. struct io_buffer *iobuf,
  188. struct xfer_metadata *meta, size_t pos ) {
  189. struct xfer_metadata xfer_meta;
  190. size_t len = iob_len ( iobuf );
  191. size_t start = pos;
  192. size_t end = ( pos + len );
  193. int rc;
  194. /* Discard zero-length packets and packets which lie entirely
  195. * outside the trimmed range.
  196. */
  197. if ( ( start >= peerblk->end ) || ( end <= peerblk->start ) ||
  198. ( len == 0 ) ) {
  199. free_iob ( iobuf );
  200. return 0;
  201. }
  202. /* Truncate data to within trimmed range */
  203. if ( start < peerblk->start ) {
  204. iob_pull ( iobuf, ( peerblk->start - start ) );
  205. start = peerblk->start;
  206. }
  207. if ( end > peerblk->end ) {
  208. iob_unput ( iobuf, ( end - peerblk->end ) );
  209. end = peerblk->end;
  210. }
  211. /* Construct metadata */
  212. memcpy ( &xfer_meta, meta, sizeof ( xfer_meta ) );
  213. xfer_meta.flags |= XFER_FL_ABS_OFFSET;
  214. xfer_meta.offset = peerblk_offset ( peerblk, start );
  215. /* Deliver data */
  216. if ( ( rc = xfer_deliver ( &peerblk->xfer, iob_disown ( iobuf ),
  217. &xfer_meta ) ) != 0 ) {
  218. DBGC ( peerblk, "PEERBLK %p %d.%d could not deliver data: %s\n",
  219. peerblk, peerblk->segment, peerblk->block,
  220. strerror ( rc ) );
  221. return rc;
  222. }
  223. return 0;
  224. }
  225. /**
  226. * Finish PeerDist block download attempt
  227. *
  228. * @v peerblk PeerDist block download
  229. * @v rc Reason for close
  230. */
  231. static void peerblk_done ( struct peerdist_block *peerblk, int rc ) {
  232. struct digest_algorithm *digest = peerblk->digest;
  233. struct peerdisc_segment *segment = peerblk->discovery.segment;
  234. struct peerdisc_peer *head;
  235. struct peerdisc_peer *peer;
  236. uint8_t hash[digest->digestsize];
  237. unsigned long now = peerblk_timestamp();
  238. /* Check for errors on completion */
  239. if ( rc != 0 ) {
  240. DBGC ( peerblk, "PEERBLK %p %d.%d attempt failed: %s\n",
  241. peerblk, peerblk->segment, peerblk->block,
  242. strerror ( rc ) );
  243. goto err;
  244. }
  245. /* Check digest */
  246. digest_final ( digest, peerblk->digestctx, hash );
  247. if ( memcmp ( hash, peerblk->hash, peerblk->digestsize ) != 0 ) {
  248. DBGC ( peerblk, "PEERBLK %p %d.%d digest mismatch:\n",
  249. peerblk, peerblk->segment, peerblk->block );
  250. DBGC_HDA ( peerblk, 0, hash, peerblk->digestsize );
  251. DBGC_HDA ( peerblk, 0, peerblk->hash, peerblk->digestsize );
  252. rc = -EIO;
  253. goto err;
  254. }
  255. /* Profile successful attempt */
  256. profile_custom ( &peerblk_attempt_success_profiler,
  257. ( now - peerblk->attempted ) );
  258. /* Report peer statistics */
  259. head = list_entry ( &segment->peers, struct peerdisc_peer, list );
  260. peer = ( ( peerblk->peer == head ) ? NULL : peerblk->peer );
  261. peerdisc_stat ( &peerblk->xfer, peer, &segment->peers );
  262. /* Close download */
  263. peerblk_close ( peerblk, 0 );
  264. return;
  265. err:
  266. /* Record failure reason and schedule a retry attempt */
  267. profile_custom ( &peerblk_attempt_failure_profiler,
  268. ( now - peerblk->attempted ) );
  269. peerblk_reset ( peerblk, rc );
  270. peerblk->rc = rc;
  271. start_timer_nodelay ( &peerblk->timer );
  272. }
  273. /******************************************************************************
  274. *
  275. * Raw block download attempts (using an HTTP range request)
  276. *
  277. ******************************************************************************
  278. */
  279. /**
  280. * Open PeerDist raw block download attempt
  281. *
  282. * @v peerblk PeerDist block download
  283. * @ret rc Return status code
  284. */
  285. static int peerblk_raw_open ( struct peerdist_block *peerblk ) {
  286. struct http_request_range range;
  287. int rc;
  288. DBGC2 ( peerblk, "PEERBLK %p %d.%d attempting raw range request\n",
  289. peerblk, peerblk->segment, peerblk->block );
  290. /* Construct HTTP range */
  291. memset ( &range, 0, sizeof ( range ) );
  292. range.start = peerblk->range.start;
  293. range.len = ( peerblk->range.end - peerblk->range.start );
  294. /* Initiate range request to retrieve block */
  295. if ( ( rc = http_open ( &peerblk->raw, &http_get, peerblk->uri,
  296. &range, NULL ) ) != 0 ) {
  297. DBGC ( peerblk, "PEERBLK %p %d.%d could not create range "
  298. "request: %s\n", peerblk, peerblk->segment,
  299. peerblk->block, strerror ( rc ) );
  300. return rc;
  301. }
  302. /* Annul HTTP connection (for testing) if applicable. Do not
  303. * report as an immediate error, in order to test our ability
  304. * to recover from a totally unresponsive HTTP server.
  305. */
  306. if ( inject_fault ( PEERBLK_ANNUL_RATE ) )
  307. intf_restart ( &peerblk->raw, 0 );
  308. /* Start download attempt timer */
  309. peerblk->rc = -ETIMEDOUT;
  310. start_timer_fixed ( &peerblk->timer, PEERBLK_RAW_OPEN_TIMEOUT );
  311. return 0;
  312. }
  313. /**
  314. * Receive PeerDist raw data
  315. *
  316. * @v peerblk PeerDist block download
  317. * @v iobuf I/O buffer
  318. * @v meta Data transfer metadata
  319. * @ret rc Return status code
  320. */
  321. static int peerblk_raw_rx ( struct peerdist_block *peerblk,
  322. struct io_buffer *iobuf,
  323. struct xfer_metadata *meta ) {
  324. size_t len = iob_len ( iobuf );
  325. size_t pos = peerblk->pos;
  326. size_t mid = ( ( peerblk->range.end - peerblk->range.start ) / 2 );
  327. int rc;
  328. /* Corrupt received data (for testing) if applicable */
  329. inject_corruption ( PEERBLK_CORRUPT_RATE, iobuf->data, len );
  330. /* Fail if data is delivered out of order, since the streaming
  331. * digest requires strict ordering.
  332. */
  333. if ( ( rc = xfer_check_order ( meta, &peerblk->pos, len ) ) != 0 )
  334. goto err;
  335. /* Add data to digest */
  336. digest_update ( peerblk->digest, peerblk->digestctx, iobuf->data, len );
  337. /* Deliver data */
  338. if ( ( rc = peerblk_deliver ( peerblk, iob_disown ( iobuf ), meta,
  339. pos ) ) != 0 )
  340. goto err;
  341. /* Extend download attempt timer */
  342. start_timer_fixed ( &peerblk->timer, PEERBLK_RAW_RX_TIMEOUT );
  343. /* Stall download attempt (for testing) if applicable */
  344. if ( ( pos < mid ) && ( ( pos + len ) >= mid ) &&
  345. ( ( rc = inject_fault ( PEERBLK_STALL_RATE ) ) != 0 ) ) {
  346. intf_restart ( &peerblk->raw, rc );
  347. }
  348. return 0;
  349. err:
  350. free_iob ( iobuf );
  351. peerblk_done ( peerblk, rc );
  352. return rc;
  353. }
  354. /**
  355. * Close PeerDist raw block download attempt
  356. *
  357. * @v peerblk PeerDist block download
  358. * @v rc Reason for close
  359. */
  360. static void peerblk_raw_close ( struct peerdist_block *peerblk, int rc ) {
  361. /* Restart interface */
  362. intf_restart ( &peerblk->raw, rc );
  363. /* Fail immediately if we have an error */
  364. if ( rc != 0 )
  365. goto done;
  366. /* Abort download attempt (for testing) if applicable */
  367. if ( ( rc = inject_fault ( PEERBLK_ABORT_RATE ) ) != 0 )
  368. goto done;
  369. done:
  370. /* Complete download attempt */
  371. peerblk_done ( peerblk, rc );
  372. }
  373. /******************************************************************************
  374. *
  375. * Retrieval protocol block download attempts (using HTTP POST)
  376. *
  377. ******************************************************************************
  378. */
  379. /**
  380. * Construct PeerDist retrieval protocol URI
  381. *
  382. * @v location Peer location
  383. * @ret uri Retrieval URI, or NULL on error
  384. */
  385. static struct uri * peerblk_retrieval_uri ( const char *location ) {
  386. char uri_string[ 7 /* "http://" */ + strlen ( location ) +
  387. sizeof ( PEERDIST_MAGIC_PATH /* includes NUL */ ) ];
  388. /* Construct URI string */
  389. snprintf ( uri_string, sizeof ( uri_string ),
  390. ( "http://%s" PEERDIST_MAGIC_PATH ), location );
  391. /* Parse URI string */
  392. return parse_uri ( uri_string );
  393. }
  394. /**
  395. * Open PeerDist retrieval protocol block download attempt
  396. *
  397. * @v peerblk PeerDist block download
  398. * @v location Peer location
  399. * @ret rc Return status code
  400. */
  401. static int peerblk_retrieval_open ( struct peerdist_block *peerblk,
  402. const char *location ) {
  403. size_t digestsize = peerblk->digestsize;
  404. peerdist_msg_getblks_t ( digestsize, 1, 0 ) req;
  405. peerblk_msg_blk_t ( digestsize, 0, 0, 0 ) *rsp;
  406. struct http_request_content content;
  407. struct uri *uri;
  408. int rc;
  409. DBGC2 ( peerblk, "PEERBLK %p %d.%d attempting retrieval from %s\n",
  410. peerblk, peerblk->segment, peerblk->block, location );
  411. /* Construct block fetch request */
  412. memset ( &req, 0, sizeof ( req ) );
  413. req.getblks.hdr.version.raw = htonl ( PEERDIST_MSG_GETBLKS_VERSION );
  414. req.getblks.hdr.type = htonl ( PEERDIST_MSG_GETBLKS_TYPE );
  415. req.getblks.hdr.len = htonl ( sizeof ( req ) );
  416. req.getblks.hdr.algorithm = htonl ( PEERDIST_MSG_AES_128_CBC );
  417. req.segment.segment.digestsize = htonl ( digestsize );
  418. memcpy ( req.segment.id, peerblk->id, digestsize );
  419. req.ranges.ranges.count = htonl ( 1 );
  420. req.ranges.range[0].first = htonl ( peerblk->block );
  421. req.ranges.range[0].count = htonl ( 1 );
  422. /* Construct POST request content */
  423. memset ( &content, 0, sizeof ( content ) );
  424. content.data = &req;
  425. content.len = sizeof ( req );
  426. /* Construct URI */
  427. if ( ( uri = peerblk_retrieval_uri ( location ) ) == NULL ) {
  428. rc = -ENOMEM;
  429. goto err_uri;
  430. }
  431. /* Update trim thresholds */
  432. peerblk->start += offsetof ( typeof ( *rsp ), msg.vrf );
  433. peerblk->end += offsetof ( typeof ( *rsp ), msg.vrf );
  434. /* Initiate HTTP POST to retrieve block */
  435. if ( ( rc = http_open ( &peerblk->retrieval, &http_post, uri,
  436. NULL, &content ) ) != 0 ) {
  437. DBGC ( peerblk, "PEERBLK %p %d.%d could not create retrieval "
  438. "request: %s\n", peerblk, peerblk->segment,
  439. peerblk->block, strerror ( rc ) );
  440. goto err_open;
  441. }
  442. /* Annul HTTP connection (for testing) if applicable. Do not
  443. * report as an immediate error, in order to test our ability
  444. * to recover from a totally unresponsive HTTP server.
  445. */
  446. if ( inject_fault ( PEERBLK_ANNUL_RATE ) )
  447. intf_restart ( &peerblk->retrieval, 0 );
  448. /* Start download attempt timer */
  449. peerblk->rc = -ETIMEDOUT;
  450. start_timer_fixed ( &peerblk->timer, PEERBLK_RETRIEVAL_OPEN_TIMEOUT );
  451. err_open:
  452. uri_put ( uri );
  453. err_uri:
  454. return rc;
  455. }
  456. /**
  457. * Receive PeerDist retrieval protocol data
  458. *
  459. * @v peerblk PeerDist block download
  460. * @v iobuf I/O buffer
  461. * @v meta Data transfer metadata
  462. * @ret rc Return status code
  463. */
  464. static int peerblk_retrieval_rx ( struct peerdist_block *peerblk,
  465. struct io_buffer *iobuf,
  466. struct xfer_metadata *meta ) {
  467. size_t len = iob_len ( iobuf );
  468. size_t start;
  469. size_t end;
  470. size_t before;
  471. size_t after;
  472. size_t cut;
  473. int rc;
  474. /* Some genius at Microsoft thought it would be a great idea
  475. * to place the AES-CBC initialisation vector *after* the
  476. * encrypted data, thereby making it logically impossible to
  477. * decrypt each packet as it arrives.
  478. *
  479. * To work around this mindless stupidity, we deliver the
  480. * ciphertext as-is and later use xfer_buffer() to obtain
  481. * access to the underlying data transfer buffer in order to
  482. * perform the decryption.
  483. *
  484. * There will be some data both before and after the bytes
  485. * corresponding to the trimmed plaintext: a MSG_BLK
  486. * header/footer, some block padding for the AES-CBC cipher,
  487. * and a possibly large quantity of unwanted ciphertext which
  488. * is excluded from the trimmed content range. We store this
  489. * data in a local data transfer buffer. If the amount of
  490. * data to be stored is too large, we will fail allocation and
  491. * so eventually fall back to using a range request (which
  492. * does not require this kind of temporary storage
  493. * allocation).
  494. */
  495. /* Corrupt received data (for testing) if applicable */
  496. inject_corruption ( PEERBLK_CORRUPT_RATE, iobuf->data, len );
  497. /* Calculate start and end positions of this buffer */
  498. start = peerblk->pos;
  499. if ( meta->flags & XFER_FL_ABS_OFFSET )
  500. start = 0;
  501. start += meta->offset;
  502. end = ( start + len );
  503. /* Buffer any data before the trimmed content */
  504. if ( ( start < peerblk->start ) && ( len > 0 ) ) {
  505. /* Calculate length of data before the trimmed content */
  506. before = ( peerblk->start - start );
  507. if ( before > len )
  508. before = len;
  509. /* Buffer data before the trimmed content */
  510. if ( ( rc = xferbuf_write ( &peerblk->buffer, start,
  511. iobuf->data, before ) ) != 0 ) {
  512. DBGC ( peerblk, "PEERBLK %p %d.%d could not buffer "
  513. "data: %s\n", peerblk, peerblk->segment,
  514. peerblk->block, strerror ( rc ) );
  515. goto err;
  516. }
  517. }
  518. /* Buffer any data after the trimmed content */
  519. if ( ( end > peerblk->end ) && ( len > 0 ) ) {
  520. /* Calculate length of data after the trimmed content */
  521. after = ( end - peerblk->end );
  522. if ( after > len )
  523. after = len;
  524. /* Buffer data after the trimmed content */
  525. cut = ( peerblk->end - peerblk->start );
  526. if ( ( rc = xferbuf_write ( &peerblk->buffer,
  527. ( end - after - cut ),
  528. ( iobuf->data + len - after ),
  529. after ) ) != 0 ) {
  530. DBGC ( peerblk, "PEERBLK %p %d.%d could not buffer "
  531. "data: %s\n", peerblk, peerblk->segment,
  532. peerblk->block, strerror ( rc ) );
  533. goto err;
  534. }
  535. }
  536. /* Deliver any remaining data */
  537. if ( ( rc = peerblk_deliver ( peerblk, iob_disown ( iobuf ), meta,
  538. start ) ) != 0 )
  539. goto err;
  540. /* Update position */
  541. peerblk->pos = end;
  542. /* Extend download attempt timer */
  543. start_timer_fixed ( &peerblk->timer, PEERBLK_RETRIEVAL_RX_TIMEOUT );
  544. /* Stall download attempt (for testing) if applicable */
  545. if ( ( start < peerblk->end ) && ( end >= peerblk->end ) &&
  546. ( ( rc = inject_fault ( PEERBLK_STALL_RATE ) ) != 0 ) ) {
  547. intf_restart ( &peerblk->retrieval, rc );
  548. }
  549. return 0;
  550. err:
  551. free_iob ( iobuf );
  552. peerblk_done ( peerblk, rc );
  553. return rc;
  554. }
  555. /**
  556. * Parse retrieval protocol message header
  557. *
  558. * @v peerblk PeerDist block download
  559. * @ret rc Return status code
  560. */
  561. static int peerblk_parse_header ( struct peerdist_block *peerblk ) {
  562. struct {
  563. struct peerdist_msg_transport_header hdr;
  564. struct peerdist_msg_header msg;
  565. } __attribute__ (( packed )) *msg = peerblk->buffer.data;
  566. struct cipher_algorithm *cipher;
  567. size_t len = peerblk->buffer.len;
  568. size_t keylen = 0;
  569. int rc;
  570. /* Check message length */
  571. if ( len < sizeof ( *msg ) ) {
  572. DBGC ( peerblk, "PEERBLK %p %d.%d message too short for header "
  573. "(%zd bytes)\n", peerblk, peerblk->segment,
  574. peerblk->block, len );
  575. return -ERANGE;
  576. }
  577. /* Check message type */
  578. if ( msg->msg.type != htonl ( PEERDIST_MSG_BLK_TYPE ) ) {
  579. DBGC ( peerblk, "PEERBLK %p %d.%d unexpected message type "
  580. "%#08x\n", peerblk, peerblk->segment, peerblk->block,
  581. ntohl ( msg->msg.type ) );
  582. return -EPROTO;
  583. }
  584. /* Determine cipher algorithm and key length */
  585. cipher = &aes_cbc_algorithm;
  586. switch ( msg->msg.algorithm ) {
  587. case htonl ( PEERDIST_MSG_PLAINTEXT ) :
  588. cipher = NULL;
  589. break;
  590. case htonl ( PEERDIST_MSG_AES_128_CBC ) :
  591. keylen = ( 128 / 8 );
  592. break;
  593. case htonl ( PEERDIST_MSG_AES_192_CBC ) :
  594. keylen = ( 192 / 8 );
  595. break;
  596. case htonl ( PEERDIST_MSG_AES_256_CBC ) :
  597. keylen = ( 256 / 8 );
  598. break;
  599. default:
  600. DBGC ( peerblk, "PEERBLK %p %d.%d unrecognised algorithm "
  601. "%#08x\n", peerblk, peerblk->segment, peerblk->block,
  602. ntohl ( msg->msg.algorithm ) );
  603. return -ENOTSUP;
  604. }
  605. DBGC2 ( peerblk, "PEERBLK %p %d.%d using %s with %zd-bit key\n",
  606. peerblk, peerblk->segment, peerblk->block,
  607. ( cipher ? cipher->name : "plaintext" ), ( 8 * keylen ) );
  608. /* Sanity check key length against maximum secret length */
  609. if ( keylen > peerblk->digestsize ) {
  610. DBGC ( peerblk, "PEERBLK %p %d.%d %zd-byte secret too short "
  611. "for %zd-bit key\n", peerblk, peerblk->segment,
  612. peerblk->block, peerblk->digestsize, ( 8 * keylen ) );
  613. return -EPROTO;
  614. }
  615. /* Allocate cipher context, if applicable. Freeing the cipher
  616. * context (on error or otherwise) is handled by peerblk_reset().
  617. */
  618. peerblk->cipher = cipher;
  619. assert ( peerblk->cipherctx == NULL );
  620. if ( cipher ) {
  621. peerblk->cipherctx = malloc ( cipher->ctxsize );
  622. if ( ! peerblk->cipherctx )
  623. return -ENOMEM;
  624. }
  625. /* Initialise cipher, if applicable */
  626. if ( cipher &&
  627. ( rc = cipher_setkey ( cipher, peerblk->cipherctx, peerblk->secret,
  628. keylen ) ) != 0 ) {
  629. DBGC ( peerblk, "PEERBLK %p %d.%d could not set key: %s\n",
  630. peerblk, peerblk->segment, peerblk->block,
  631. strerror ( rc ) );
  632. return rc;
  633. }
  634. return 0;
  635. }
  636. /**
  637. * Parse retrieval protocol message segment and block details
  638. *
  639. * @v peerblk PeerDist block download
  640. * @v buf_len Length of buffered data to fill in
  641. * @ret rc Return status code
  642. */
  643. static int peerblk_parse_block ( struct peerdist_block *peerblk,
  644. size_t *buf_len ) {
  645. size_t digestsize = peerblk->digestsize;
  646. peerblk_msg_blk_t ( digestsize, 0, 0, 0 ) *msg = peerblk->buffer.data;
  647. size_t len = peerblk->buffer.len;
  648. size_t data_len;
  649. size_t total;
  650. /* Check message length */
  651. if ( len < offsetof ( typeof ( *msg ), msg.block.data ) ) {
  652. DBGC ( peerblk, "PEERBLK %p %d.%d message too short for "
  653. "zero-length data (%zd bytes)\n", peerblk,
  654. peerblk->segment, peerblk->block, len );
  655. return -ERANGE;
  656. }
  657. /* Check digest size */
  658. if ( ntohl ( msg->msg.segment.segment.digestsize ) != digestsize ) {
  659. DBGC ( peerblk, "PEERBLK %p %d.%d incorrect digest size %d\n",
  660. peerblk, peerblk->segment, peerblk->block,
  661. ntohl ( msg->msg.segment.segment.digestsize ) );
  662. return -EPROTO;
  663. }
  664. /* Check segment ID */
  665. if ( memcmp ( msg->msg.segment.id, peerblk->id, digestsize ) != 0 ) {
  666. DBGC ( peerblk, "PEERBLK %p %d.%d segment ID mismatch\n",
  667. peerblk, peerblk->segment, peerblk->block );
  668. return -EPROTO;
  669. }
  670. /* Check block ID */
  671. if ( ntohl ( msg->msg.index ) != peerblk->block ) {
  672. DBGC ( peerblk, "PEERBLK %p %d.%d block ID mismatch (got %d)\n",
  673. peerblk, peerblk->segment, peerblk->block,
  674. ntohl ( msg->msg.index ) );
  675. return -EPROTO;
  676. }
  677. /* Check for missing blocks */
  678. data_len = be32_to_cpu ( msg->msg.block.block.len );
  679. if ( ! data_len ) {
  680. DBGC ( peerblk, "PEERBLK %p %d.%d block not found\n",
  681. peerblk, peerblk->segment, peerblk->block );
  682. return -ENOENT;
  683. }
  684. /* Check for underlength blocks */
  685. if ( data_len < ( peerblk->range.end - peerblk->range.start ) ) {
  686. DBGC ( peerblk, "PEERBLK %p %d.%d underlength block (%zd "
  687. "bytes)\n", peerblk, peerblk->segment, peerblk->block,
  688. data_len );
  689. return -ERANGE;
  690. }
  691. /* Calculate buffered data length (i.e. excluding data which
  692. * was delivered to the final data transfer buffer).
  693. */
  694. *buf_len = ( data_len - ( peerblk->end - peerblk->start ) );
  695. /* Describe data before the trimmed content */
  696. peerblk->decrypt[PEERBLK_BEFORE].xferbuf = &peerblk->buffer;
  697. peerblk->decrypt[PEERBLK_BEFORE].offset =
  698. offsetof ( typeof ( *msg ), msg.block.data );
  699. peerblk->decrypt[PEERBLK_BEFORE].len =
  700. ( peerblk->start -
  701. offsetof ( typeof ( *msg ), msg.block.data ) );
  702. total = peerblk->decrypt[PEERBLK_BEFORE].len;
  703. /* Describe data within the trimmed content */
  704. peerblk->decrypt[PEERBLK_DURING].offset =
  705. peerblk_offset ( peerblk, peerblk->start );
  706. peerblk->decrypt[PEERBLK_DURING].len =
  707. ( peerblk->end - peerblk->start );
  708. total += peerblk->decrypt[PEERBLK_DURING].len;
  709. /* Describe data after the trimmed content */
  710. peerblk->decrypt[PEERBLK_AFTER].xferbuf = &peerblk->buffer;
  711. peerblk->decrypt[PEERBLK_AFTER].offset = peerblk->start;
  712. peerblk->decrypt[PEERBLK_AFTER].len =
  713. ( offsetof ( typeof ( *msg ), msg.block.data )
  714. + *buf_len - peerblk->start );
  715. total += peerblk->decrypt[PEERBLK_AFTER].len;
  716. /* Sanity check */
  717. assert ( total == be32_to_cpu ( msg->msg.block.block.len ) );
  718. /* Initialise cipher and digest lengths */
  719. peerblk->cipher_remaining = total;
  720. peerblk->digest_remaining =
  721. ( peerblk->range.end - peerblk->range.start );
  722. assert ( peerblk->cipher_remaining >= peerblk->digest_remaining );
  723. return 0;
  724. }
  725. /**
  726. * Parse retrieval protocol message useless details
  727. *
  728. * @v peerblk PeerDist block download
  729. * @v buf_len Length of buffered data
  730. * @v vrf_len Length of uselessness to fill in
  731. * @ret rc Return status code
  732. */
  733. static int peerblk_parse_useless ( struct peerdist_block *peerblk,
  734. size_t buf_len, size_t *vrf_len ) {
  735. size_t digestsize = peerblk->digestsize;
  736. peerblk_msg_blk_t ( digestsize, buf_len, 0, 0 ) *msg =
  737. peerblk->buffer.data;
  738. size_t len = peerblk->buffer.len;
  739. /* Check message length */
  740. if ( len < offsetof ( typeof ( *msg ), msg.vrf.data ) ) {
  741. DBGC ( peerblk, "PEERBLK %p %d.%d message too short for "
  742. "zero-length uselessness (%zd bytes)\n", peerblk,
  743. peerblk->segment, peerblk->block, len );
  744. return -ERANGE;
  745. }
  746. /* Extract length of uselessness */
  747. *vrf_len = be32_to_cpu ( msg->msg.vrf.vrf.len );
  748. return 0;
  749. }
  750. /**
  751. * Parse retrieval protocol message initialisation vector details
  752. *
  753. * @v peerblk PeerDist block download
  754. * @v buf_len Length of buffered data
  755. * @v vrf_len Length of uselessness
  756. * @ret rc Return status code
  757. */
  758. static int peerblk_parse_iv ( struct peerdist_block *peerblk, size_t buf_len,
  759. size_t vrf_len ) {
  760. size_t digestsize = peerblk->digestsize;
  761. size_t blksize = peerblk->cipher->blocksize;
  762. peerblk_msg_blk_t ( digestsize, buf_len, vrf_len, blksize ) *msg =
  763. peerblk->buffer.data;
  764. size_t len = peerblk->buffer.len;
  765. /* Check message length */
  766. if ( len < sizeof ( *msg ) ) {
  767. DBGC ( peerblk, "PEERBLK %p %d.%d message too short for "
  768. "initialisation vector (%zd bytes)\n", peerblk,
  769. peerblk->segment, peerblk->block, len );
  770. return -ERANGE;
  771. }
  772. /* Check initialisation vector size */
  773. if ( ntohl ( msg->msg.iv.iv.blksize ) != blksize ) {
  774. DBGC ( peerblk, "PEERBLK %p %d.%d incorrect IV size %d\n",
  775. peerblk, peerblk->segment, peerblk->block,
  776. ntohl ( msg->msg.iv.iv.blksize ) );
  777. return -EPROTO;
  778. }
  779. /* Set initialisation vector */
  780. cipher_setiv ( peerblk->cipher, peerblk->cipherctx, msg->msg.iv.data );
  781. return 0;
  782. }
  783. /**
  784. * Read from decryption buffers
  785. *
  786. * @v peerblk PeerDist block download
  787. * @v data Data buffer
  788. * @v len Length to read
  789. * @ret rc Return status code
  790. */
  791. static int peerblk_decrypt_read ( struct peerdist_block *peerblk,
  792. void *data, size_t len ) {
  793. struct peerdist_block_decrypt *decrypt = peerblk->decrypt;
  794. size_t frag_len;
  795. int rc;
  796. /* Read from each decryption buffer in turn */
  797. for ( ; len ; decrypt++, data += frag_len, len -= frag_len ) {
  798. /* Calculate length to use from this buffer */
  799. frag_len = decrypt->len;
  800. if ( frag_len > len )
  801. frag_len = len;
  802. if ( ! frag_len )
  803. continue;
  804. /* Read from this buffer */
  805. if ( ( rc = xferbuf_read ( decrypt->xferbuf, decrypt->offset,
  806. data, frag_len ) ) != 0 )
  807. return rc;
  808. }
  809. return 0;
  810. }
  811. /**
  812. * Write to decryption buffers and update offsets and lengths
  813. *
  814. * @v peerblk PeerDist block download
  815. * @v data Data buffer
  816. * @v len Length to read
  817. * @ret rc Return status code
  818. */
  819. static int peerblk_decrypt_write ( struct peerdist_block *peerblk,
  820. const void *data, size_t len ) {
  821. struct peerdist_block_decrypt *decrypt = peerblk->decrypt;
  822. size_t frag_len;
  823. int rc;
  824. /* Write to each decryption buffer in turn */
  825. for ( ; len ; decrypt++, data += frag_len, len -= frag_len ) {
  826. /* Calculate length to use from this buffer */
  827. frag_len = decrypt->len;
  828. if ( frag_len > len )
  829. frag_len = len;
  830. if ( ! frag_len )
  831. continue;
  832. /* Write to this buffer */
  833. if ( ( rc = xferbuf_write ( decrypt->xferbuf, decrypt->offset,
  834. data, frag_len ) ) != 0 )
  835. return rc;
  836. /* Update offset and length */
  837. decrypt->offset += frag_len;
  838. decrypt->len -= frag_len;
  839. }
  840. return 0;
  841. }
  842. /**
  843. * Decrypt one chunk of PeerDist retrieval protocol data
  844. *
  845. * @v peerblk PeerDist block download
  846. */
  847. static void peerblk_decrypt ( struct peerdist_block *peerblk ) {
  848. struct cipher_algorithm *cipher = peerblk->cipher;
  849. struct digest_algorithm *digest = peerblk->digest;
  850. struct xfer_buffer *xferbuf;
  851. size_t cipher_len;
  852. size_t digest_len;
  853. void *data;
  854. int rc;
  855. /* Sanity check */
  856. assert ( ( PEERBLK_DECRYPT_CHUNKSIZE % cipher->blocksize ) == 0 );
  857. /* Get the underlying data transfer buffer */
  858. xferbuf = xfer_buffer ( &peerblk->xfer );
  859. if ( ! xferbuf ) {
  860. DBGC ( peerblk, "PEERBLK %p %d.%d has no underlying data "
  861. "transfer buffer\n", peerblk, peerblk->segment,
  862. peerblk->block );
  863. rc = -ENOTSUP;
  864. goto err_xfer_buffer;
  865. }
  866. peerblk->decrypt[PEERBLK_DURING].xferbuf = xferbuf;
  867. /* Calculate cipher and digest lengths */
  868. cipher_len = PEERBLK_DECRYPT_CHUNKSIZE;
  869. if ( cipher_len > peerblk->cipher_remaining )
  870. cipher_len = peerblk->cipher_remaining;
  871. digest_len = cipher_len;
  872. if ( digest_len > peerblk->digest_remaining )
  873. digest_len = peerblk->digest_remaining;
  874. assert ( ( cipher_len & ( cipher->blocksize - 1 ) ) == 0 );
  875. /* Allocate temporary data buffer */
  876. data = malloc ( cipher_len );
  877. if ( ! data ) {
  878. rc = -ENOMEM;
  879. goto err_alloc_data;
  880. }
  881. /* Read ciphertext */
  882. if ( ( rc = peerblk_decrypt_read ( peerblk, data, cipher_len ) ) != 0 ){
  883. DBGC ( peerblk, "PEERBLK %p %d.%d could not read ciphertext: "
  884. "%s\n", peerblk, peerblk->segment, peerblk->block,
  885. strerror ( rc ) );
  886. goto err_read;
  887. }
  888. /* Decrypt data */
  889. cipher_decrypt ( cipher, peerblk->cipherctx, data, data, cipher_len );
  890. /* Add data to digest */
  891. digest_update ( digest, peerblk->digestctx, data, digest_len );
  892. /* Write plaintext */
  893. if ( ( rc = peerblk_decrypt_write ( peerblk, data, cipher_len ) ) != 0){
  894. DBGC ( peerblk, "PEERBLK %p %d.%d could not write plaintext: "
  895. "%s\n", peerblk, peerblk->segment, peerblk->block,
  896. strerror ( rc ) );
  897. goto err_write;
  898. }
  899. /* Consume input */
  900. peerblk->cipher_remaining -= cipher_len;
  901. peerblk->digest_remaining -= digest_len;
  902. /* Free temporary data buffer */
  903. free ( data );
  904. /* Continue processing until all input is consumed */
  905. if ( peerblk->cipher_remaining )
  906. return;
  907. /* Complete download attempt */
  908. peerblk_done ( peerblk, 0 );
  909. return;
  910. err_write:
  911. err_read:
  912. free ( data );
  913. err_alloc_data:
  914. err_xfer_buffer:
  915. peerblk_done ( peerblk, rc );
  916. }
  917. /**
  918. * Close PeerDist retrieval protocol block download attempt
  919. *
  920. * @v peerblk PeerDist block download
  921. * @v rc Reason for close
  922. */
  923. static void peerblk_retrieval_close ( struct peerdist_block *peerblk, int rc ) {
  924. size_t buf_len;
  925. size_t vrf_len;
  926. /* Restart interface */
  927. intf_restart ( &peerblk->retrieval, rc );
  928. /* Fail immediately if we have an error */
  929. if ( rc != 0 )
  930. goto done;
  931. /* Abort download attempt (for testing) if applicable */
  932. if ( ( rc = inject_fault ( PEERBLK_ABORT_RATE ) ) != 0 )
  933. goto done;
  934. /* Parse message header */
  935. if ( ( rc = peerblk_parse_header ( peerblk ) ) != 0 )
  936. goto done;
  937. /* Parse message segment and block details */
  938. if ( ( rc = peerblk_parse_block ( peerblk, &buf_len ) ) != 0 )
  939. goto done;
  940. /* If the block was plaintext, then there is nothing more to do */
  941. if ( ! peerblk->cipher )
  942. goto done;
  943. /* Parse message useless details */
  944. if ( ( rc = peerblk_parse_useless ( peerblk, buf_len, &vrf_len ) ) != 0)
  945. goto done;
  946. /* Parse message initialisation vector details */
  947. if ( ( rc = peerblk_parse_iv ( peerblk, buf_len, vrf_len ) ) != 0 )
  948. goto done;
  949. /* Fail if decryption length is not aligned to the cipher block size */
  950. if ( peerblk->cipher_remaining & ( peerblk->cipher->blocksize - 1 ) ) {
  951. DBGC ( peerblk, "PEERBLK %p %d.%d unaligned data length %zd\n",
  952. peerblk, peerblk->segment, peerblk->block,
  953. peerblk->cipher_remaining );
  954. rc = -EPROTO;
  955. goto done;
  956. }
  957. /* Stop the download attempt timer: there is no point in
  958. * timing out while decrypting.
  959. */
  960. stop_timer ( &peerblk->timer );
  961. /* Start decryption process */
  962. process_add ( &peerblk->process );
  963. return;
  964. done:
  965. /* Complete download attempt */
  966. peerblk_done ( peerblk, rc );
  967. }
  968. /******************************************************************************
  969. *
  970. * Retry policy
  971. *
  972. ******************************************************************************
  973. */
  974. /**
  975. * Handle PeerDist retry timer expiry
  976. *
  977. * @v timer Retry timer
  978. * @v over Failure indicator
  979. */
  980. static void peerblk_expired ( struct retry_timer *timer, int over __unused ) {
  981. struct peerdist_block *peerblk =
  982. container_of ( timer, struct peerdist_block, timer );
  983. struct peerdisc_segment *segment = peerblk->discovery.segment;
  984. struct peerdisc_peer *head;
  985. unsigned long now = peerblk_timestamp();
  986. const char *location;
  987. int rc;
  988. /* Profile discovery timeout, if applicable */
  989. if ( ( peerblk->peer == NULL ) && ( timer->timeout != 0 ) ) {
  990. profile_custom ( &peerblk_discovery_timeout_profiler,
  991. ( now - peerblk->started ) );
  992. DBGC ( peerblk, "PEERBLK %p %d.%d discovery timed out after "
  993. "%ld ticks\n", peerblk, peerblk->segment,
  994. peerblk->block, timer->timeout );
  995. }
  996. /* Profile download timeout, if applicable */
  997. if ( ( peerblk->peer != NULL ) && ( timer->timeout != 0 ) ) {
  998. profile_custom ( &peerblk_attempt_timeout_profiler,
  999. ( now - peerblk->attempted ) );
  1000. DBGC ( peerblk, "PEERBLK %p %d.%d timed out after %ld ticks\n",
  1001. peerblk, peerblk->segment, peerblk->block,
  1002. timer->timeout );
  1003. }
  1004. /* Abort any current download attempt */
  1005. peerblk_reset ( peerblk, -ETIMEDOUT );
  1006. /* Record attempt start time */
  1007. peerblk->attempted = now;
  1008. /* If we have exceeded our maximum number of attempt cycles
  1009. * (each cycle comprising a retrieval protocol download from
  1010. * each peer in the list followed by a raw download from the
  1011. * origin server), then abort the overall download.
  1012. */
  1013. head = list_entry ( &segment->peers, struct peerdisc_peer, list );
  1014. if ( ( peerblk->peer == head ) &&
  1015. ( ++peerblk->cycles >= PEERBLK_MAX_ATTEMPT_CYCLES ) ) {
  1016. rc = peerblk->rc;
  1017. assert ( rc != 0 );
  1018. goto err;
  1019. }
  1020. /* If we have not yet made any download attempts, then move to
  1021. * the start of the peer list.
  1022. */
  1023. if ( peerblk->peer == NULL )
  1024. peerblk->peer = head;
  1025. /* Attempt retrieval protocol download from next usable peer */
  1026. list_for_each_entry_continue ( peerblk->peer, &segment->peers, list ) {
  1027. /* Attempt retrieval protocol download from this peer */
  1028. location = peerblk->peer->location;
  1029. if ( ( rc = peerblk_retrieval_open ( peerblk,
  1030. location ) ) != 0 ) {
  1031. /* Non-fatal: continue to try next peer */
  1032. continue;
  1033. }
  1034. /* Peer download started */
  1035. return;
  1036. }
  1037. /* Attempt raw download */
  1038. if ( ( rc = peerblk_raw_open ( peerblk ) ) != 0 )
  1039. goto err;
  1040. return;
  1041. err:
  1042. peerblk_close ( peerblk, rc );
  1043. }
  1044. /**
  1045. * Handle PeerDist peer discovery
  1046. *
  1047. * @v discovery PeerDist discovery client
  1048. */
  1049. static void peerblk_discovered ( struct peerdisc_client *discovery ) {
  1050. struct peerdist_block *peerblk =
  1051. container_of ( discovery, struct peerdist_block, discovery );
  1052. unsigned long now = peerblk_timestamp();
  1053. /* Do nothing unless we are still waiting for the initial
  1054. * discovery timeout.
  1055. */
  1056. if ( ( peerblk->peer != NULL ) || ( peerblk->timer.timeout == 0 ) )
  1057. return;
  1058. /* Schedule an immediate retry */
  1059. start_timer_nodelay ( &peerblk->timer );
  1060. /* Profile discovery success */
  1061. profile_custom ( &peerblk_discovery_success_profiler,
  1062. ( now - peerblk->started ) );
  1063. }
  1064. /******************************************************************************
  1065. *
  1066. * Opener
  1067. *
  1068. ******************************************************************************
  1069. */
  1070. /** PeerDist block download data transfer interface operations */
  1071. static struct interface_operation peerblk_xfer_operations[] = {
  1072. INTF_OP ( intf_close, struct peerdist_block *, peerblk_close ),
  1073. };
  1074. /** PeerDist block download data transfer interface descriptor */
  1075. static struct interface_descriptor peerblk_xfer_desc =
  1076. INTF_DESC ( struct peerdist_block, xfer, peerblk_xfer_operations );
  1077. /** PeerDist block download raw data interface operations */
  1078. static struct interface_operation peerblk_raw_operations[] = {
  1079. INTF_OP ( xfer_deliver, struct peerdist_block *, peerblk_raw_rx ),
  1080. INTF_OP ( intf_close, struct peerdist_block *, peerblk_raw_close ),
  1081. };
  1082. /** PeerDist block download raw data interface descriptor */
  1083. static struct interface_descriptor peerblk_raw_desc =
  1084. INTF_DESC ( struct peerdist_block, raw, peerblk_raw_operations );
  1085. /** PeerDist block download retrieval protocol interface operations */
  1086. static struct interface_operation peerblk_retrieval_operations[] = {
  1087. INTF_OP ( xfer_deliver, struct peerdist_block *, peerblk_retrieval_rx ),
  1088. INTF_OP ( intf_close, struct peerdist_block *, peerblk_retrieval_close),
  1089. };
  1090. /** PeerDist block download retrieval protocol interface descriptor */
  1091. static struct interface_descriptor peerblk_retrieval_desc =
  1092. INTF_DESC ( struct peerdist_block, retrieval,
  1093. peerblk_retrieval_operations );
  1094. /** PeerDist block download decryption process descriptor */
  1095. static struct process_descriptor peerblk_process_desc =
  1096. PROC_DESC ( struct peerdist_block, process, peerblk_decrypt );
  1097. /** PeerDist block download discovery operations */
  1098. static struct peerdisc_client_operations peerblk_discovery_operations = {
  1099. .discovered = peerblk_discovered,
  1100. };
  1101. /**
  1102. * Open PeerDist block download
  1103. *
  1104. * @v xfer Data transfer interface
  1105. * @v uri Original URI
  1106. * @v info Content information block
  1107. * @ret rc Return status code
  1108. */
  1109. int peerblk_open ( struct interface *xfer, struct uri *uri,
  1110. struct peerdist_info_block *block ) {
  1111. const struct peerdist_info_segment *segment = block->segment;
  1112. const struct peerdist_info *info = segment->info;
  1113. struct digest_algorithm *digest = info->digest;
  1114. struct peerdist_block *peerblk;
  1115. unsigned long timeout;
  1116. size_t digestsize;
  1117. int rc;
  1118. /* Allocate and initialise structure */
  1119. peerblk = zalloc ( sizeof ( *peerblk ) + digest->ctxsize );
  1120. if ( ! peerblk ) {
  1121. rc = -ENOMEM;
  1122. goto err_alloc;
  1123. }
  1124. ref_init ( &peerblk->refcnt, peerblk_free );
  1125. intf_init ( &peerblk->xfer, &peerblk_xfer_desc, &peerblk->refcnt );
  1126. intf_init ( &peerblk->raw, &peerblk_raw_desc, &peerblk->refcnt );
  1127. intf_init ( &peerblk->retrieval, &peerblk_retrieval_desc,
  1128. &peerblk->refcnt );
  1129. peerblk->uri = uri_get ( uri );
  1130. memcpy ( &peerblk->range, &block->range, sizeof ( peerblk->range ) );
  1131. memcpy ( &peerblk->trim, &block->trim, sizeof ( peerblk->trim ) );
  1132. peerblk->offset = ( block->trim.start - info->trim.start );
  1133. peerblk->digest = info->digest;
  1134. peerblk->digestsize = digestsize = info->digestsize;
  1135. peerblk->digestctx = ( ( ( void * ) peerblk ) + sizeof ( *peerblk ) );
  1136. peerblk->segment = segment->index;
  1137. memcpy ( peerblk->id, segment->id, sizeof ( peerblk->id ) );
  1138. memcpy ( peerblk->secret, segment->secret, sizeof ( peerblk->secret ) );
  1139. peerblk->block = block->index;
  1140. memcpy ( peerblk->hash, block->hash, sizeof ( peerblk->hash ) );
  1141. xferbuf_malloc_init ( &peerblk->buffer );
  1142. process_init_stopped ( &peerblk->process, &peerblk_process_desc,
  1143. &peerblk->refcnt );
  1144. peerdisc_init ( &peerblk->discovery, &peerblk_discovery_operations );
  1145. timer_init ( &peerblk->timer, peerblk_expired, &peerblk->refcnt );
  1146. DBGC2 ( peerblk, "PEERBLK %p %d.%d id %02x%02x%02x%02x%02x..."
  1147. "%02x%02x%02x [%08zx,%08zx)", peerblk, peerblk->segment,
  1148. peerblk->block, peerblk->id[0], peerblk->id[1], peerblk->id[2],
  1149. peerblk->id[3], peerblk->id[4], peerblk->id[ digestsize - 3 ],
  1150. peerblk->id[ digestsize - 2 ], peerblk->id[ digestsize - 1 ],
  1151. peerblk->range.start, peerblk->range.end );
  1152. if ( ( peerblk->trim.start != peerblk->range.start ) ||
  1153. ( peerblk->trim.end != peerblk->range.end ) ) {
  1154. DBGC2 ( peerblk, " covers [%08zx,%08zx)",
  1155. peerblk->trim.start, peerblk->trim.end );
  1156. }
  1157. DBGC2 ( peerblk, "\n" );
  1158. /* Open discovery */
  1159. if ( ( rc = peerdisc_open ( &peerblk->discovery, peerblk->id,
  1160. peerblk->digestsize ) ) != 0 )
  1161. goto err_open_discovery;
  1162. /* Schedule a retry attempt either immediately (if we already
  1163. * have some peers) or after the discovery timeout.
  1164. */
  1165. timeout = ( list_empty ( &peerblk->discovery.segment->peers ) ?
  1166. ( peerdisc_timeout_secs * TICKS_PER_SEC ) : 0 );
  1167. start_timer_fixed ( &peerblk->timer, timeout );
  1168. /* Record start time */
  1169. peerblk->started = peerblk_timestamp();
  1170. /* Attach to parent interface, mortalise self, and return */
  1171. intf_plug_plug ( xfer, &peerblk->xfer );
  1172. ref_put ( &peerblk->refcnt );
  1173. return 0;
  1174. err_open_discovery:
  1175. peerblk_close ( peerblk, rc );
  1176. err_alloc:
  1177. return rc;
  1178. }