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.
 
 
 
 
 
 

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