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.
 
 
 
 
 
 

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