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.
 
 
 
 
 
 

896 lines
26 KiB

  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. /* ######################################################################
  4. HTTP and HTTPS share a lot of common code and these classes are
  5. exactly the dumping ground for this common code
  6. ##################################################################### */
  7. /*}}}*/
  8. // Include Files /*{{{*/
  9. #include <config.h>
  10. #include <apt-pkg/configuration.h>
  11. #include <apt-pkg/error.h>
  12. #include <apt-pkg/fileutl.h>
  13. #include <apt-pkg/strutl.h>
  14. #include <iostream>
  15. #include <limits>
  16. #include <map>
  17. #include <string>
  18. #include <vector>
  19. #include <ctype.h>
  20. #include <signal.h>
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #include <sys/stat.h>
  24. #include <sys/time.h>
  25. #include <time.h>
  26. #include <unistd.h>
  27. #include "basehttp.h"
  28. #include <apti18n.h>
  29. /*}}}*/
  30. using namespace std;
  31. string BaseHttpMethod::FailFile;
  32. int BaseHttpMethod::FailFd = -1;
  33. time_t BaseHttpMethod::FailTime = 0;
  34. // ServerState::RunHeaders - Get the headers before the data /*{{{*/
  35. // ---------------------------------------------------------------------
  36. /* Returns 0 if things are OK, 1 if an IO error occurred and 2 if a header
  37. parse error occurred */
  38. ServerState::RunHeadersResult ServerState::RunHeaders(RequestState &Req,
  39. const std::string &Uri)
  40. {
  41. Owner->Status(_("Waiting for headers"));
  42. do
  43. {
  44. string Data;
  45. if (ReadHeaderLines(Data) == false)
  46. continue;
  47. if (Owner->Debug == true)
  48. clog << "Answer for: " << Uri << endl << Data;
  49. for (string::const_iterator I = Data.begin(); I < Data.end(); ++I)
  50. {
  51. string::const_iterator J = I;
  52. for (; J != Data.end() && *J != '\n' && *J != '\r'; ++J);
  53. if (Req.HeaderLine(string(I,J)) == false)
  54. return RUN_HEADERS_PARSE_ERROR;
  55. I = J;
  56. }
  57. // 100 Continue is a Nop...
  58. if (Req.Result == 100)
  59. continue;
  60. // Tidy up the connection persistence state.
  61. if (Req.Encoding == RequestState::Closes && Req.HaveContent == true)
  62. Persistent = false;
  63. return RUN_HEADERS_OK;
  64. } while (LoadNextResponse(false, Req) == ResultState::SUCCESSFUL);
  65. return RUN_HEADERS_IO_ERROR;
  66. }
  67. /*}}}*/
  68. bool RequestState::HeaderLine(string const &Line) /*{{{*/
  69. {
  70. if (Line.empty() == true)
  71. return true;
  72. if (Result == 0 && Line.size() > 4 && stringcasecmp(Line.data(), Line.data() + 4, "HTTP") == 0)
  73. {
  74. // Evil servers return no version
  75. if (Line[4] == '/')
  76. {
  77. int const elements = sscanf(Line.c_str(),"HTTP/%3u.%3u %3u%359[^\n]",&Major,&Minor,&Result,Code);
  78. if (elements == 3)
  79. {
  80. Code[0] = '\0';
  81. if (Owner != NULL && Owner->Debug == true)
  82. clog << "HTTP server doesn't give Reason-Phrase for " << std::to_string(Result) << std::endl;
  83. }
  84. else if (elements != 4)
  85. return _error->Error(_("The HTTP server sent an invalid reply header"));
  86. }
  87. else
  88. {
  89. Major = 0;
  90. Minor = 9;
  91. if (sscanf(Line.c_str(),"HTTP %3u%359[^\n]",&Result,Code) != 2)
  92. return _error->Error(_("The HTTP server sent an invalid reply header"));
  93. }
  94. /* Check the HTTP response header to get the default persistence
  95. state. */
  96. if (Major < 1)
  97. Server->Persistent = false;
  98. else
  99. {
  100. if (Major == 1 && Minor == 0)
  101. {
  102. Server->Persistent = false;
  103. }
  104. else
  105. {
  106. Server->Persistent = true;
  107. if (Server->PipelineAllowed)
  108. Server->Pipeline = true;
  109. }
  110. }
  111. return true;
  112. }
  113. // Blah, some servers use "connection:closes", evil.
  114. // and some even send empty header fields…
  115. string::size_type Pos = Line.find(':');
  116. if (Pos == string::npos)
  117. return _error->Error(_("Bad header line"));
  118. ++Pos;
  119. // Parse off any trailing spaces between the : and the next word.
  120. string::size_type Pos2 = Pos;
  121. while (Pos2 < Line.length() && isspace_ascii(Line[Pos2]) != 0)
  122. Pos2++;
  123. string const Tag(Line,0,Pos);
  124. string const Val(Line,Pos2);
  125. if (stringcasecmp(Tag,"Content-Length:") == 0)
  126. {
  127. auto ContentLength = strtoull(Val.c_str(), NULL, 10);
  128. if (ContentLength == 0)
  129. return true;
  130. if (Encoding == Closes)
  131. Encoding = Stream;
  132. HaveContent = true;
  133. unsigned long long * DownloadSizePtr = &DownloadSize;
  134. if (Result == 416 || (Result >= 300 && Result < 400))
  135. DownloadSizePtr = &JunkSize;
  136. *DownloadSizePtr = ContentLength;
  137. if (*DownloadSizePtr >= std::numeric_limits<unsigned long long>::max())
  138. return _error->Errno("HeaderLine", _("The HTTP server sent an invalid Content-Length header"));
  139. else if (*DownloadSizePtr == 0)
  140. HaveContent = false;
  141. // On partial content (206) the Content-Length less than the real
  142. // size, so do not set it here but leave that to the Content-Range
  143. // header instead
  144. if(Result != 206 && TotalFileSize == 0)
  145. TotalFileSize = DownloadSize;
  146. return true;
  147. }
  148. if (stringcasecmp(Tag,"Content-Type:") == 0)
  149. {
  150. HaveContent = true;
  151. return true;
  152. }
  153. // The Content-Range field only has a meaning in HTTP/1.1 for the
  154. // 206 (Partial Content) and 416 (Range Not Satisfiable) responses
  155. // according to RFC7233 "Range Requests", §4.2, so only consider it
  156. // for such responses.
  157. if ((Result == 416 || Result == 206) && stringcasecmp(Tag,"Content-Range:") == 0)
  158. {
  159. HaveContent = true;
  160. // §14.16 says 'byte-range-resp-spec' should be a '*' in case of 416
  161. if (Result == 416 && sscanf(Val.c_str(), "bytes */%llu",&TotalFileSize) == 1)
  162. ; // we got the expected filesize which is all we wanted
  163. else if (sscanf(Val.c_str(),"bytes %llu-%*u/%llu",&StartPos,&TotalFileSize) != 2)
  164. return _error->Error(_("The HTTP server sent an invalid Content-Range header"));
  165. if (StartPos > TotalFileSize)
  166. return _error->Error(_("This HTTP server has broken range support"));
  167. // figure out what we will download
  168. DownloadSize = TotalFileSize - StartPos;
  169. return true;
  170. }
  171. if (stringcasecmp(Tag,"Transfer-Encoding:") == 0)
  172. {
  173. HaveContent = true;
  174. if (stringcasecmp(Val,"chunked") == 0)
  175. Encoding = Chunked;
  176. return true;
  177. }
  178. if (stringcasecmp(Tag,"Connection:") == 0)
  179. {
  180. if (stringcasecmp(Val,"close") == 0)
  181. {
  182. Server->Persistent = false;
  183. Server->Pipeline = false;
  184. /* Some servers send error pages (as they are dynamically generated)
  185. for simplicity via a connection close instead of e.g. chunked,
  186. so assuming an always closing server only if we get a file + close */
  187. if (Result >= 200 && Result < 300)
  188. Server->PipelineAllowed = false;
  189. }
  190. else if (stringcasecmp(Val,"keep-alive") == 0)
  191. Server->Persistent = true;
  192. return true;
  193. }
  194. if (stringcasecmp(Tag,"Last-Modified:") == 0)
  195. {
  196. if (RFC1123StrToTime(Val.c_str(), Date) == false)
  197. return _error->Error(_("Unknown date format"));
  198. return true;
  199. }
  200. if (stringcasecmp(Tag,"Location:") == 0)
  201. {
  202. Location = Val;
  203. return true;
  204. }
  205. if (stringcasecmp(Tag, "Accept-Ranges:") == 0)
  206. {
  207. std::string ranges = ',' + Val + ',';
  208. ranges.erase(std::remove(ranges.begin(), ranges.end(), ' '), ranges.end());
  209. if (ranges.find(",bytes,") == std::string::npos)
  210. Server->RangesAllowed = false;
  211. return true;
  212. }
  213. return true;
  214. }
  215. /*}}}*/
  216. // ServerState::ServerState - Constructor /*{{{*/
  217. ServerState::ServerState(URI Srv, BaseHttpMethod *Owner) :
  218. ServerName(Srv), TimeOut(120), Owner(Owner)
  219. {
  220. Reset();
  221. }
  222. /*}}}*/
  223. bool RequestState::AddPartialFileToHashes(FileFd &File) /*{{{*/
  224. {
  225. File.Truncate(StartPos);
  226. return Server->GetHashes()->AddFD(File, StartPos);
  227. }
  228. /*}}}*/
  229. void ServerState::Reset() /*{{{*/
  230. {
  231. Persistent = false;
  232. Pipeline = false;
  233. PipelineAllowed = true;
  234. RangesAllowed = true;
  235. }
  236. /*}}}*/
  237. // BaseHttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
  238. // ---------------------------------------------------------------------
  239. /* We look at the header data we got back from the server and decide what
  240. to do. Returns DealWithHeadersResult (see http.h for details).
  241. */
  242. BaseHttpMethod::DealWithHeadersResult
  243. BaseHttpMethod::DealWithHeaders(FetchResult &Res, RequestState &Req)
  244. {
  245. // Not Modified
  246. if (Req.Result == 304)
  247. {
  248. RemoveFile("server", Queue->DestFile);
  249. Res.IMSHit = true;
  250. Res.LastModified = Queue->LastModified;
  251. Res.Size = 0;
  252. return IMS_HIT;
  253. }
  254. /* Note that it is only OK for us to treat all redirection the same
  255. because we *always* use GET, not other HTTP methods.
  256. Codes not mentioned are handled as errors later as required by the
  257. HTTP spec to handle unknown codes the same as the x00 code. */
  258. constexpr unsigned int RedirectCodes[] = {
  259. 301, // Moved Permanently
  260. 302, // Found
  261. 303, // See Other
  262. 307, // Temporary Redirect
  263. 308, // Permanent Redirect
  264. };
  265. if (AllowRedirect && std::find(std::begin(RedirectCodes), std::end(RedirectCodes), Req.Result) != std::end(RedirectCodes))
  266. {
  267. if (Req.Location.empty() == true)
  268. ;
  269. else if (Req.Location[0] == '/' && Queue->Uri.empty() == false)
  270. {
  271. URI Uri = Queue->Uri;
  272. if (Uri.Host.empty() == false)
  273. NextURI = URI::SiteOnly(Uri);
  274. else
  275. NextURI.clear();
  276. NextURI.append(DeQuoteString(Req.Location));
  277. if (Queue->Uri == NextURI)
  278. {
  279. SetFailReason("RedirectionLoop");
  280. _error->Error("Redirection loop encountered");
  281. if (Req.HaveContent == true)
  282. return ERROR_WITH_CONTENT_PAGE;
  283. return ERROR_UNRECOVERABLE;
  284. }
  285. return TRY_AGAIN_OR_REDIRECT;
  286. }
  287. else
  288. {
  289. NextURI = DeQuoteString(Req.Location);
  290. URI tmpURI = NextURI;
  291. if (tmpURI.Access.find('+') != std::string::npos)
  292. {
  293. _error->Error("Server tried to trick us into using a specific implementation: %s", tmpURI.Access.c_str());
  294. if (Req.HaveContent == true)
  295. return ERROR_WITH_CONTENT_PAGE;
  296. return ERROR_UNRECOVERABLE;
  297. }
  298. URI Uri = Queue->Uri;
  299. if (Binary.find('+') != std::string::npos)
  300. {
  301. auto base = Binary.substr(0, Binary.find('+'));
  302. if (base != tmpURI.Access)
  303. {
  304. tmpURI.Access = base + '+' + tmpURI.Access;
  305. if (tmpURI.Access == Binary)
  306. {
  307. std::string tmpAccess = Uri.Access;
  308. std::swap(tmpURI.Access, Uri.Access);
  309. NextURI = tmpURI;
  310. std::swap(tmpURI.Access, Uri.Access);
  311. }
  312. else
  313. NextURI = tmpURI;
  314. }
  315. }
  316. if (Queue->Uri == NextURI)
  317. {
  318. SetFailReason("RedirectionLoop");
  319. _error->Error("Redirection loop encountered");
  320. if (Req.HaveContent == true)
  321. return ERROR_WITH_CONTENT_PAGE;
  322. return ERROR_UNRECOVERABLE;
  323. }
  324. Uri.Access = Binary;
  325. // same protocol redirects are okay
  326. if (tmpURI.Access == Uri.Access)
  327. return TRY_AGAIN_OR_REDIRECT;
  328. // as well as http to https
  329. else if ((Uri.Access == "http" || Uri.Access == "https+http") && tmpURI.Access == "https")
  330. return TRY_AGAIN_OR_REDIRECT;
  331. else
  332. {
  333. auto const tmpplus = tmpURI.Access.find('+');
  334. if (tmpplus != std::string::npos && tmpURI.Access.substr(tmpplus + 1) == "https")
  335. {
  336. auto const uriplus = Uri.Access.find('+');
  337. if (uriplus == std::string::npos)
  338. {
  339. if (Uri.Access == tmpURI.Access.substr(0, tmpplus)) // foo -> foo+https
  340. return TRY_AGAIN_OR_REDIRECT;
  341. }
  342. else if (Uri.Access.substr(uriplus + 1) == "http" &&
  343. Uri.Access.substr(0, uriplus) == tmpURI.Access.substr(0, tmpplus)) // foo+http -> foo+https
  344. return TRY_AGAIN_OR_REDIRECT;
  345. }
  346. }
  347. _error->Error("Redirection from %s to '%s' is forbidden", Uri.Access.c_str(), NextURI.c_str());
  348. }
  349. /* else pass through for error message */
  350. }
  351. // retry after an invalid range response without partial data
  352. else if (Req.Result == 416)
  353. {
  354. struct stat SBuf;
  355. if (stat(Queue->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
  356. {
  357. bool partialHit = false;
  358. if (Queue->ExpectedHashes.usable() == true)
  359. {
  360. Hashes resultHashes(Queue->ExpectedHashes);
  361. FileFd file(Queue->DestFile, FileFd::ReadOnly);
  362. Req.TotalFileSize = file.FileSize();
  363. Req.Date = file.ModificationTime();
  364. resultHashes.AddFD(file);
  365. HashStringList const hashList = resultHashes.GetHashStringList();
  366. partialHit = (Queue->ExpectedHashes == hashList);
  367. }
  368. else if ((unsigned long long)SBuf.st_size == Req.TotalFileSize)
  369. partialHit = true;
  370. if (partialHit == true)
  371. {
  372. // the file is completely downloaded, but was not moved
  373. if (Req.HaveContent == true)
  374. {
  375. // nuke the sent error page
  376. Server->RunDataToDevNull(Req);
  377. Req.HaveContent = false;
  378. }
  379. Req.StartPos = Req.TotalFileSize;
  380. Req.Result = 200;
  381. }
  382. else if (RemoveFile("server", Queue->DestFile))
  383. {
  384. NextURI = Queue->Uri;
  385. return TRY_AGAIN_OR_REDIRECT;
  386. }
  387. }
  388. }
  389. /* We have a reply we don't handle. This should indicate a perm server
  390. failure */
  391. if (Req.Result < 200 || Req.Result >= 300)
  392. {
  393. if (_error->PendingError() == false)
  394. {
  395. std::string err;
  396. strprintf(err, "HttpError%u", Req.Result);
  397. SetFailReason(err);
  398. _error->Error("%u %s", Req.Result, Req.Code);
  399. }
  400. if (Req.HaveContent == true)
  401. return ERROR_WITH_CONTENT_PAGE;
  402. return ERROR_UNRECOVERABLE;
  403. }
  404. // This is some sort of 2xx 'data follows' reply
  405. Res.LastModified = Req.Date;
  406. Res.Size = Req.TotalFileSize;
  407. return FILE_IS_OPEN;
  408. }
  409. /*}}}*/
  410. // BaseHttpMethod::SigTerm - Handle a fatal signal /*{{{*/
  411. // ---------------------------------------------------------------------
  412. /* This closes and timestamps the open file. This is necessary to get
  413. resume behavior on user abort */
  414. void BaseHttpMethod::SigTerm(int)
  415. {
  416. if (FailFd == -1)
  417. _exit(100);
  418. struct timeval times[2];
  419. times[0].tv_sec = FailTime;
  420. times[1].tv_sec = FailTime;
  421. times[0].tv_usec = times[1].tv_usec = 0;
  422. utimes(FailFile.c_str(), times);
  423. close(FailFd);
  424. _exit(100);
  425. }
  426. /*}}}*/
  427. // BaseHttpMethod::Fetch - Fetch an item /*{{{*/
  428. // ---------------------------------------------------------------------
  429. /* This adds an item to the pipeline. We keep the pipeline at a fixed
  430. depth. */
  431. bool BaseHttpMethod::Fetch(FetchItem *)
  432. {
  433. if (Server == nullptr || QueueBack == nullptr)
  434. return true;
  435. // If pipelining is disabled, we only queue 1 request
  436. auto const AllowedDepth = Server->Pipeline ? PipelineDepth : 0;
  437. // how deep is our pipeline currently?
  438. decltype(PipelineDepth) CurrentDepth = 0;
  439. for (FetchItem const *I = Queue; I != QueueBack; I = I->Next)
  440. ++CurrentDepth;
  441. if (CurrentDepth > AllowedDepth)
  442. return true;
  443. do {
  444. // Make sure we stick with the same server
  445. if (Server->Comp(QueueBack->Uri) == false)
  446. break;
  447. bool const UsableHashes = QueueBack->ExpectedHashes.usable();
  448. // if we have no hashes, do at most one such request
  449. // as we can't fixup pipeling misbehaviors otherwise
  450. if (CurrentDepth != 0 && UsableHashes == false)
  451. break;
  452. if (UsableHashes && FileExists(QueueBack->DestFile))
  453. {
  454. FileFd partial(QueueBack->DestFile, FileFd::ReadOnly);
  455. Hashes wehave(QueueBack->ExpectedHashes);
  456. if (QueueBack->ExpectedHashes.FileSize() == partial.FileSize())
  457. {
  458. if (wehave.AddFD(partial) &&
  459. wehave.GetHashStringList() == QueueBack->ExpectedHashes)
  460. {
  461. FetchResult Res;
  462. Res.Filename = QueueBack->DestFile;
  463. Res.ResumePoint = QueueBack->ExpectedHashes.FileSize();
  464. URIStart(Res);
  465. // move item to the start of the queue as URIDone will
  466. // always dequeued the first item in the queue
  467. if (Queue != QueueBack)
  468. {
  469. FetchItem *Prev = Queue;
  470. for (; Prev->Next != QueueBack; Prev = Prev->Next)
  471. /* look for the previous queue item */;
  472. Prev->Next = QueueBack->Next;
  473. QueueBack->Next = Queue;
  474. Queue = QueueBack;
  475. QueueBack = Prev->Next;
  476. }
  477. Res.TakeHashes(wehave);
  478. URIDone(Res);
  479. continue;
  480. }
  481. else
  482. RemoveFile("Fetch-Partial", QueueBack->DestFile);
  483. }
  484. }
  485. auto const Tmp = QueueBack;
  486. QueueBack = QueueBack->Next;
  487. SendReq(Tmp);
  488. ++CurrentDepth;
  489. } while (CurrentDepth <= AllowedDepth && QueueBack != nullptr);
  490. return true;
  491. }
  492. /*}}}*/
  493. // BaseHttpMethod::Loop - Main loop /*{{{*/
  494. int BaseHttpMethod::Loop()
  495. {
  496. signal(SIGTERM,SigTerm);
  497. signal(SIGINT,SigTerm);
  498. Server = 0;
  499. int FailCounter = 0;
  500. while (1)
  501. {
  502. // We have no commands, wait for some to arrive
  503. if (Queue == 0)
  504. {
  505. if (WaitFd(STDIN_FILENO) == false)
  506. return 0;
  507. }
  508. /* Run messages, we can accept 0 (no message) if we didn't
  509. do a WaitFd above.. Otherwise the FD is closed. */
  510. int Result = Run(true);
  511. if (Result != -1 && (Result != 0 || Queue == 0))
  512. {
  513. if(FailReason.empty() == false ||
  514. ConfigFindB("DependOnSTDIN", true) == true)
  515. return 100;
  516. else
  517. return 0;
  518. }
  519. if (Queue == 0)
  520. continue;
  521. // Connect to the server
  522. if (Server == 0 || Server->Comp(Queue->Uri) == false)
  523. {
  524. if (!Queue->Proxy().empty())
  525. {
  526. URI uri = Queue->Uri;
  527. _config->Set("Acquire::" + uri.Access + "::proxy::" + uri.Host, Queue->Proxy());
  528. }
  529. Server = CreateServerState(Queue->Uri);
  530. setPostfixForMethodNames(::URI(Queue->Uri).Host.c_str());
  531. AllowRedirect = ConfigFindB("AllowRedirect", true);
  532. PipelineDepth = ConfigFindI("Pipeline-Depth", 10);
  533. Debug = DebugEnabled();
  534. }
  535. /* If the server has explicitly said this is the last connection
  536. then we pre-emptively shut down the pipeline and tear down
  537. the connection. This will speed up HTTP/1.0 servers a tad
  538. since we don't have to wait for the close sequence to
  539. complete */
  540. if (Server->Persistent == false)
  541. Server->Close();
  542. // Reset the pipeline
  543. if (Server->IsOpen() == false)
  544. QueueBack = Queue;
  545. // Connect to the host
  546. switch (Server->Open())
  547. {
  548. case ResultState::FATAL_ERROR:
  549. Fail(false);
  550. Server = nullptr;
  551. continue;
  552. case ResultState::TRANSIENT_ERROR:
  553. Fail(true);
  554. Server = nullptr;
  555. continue;
  556. case ResultState::SUCCESSFUL:
  557. break;
  558. }
  559. // Fill the pipeline.
  560. Fetch(0);
  561. RequestState Req(this, Server.get());
  562. // Fetch the next URL header data from the server.
  563. switch (Server->RunHeaders(Req, Queue->Uri))
  564. {
  565. case ServerState::RUN_HEADERS_OK:
  566. break;
  567. // The header data is bad
  568. case ServerState::RUN_HEADERS_PARSE_ERROR:
  569. {
  570. _error->Error(_("Bad header data"));
  571. Fail(true);
  572. Server->Close();
  573. RotateDNS();
  574. continue;
  575. }
  576. // The server closed a connection during the header get..
  577. default:
  578. case ServerState::RUN_HEADERS_IO_ERROR:
  579. {
  580. FailCounter++;
  581. _error->Discard();
  582. Server->Close();
  583. Server->Pipeline = false;
  584. Server->PipelineAllowed = false;
  585. if (FailCounter >= 2)
  586. {
  587. Fail(_("Connection failed"),true);
  588. FailCounter = 0;
  589. }
  590. RotateDNS();
  591. continue;
  592. }
  593. };
  594. // Decide what to do.
  595. FetchResult Res;
  596. Res.Filename = Queue->DestFile;
  597. switch (DealWithHeaders(Res, Req))
  598. {
  599. // Ok, the file is Open
  600. case FILE_IS_OPEN:
  601. {
  602. URIStart(Res);
  603. // Run the data
  604. ResultState Result = ResultState::SUCCESSFUL;
  605. // ensure we don't fetch too much
  606. // we could do "Server->MaximumSize = Queue->MaximumSize" here
  607. // but that would break the clever pipeline messup detection
  608. // so instead we use the size of the biggest item in the queue
  609. Req.MaximumSize = FindMaximumObjectSizeInQueue();
  610. if (Req.HaveContent)
  611. {
  612. /* If the server provides Content-Length we can figure out with it if
  613. this satisfies any request we have made so far (in the pipeline).
  614. If not we can kill the connection as whatever file the server is trying
  615. to send to us would be rejected with a hashsum mismatch later or triggers
  616. a maximum size error. We don't run the data to /dev/null as this can be MBs
  617. of junk data we would waste bandwidth on and instead just close the connection
  618. to reopen a fresh one which should be more cost/time efficient */
  619. if (Req.DownloadSize > 0)
  620. {
  621. decltype(Queue->ExpectedHashes.FileSize()) const filesize = Req.StartPos + Req.DownloadSize;
  622. bool found = false;
  623. for (FetchItem const *I = Queue; I != 0 && I != QueueBack; I = I->Next)
  624. {
  625. auto const fs = I->ExpectedHashes.FileSize();
  626. if (fs == 0 || fs == filesize)
  627. {
  628. found = true;
  629. break;
  630. }
  631. }
  632. if (found == false)
  633. {
  634. SetFailReason("MaximumSizeExceeded");
  635. _error->Error(_("File has unexpected size (%llu != %llu). Mirror sync in progress?"),
  636. filesize, Queue->ExpectedHashes.FileSize());
  637. Result = ResultState::FATAL_ERROR;
  638. }
  639. }
  640. if (Result == ResultState::SUCCESSFUL)
  641. Result = Server->RunData(Req);
  642. }
  643. /* If the server is sending back sizeless responses then fill in
  644. the size now */
  645. if (Res.Size == 0)
  646. Res.Size = Req.File.Size();
  647. // Close the file, destroy the FD object and timestamp it
  648. FailFd = -1;
  649. Req.File.Close();
  650. // Timestamp
  651. struct timeval times[2];
  652. times[0].tv_sec = times[1].tv_sec = Req.Date;
  653. times[0].tv_usec = times[1].tv_usec = 0;
  654. utimes(Queue->DestFile.c_str(), times);
  655. // Send status to APT
  656. if (Result == ResultState::SUCCESSFUL)
  657. {
  658. Hashes * const resultHashes = Server->GetHashes();
  659. HashStringList const hashList = resultHashes->GetHashStringList();
  660. if (PipelineDepth != 0 && Queue->ExpectedHashes.usable() == true && Queue->ExpectedHashes != hashList)
  661. {
  662. // we did not get the expected hash… mhhh:
  663. // could it be that server/proxy messed up pipelining?
  664. FetchItem * BeforeI = Queue;
  665. for (FetchItem *I = Queue->Next; I != 0 && I != QueueBack; I = I->Next)
  666. {
  667. if (I->ExpectedHashes.usable() == true && I->ExpectedHashes == hashList)
  668. {
  669. // yes, he did! Disable pipelining and rewrite queue
  670. if (Server->Pipeline == true)
  671. {
  672. Warning(_("Automatically disabled %s due to incorrect response from server/proxy. (man 5 apt.conf)"), "Acquire::http::Pipeline-Depth");
  673. Server->Pipeline = false;
  674. Server->PipelineAllowed = false;
  675. // we keep the PipelineDepth value so that the rest of the queue can be fixed up as well
  676. }
  677. Rename(Res.Filename, I->DestFile);
  678. Res.Filename = I->DestFile;
  679. BeforeI->Next = I->Next;
  680. I->Next = Queue;
  681. Queue = I;
  682. break;
  683. }
  684. BeforeI = I;
  685. }
  686. }
  687. Res.TakeHashes(*resultHashes);
  688. URIDone(Res);
  689. }
  690. else
  691. {
  692. if (Server->IsOpen() == false)
  693. {
  694. FailCounter++;
  695. _error->Discard();
  696. Server->Close();
  697. if (FailCounter >= 2)
  698. {
  699. Fail(_("Connection failed"),true);
  700. FailCounter = 0;
  701. }
  702. QueueBack = Queue;
  703. }
  704. else
  705. {
  706. Server->Close();
  707. switch (Result)
  708. {
  709. case ResultState::TRANSIENT_ERROR:
  710. Fail(true);
  711. break;
  712. case ResultState::FATAL_ERROR:
  713. case ResultState::SUCCESSFUL:
  714. Fail(false);
  715. break;
  716. }
  717. }
  718. }
  719. break;
  720. }
  721. // IMS hit
  722. case IMS_HIT:
  723. {
  724. URIDone(Res);
  725. break;
  726. }
  727. // Hard server error, not found or something
  728. case ERROR_UNRECOVERABLE:
  729. {
  730. Fail();
  731. break;
  732. }
  733. // Hard internal error, kill the connection and fail
  734. case ERROR_NOT_FROM_SERVER:
  735. {
  736. Fail();
  737. RotateDNS();
  738. Server->Close();
  739. break;
  740. }
  741. // We need to flush the data, the header is like a 404 w/ error text
  742. case ERROR_WITH_CONTENT_PAGE:
  743. {
  744. Server->RunDataToDevNull(Req);
  745. constexpr unsigned int TransientCodes[] = {
  746. 408, // Request Timeout
  747. 429, // Too Many Requests
  748. 500, // Internal Server Error
  749. 502, // Bad Gateway
  750. 503, // Service Unavailable
  751. 504, // Gateway Timeout
  752. 599, // Network Connect Timeout Error
  753. };
  754. if (std::find(std::begin(TransientCodes), std::end(TransientCodes), Req.Result) != std::end(TransientCodes))
  755. Fail(true);
  756. else
  757. Fail();
  758. break;
  759. }
  760. // Try again with a new URL
  761. case TRY_AGAIN_OR_REDIRECT:
  762. {
  763. // Clear rest of response if there is content
  764. if (Req.HaveContent)
  765. Server->RunDataToDevNull(Req);
  766. Redirect(NextURI);
  767. break;
  768. }
  769. default:
  770. Fail(_("Internal error"));
  771. break;
  772. }
  773. FailCounter = 0;
  774. }
  775. return 0;
  776. }
  777. /*}}}*/
  778. unsigned long long BaseHttpMethod::FindMaximumObjectSizeInQueue() const /*{{{*/
  779. {
  780. unsigned long long MaxSizeInQueue = 0;
  781. for (FetchItem *I = Queue; I != 0 && I != QueueBack; I = I->Next)
  782. MaxSizeInQueue = std::max(MaxSizeInQueue, I->MaximumSize);
  783. return MaxSizeInQueue;
  784. }
  785. /*}}}*/
  786. BaseHttpMethod::BaseHttpMethod(std::string &&Binary, char const * const Ver,unsigned long const Flags) :/*{{{*/
  787. aptAuthConfMethod(std::move(Binary), Ver, Flags), Server(nullptr), PipelineDepth(10),
  788. AllowRedirect(false), Debug(false)
  789. {
  790. }
  791. /*}}}*/
  792. bool BaseHttpMethod::Configuration(std::string Message) /*{{{*/
  793. {
  794. if (aptAuthConfMethod::Configuration(Message) == false)
  795. return false;
  796. _config->CndSet("Acquire::tor::Proxy",
  797. "socks5h://apt-transport-tor@127.0.0.1:9050");
  798. return true;
  799. }
  800. /*}}}*/
  801. bool BaseHttpMethod::AddProxyAuth(URI &Proxy, URI const &Server) /*{{{*/
  802. {
  803. MaybeAddAuthTo(Proxy);
  804. if (std::find(methodNames.begin(), methodNames.end(), "tor") != methodNames.end() &&
  805. Proxy.User == "apt-transport-tor" && Proxy.Password.empty())
  806. {
  807. std::string pass = Server.Host;
  808. pass.erase(std::remove_if(pass.begin(), pass.end(), [](char const c) { return std::isalnum(c) == 0; }), pass.end());
  809. if (pass.length() > 255)
  810. Proxy.Password = pass.substr(0, 255);
  811. else
  812. Proxy.Password = std::move(pass);
  813. }
  814. return true;
  815. }
  816. /*}}}*/