server.cc 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  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/acquire-method.h>
  11. #include <apt-pkg/configuration.h>
  12. #include <apt-pkg/error.h>
  13. #include <apt-pkg/fileutl.h>
  14. #include <apt-pkg/strutl.h>
  15. #include <ctype.h>
  16. #include <signal.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <sys/stat.h>
  20. #include <sys/time.h>
  21. #include <time.h>
  22. #include <unistd.h>
  23. #include <iostream>
  24. #include <limits>
  25. #include <map>
  26. #include <string>
  27. #include <vector>
  28. #include "server.h"
  29. #include <apti18n.h>
  30. /*}}}*/
  31. using namespace std;
  32. string ServerMethod::FailFile;
  33. int ServerMethod::FailFd = -1;
  34. time_t ServerMethod::FailTime = 0;
  35. // ServerState::RunHeaders - Get the headers before the data /*{{{*/
  36. // ---------------------------------------------------------------------
  37. /* Returns 0 if things are OK, 1 if an IO error occurred and 2 if a header
  38. parse error occurred */
  39. ServerState::RunHeadersResult ServerState::RunHeaders(FileFd * const File,
  40. const std::string &Uri)
  41. {
  42. State = Header;
  43. Owner->Status(_("Waiting for headers"));
  44. Major = 0;
  45. Minor = 0;
  46. Result = 0;
  47. Size = 0;
  48. StartPos = 0;
  49. Encoding = Closes;
  50. HaveContent = false;
  51. time(&Date);
  52. do
  53. {
  54. string Data;
  55. if (ReadHeaderLines(Data) == false)
  56. continue;
  57. if (Owner->Debug == true)
  58. clog << "Answer for: " << Uri << endl << Data;
  59. for (string::const_iterator I = Data.begin(); I < Data.end(); ++I)
  60. {
  61. string::const_iterator J = I;
  62. for (; J != Data.end() && *J != '\n' && *J != '\r'; ++J);
  63. if (HeaderLine(string(I,J)) == false)
  64. return RUN_HEADERS_PARSE_ERROR;
  65. I = J;
  66. }
  67. // 100 Continue is a Nop...
  68. if (Result == 100)
  69. continue;
  70. // Tidy up the connection persistence state.
  71. if (Encoding == Closes && HaveContent == true)
  72. Persistent = false;
  73. return RUN_HEADERS_OK;
  74. }
  75. while (LoadNextResponse(false, File) == true);
  76. return RUN_HEADERS_IO_ERROR;
  77. }
  78. /*}}}*/
  79. // ServerState::HeaderLine - Process a header line /*{{{*/
  80. // ---------------------------------------------------------------------
  81. /* */
  82. bool ServerState::HeaderLine(string Line)
  83. {
  84. if (Line.empty() == true)
  85. return true;
  86. string::size_type Pos = Line.find(' ');
  87. if (Pos == string::npos || Pos+1 > Line.length())
  88. {
  89. // Blah, some servers use "connection:closes", evil.
  90. Pos = Line.find(':');
  91. if (Pos == string::npos || Pos + 2 > Line.length())
  92. return _error->Error(_("Bad header line"));
  93. Pos++;
  94. }
  95. // Parse off any trailing spaces between the : and the next word.
  96. string::size_type Pos2 = Pos;
  97. while (Pos2 < Line.length() && isspace(Line[Pos2]) != 0)
  98. Pos2++;
  99. string Tag = string(Line,0,Pos);
  100. string Val = string(Line,Pos2);
  101. if (stringcasecmp(Tag.c_str(),Tag.c_str()+4,"HTTP") == 0)
  102. {
  103. // Evil servers return no version
  104. if (Line[4] == '/')
  105. {
  106. int const elements = sscanf(Line.c_str(),"HTTP/%3u.%3u %3u%359[^\n]",&Major,&Minor,&Result,Code);
  107. if (elements == 3)
  108. {
  109. Code[0] = '\0';
  110. if (Owner->Debug == true)
  111. clog << "HTTP server doesn't give Reason-Phrase for " << Result << std::endl;
  112. }
  113. else if (elements != 4)
  114. return _error->Error(_("The HTTP server sent an invalid reply header"));
  115. }
  116. else
  117. {
  118. Major = 0;
  119. Minor = 9;
  120. if (sscanf(Line.c_str(),"HTTP %3u%359[^\n]",&Result,Code) != 2)
  121. return _error->Error(_("The HTTP server sent an invalid reply header"));
  122. }
  123. /* Check the HTTP response header to get the default persistence
  124. state. */
  125. if (Major < 1)
  126. Persistent = false;
  127. else
  128. {
  129. if (Major == 1 && Minor == 0)
  130. Persistent = false;
  131. else
  132. Persistent = true;
  133. }
  134. return true;
  135. }
  136. if (stringcasecmp(Tag,"Content-Length:") == 0)
  137. {
  138. if (Encoding == Closes)
  139. Encoding = Stream;
  140. HaveContent = true;
  141. // The length is already set from the Content-Range header
  142. if (StartPos != 0)
  143. return true;
  144. Size = strtoull(Val.c_str(), NULL, 10);
  145. if (Size >= std::numeric_limits<unsigned long long>::max())
  146. return _error->Errno("HeaderLine", _("The HTTP server sent an invalid Content-Length header"));
  147. else if (Size == 0)
  148. HaveContent = false;
  149. return true;
  150. }
  151. if (stringcasecmp(Tag,"Content-Type:") == 0)
  152. {
  153. HaveContent = true;
  154. return true;
  155. }
  156. if (stringcasecmp(Tag,"Content-Range:") == 0)
  157. {
  158. HaveContent = true;
  159. // §14.16 says 'byte-range-resp-spec' should be a '*' in case of 416
  160. if (Result == 416 && sscanf(Val.c_str(), "bytes */%llu",&Size) == 1)
  161. {
  162. StartPos = 1; // ignore Content-Length, it would override Size
  163. HaveContent = false;
  164. }
  165. else if (sscanf(Val.c_str(),"bytes %llu-%*u/%llu",&StartPos,&Size) != 2)
  166. return _error->Error(_("The HTTP server sent an invalid Content-Range header"));
  167. if ((unsigned long long)StartPos > Size)
  168. return _error->Error(_("This HTTP server has broken range support"));
  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. Persistent = false;
  182. if (stringcasecmp(Val,"keep-alive") == 0)
  183. Persistent = true;
  184. return true;
  185. }
  186. if (stringcasecmp(Tag,"Last-Modified:") == 0)
  187. {
  188. if (RFC1123StrToTime(Val.c_str(), Date) == false)
  189. return _error->Error(_("Unknown date format"));
  190. return true;
  191. }
  192. if (stringcasecmp(Tag,"Location:") == 0)
  193. {
  194. Location = Val;
  195. return true;
  196. }
  197. return true;
  198. }
  199. /*}}}*/
  200. // ServerState::ServerState - Constructor /*{{{*/
  201. ServerState::ServerState(URI Srv, ServerMethod *Owner) : ServerName(Srv), TimeOut(120), Owner(Owner)
  202. {
  203. Reset();
  204. }
  205. /*}}}*/
  206. bool ServerMethod::Configuration(string Message) /*{{{*/
  207. {
  208. return pkgAcqMethod::Configuration(Message);
  209. }
  210. /*}}}*/
  211. // ServerMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
  212. // ---------------------------------------------------------------------
  213. /* We look at the header data we got back from the server and decide what
  214. to do. Returns DealWithHeadersResult (see http.h for details).
  215. */
  216. ServerMethod::DealWithHeadersResult
  217. ServerMethod::DealWithHeaders(FetchResult &Res)
  218. {
  219. // Not Modified
  220. if (Server->Result == 304)
  221. {
  222. unlink(Queue->DestFile.c_str());
  223. Res.IMSHit = true;
  224. Res.LastModified = Queue->LastModified;
  225. return IMS_HIT;
  226. }
  227. /* Redirect
  228. *
  229. * Note that it is only OK for us to treat all redirection the same
  230. * because we *always* use GET, not other HTTP methods. There are
  231. * three redirection codes for which it is not appropriate that we
  232. * redirect. Pass on those codes so the error handling kicks in.
  233. */
  234. if (AllowRedirect
  235. && (Server->Result > 300 && Server->Result < 400)
  236. && (Server->Result != 300 // Multiple Choices
  237. && Server->Result != 304 // Not Modified
  238. && Server->Result != 306)) // (Not part of HTTP/1.1, reserved)
  239. {
  240. if (Server->Location.empty() == true);
  241. else if (Server->Location[0] == '/' && Queue->Uri.empty() == false)
  242. {
  243. URI Uri = Queue->Uri;
  244. if (Uri.Host.empty() == false)
  245. NextURI = URI::SiteOnly(Uri);
  246. else
  247. NextURI.clear();
  248. NextURI.append(DeQuoteString(Server->Location));
  249. return TRY_AGAIN_OR_REDIRECT;
  250. }
  251. else
  252. {
  253. NextURI = DeQuoteString(Server->Location);
  254. URI tmpURI = NextURI;
  255. URI Uri = Queue->Uri;
  256. // same protocol redirects are okay
  257. if (tmpURI.Access == Uri.Access)
  258. return TRY_AGAIN_OR_REDIRECT;
  259. // as well as http to https
  260. else if (Uri.Access == "http" && tmpURI.Access == "https")
  261. return TRY_AGAIN_OR_REDIRECT;
  262. }
  263. /* else pass through for error message */
  264. }
  265. // retry after an invalid range response without partial data
  266. else if (Server->Result == 416)
  267. {
  268. struct stat SBuf;
  269. if (stat(Queue->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
  270. {
  271. if ((unsigned long long)SBuf.st_size == Server->Size)
  272. {
  273. // the file is completely downloaded, but was not moved
  274. Server->StartPos = Server->Size;
  275. Server->Result = 200;
  276. Server->HaveContent = false;
  277. }
  278. else if (unlink(Queue->DestFile.c_str()) == 0)
  279. {
  280. NextURI = Queue->Uri;
  281. return TRY_AGAIN_OR_REDIRECT;
  282. }
  283. }
  284. }
  285. /* We have a reply we dont handle. This should indicate a perm server
  286. failure */
  287. if (Server->Result < 200 || Server->Result >= 300)
  288. {
  289. std::string err;
  290. strprintf(err, "HttpError%u", Server->Result);
  291. SetFailReason(err);
  292. _error->Error("%u %s", Server->Result, Server->Code);
  293. if (Server->HaveContent == true)
  294. return ERROR_WITH_CONTENT_PAGE;
  295. return ERROR_UNRECOVERABLE;
  296. }
  297. // This is some sort of 2xx 'data follows' reply
  298. Res.LastModified = Server->Date;
  299. Res.Size = Server->Size;
  300. // Open the file
  301. delete File;
  302. File = new FileFd(Queue->DestFile,FileFd::WriteAny);
  303. if (_error->PendingError() == true)
  304. return ERROR_NOT_FROM_SERVER;
  305. FailFile = Queue->DestFile;
  306. FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
  307. FailFd = File->Fd();
  308. FailTime = Server->Date;
  309. if (Server->InitHashes(*File) == false)
  310. {
  311. _error->Errno("read",_("Problem hashing file"));
  312. return ERROR_NOT_FROM_SERVER;
  313. }
  314. if (Server->StartPos > 0)
  315. Res.ResumePoint = Server->StartPos;
  316. SetNonBlock(File->Fd(),true);
  317. return FILE_IS_OPEN;
  318. }
  319. /*}}}*/
  320. // ServerMethod::SigTerm - Handle a fatal signal /*{{{*/
  321. // ---------------------------------------------------------------------
  322. /* This closes and timestamps the open file. This is necessary to get
  323. resume behavoir on user abort */
  324. void ServerMethod::SigTerm(int)
  325. {
  326. if (FailFd == -1)
  327. _exit(100);
  328. struct timeval times[2];
  329. times[0].tv_sec = FailTime;
  330. times[1].tv_sec = FailTime;
  331. times[0].tv_usec = times[1].tv_usec = 0;
  332. utimes(FailFile.c_str(), times);
  333. close(FailFd);
  334. _exit(100);
  335. }
  336. /*}}}*/
  337. // ServerMethod::Fetch - Fetch an item /*{{{*/
  338. // ---------------------------------------------------------------------
  339. /* This adds an item to the pipeline. We keep the pipeline at a fixed
  340. depth. */
  341. bool ServerMethod::Fetch(FetchItem *)
  342. {
  343. if (Server == 0)
  344. return true;
  345. // Queue the requests
  346. int Depth = -1;
  347. for (FetchItem *I = Queue; I != 0 && Depth < (signed)PipelineDepth;
  348. I = I->Next, Depth++)
  349. {
  350. if (Depth >= 0)
  351. {
  352. // If pipelining is disabled, we only queue 1 request
  353. if (Server->Pipeline == false)
  354. break;
  355. // if we have no hashes, do at most one such request
  356. // as we can't fixup pipeling misbehaviors otherwise
  357. else if (I->ExpectedHashes.usable() == false)
  358. break;
  359. }
  360. // Make sure we stick with the same server
  361. if (Server->Comp(I->Uri) == false)
  362. break;
  363. if (QueueBack == I)
  364. {
  365. QueueBack = I->Next;
  366. SendReq(I);
  367. continue;
  368. }
  369. }
  370. return true;
  371. }
  372. /*}}}*/
  373. // ServerMethod::Loop - Main loop /*{{{*/
  374. int ServerMethod::Loop()
  375. {
  376. typedef vector<string> StringVector;
  377. typedef vector<string>::iterator StringVectorIterator;
  378. map<string, StringVector> Redirected;
  379. signal(SIGTERM,SigTerm);
  380. signal(SIGINT,SigTerm);
  381. Server = 0;
  382. int FailCounter = 0;
  383. while (1)
  384. {
  385. // We have no commands, wait for some to arrive
  386. if (Queue == 0)
  387. {
  388. if (WaitFd(STDIN_FILENO) == false)
  389. return 0;
  390. }
  391. /* Run messages, we can accept 0 (no message) if we didn't
  392. do a WaitFd above.. Otherwise the FD is closed. */
  393. int Result = Run(true);
  394. if (Result != -1 && (Result != 0 || Queue == 0))
  395. {
  396. if(FailReason.empty() == false ||
  397. _config->FindB("Acquire::http::DependOnSTDIN", true) == true)
  398. return 100;
  399. else
  400. return 0;
  401. }
  402. if (Queue == 0)
  403. continue;
  404. // Connect to the server
  405. if (Server == 0 || Server->Comp(Queue->Uri) == false)
  406. {
  407. delete Server;
  408. Server = CreateServerState(Queue->Uri);
  409. }
  410. /* If the server has explicitly said this is the last connection
  411. then we pre-emptively shut down the pipeline and tear down
  412. the connection. This will speed up HTTP/1.0 servers a tad
  413. since we don't have to wait for the close sequence to
  414. complete */
  415. if (Server->Persistent == false)
  416. Server->Close();
  417. // Reset the pipeline
  418. if (Server->IsOpen() == false)
  419. QueueBack = Queue;
  420. // Connnect to the host
  421. if (Server->Open() == false)
  422. {
  423. Fail(true);
  424. delete Server;
  425. Server = 0;
  426. continue;
  427. }
  428. // Fill the pipeline.
  429. Fetch(0);
  430. // Fetch the next URL header data from the server.
  431. switch (Server->RunHeaders(File, Queue->Uri))
  432. {
  433. case ServerState::RUN_HEADERS_OK:
  434. break;
  435. // The header data is bad
  436. case ServerState::RUN_HEADERS_PARSE_ERROR:
  437. {
  438. _error->Error(_("Bad header data"));
  439. Fail(true);
  440. RotateDNS();
  441. continue;
  442. }
  443. // The server closed a connection during the header get..
  444. default:
  445. case ServerState::RUN_HEADERS_IO_ERROR:
  446. {
  447. FailCounter++;
  448. _error->Discard();
  449. Server->Close();
  450. Server->Pipeline = false;
  451. if (FailCounter >= 2)
  452. {
  453. Fail(_("Connection failed"),true);
  454. FailCounter = 0;
  455. }
  456. RotateDNS();
  457. continue;
  458. }
  459. };
  460. // Decide what to do.
  461. FetchResult Res;
  462. Res.Filename = Queue->DestFile;
  463. switch (DealWithHeaders(Res))
  464. {
  465. // Ok, the file is Open
  466. case FILE_IS_OPEN:
  467. {
  468. URIStart(Res);
  469. // Run the data
  470. bool Result = true;
  471. // ensure we don't fetch too much
  472. // we could do "Server->MaximumSize = Queue->MaximumSize" here
  473. // but that would break the clever pipeline messup detection
  474. // so instead we use the size of the biggest item in the queue
  475. Server->MaximumSize = FindMaximumObjectSizeInQueue();
  476. if (Server->HaveContent)
  477. Result = Server->RunData(File);
  478. /* If the server is sending back sizeless responses then fill in
  479. the size now */
  480. if (Res.Size == 0)
  481. Res.Size = File->Size();
  482. // Close the file, destroy the FD object and timestamp it
  483. FailFd = -1;
  484. delete File;
  485. File = 0;
  486. // Timestamp
  487. struct timeval times[2];
  488. times[0].tv_sec = times[1].tv_sec = Server->Date;
  489. times[0].tv_usec = times[1].tv_usec = 0;
  490. utimes(Queue->DestFile.c_str(), times);
  491. // Send status to APT
  492. if (Result == true)
  493. {
  494. Hashes * const resultHashes = Server->GetHashes();
  495. HashStringList const hashList = resultHashes->GetHashStringList();
  496. if (PipelineDepth != 0 && Queue->ExpectedHashes.usable() == true && Queue->ExpectedHashes != hashList)
  497. {
  498. // we did not get the expected hash… mhhh:
  499. // could it be that server/proxy messed up pipelining?
  500. FetchItem * BeforeI = Queue;
  501. for (FetchItem *I = Queue->Next; I != 0 && I != QueueBack; I = I->Next)
  502. {
  503. if (I->ExpectedHashes.usable() == true && I->ExpectedHashes == hashList)
  504. {
  505. // yes, he did! Disable pipelining and rewrite queue
  506. if (Server->Pipeline == true)
  507. {
  508. // FIXME: fake a warning message as we have no proper way of communicating here
  509. std::string out;
  510. strprintf(out, _("Automatically disabled %s due to incorrect response from server/proxy. (man 5 apt.conf)"), "Acquire::http::PipelineDepth");
  511. std::cerr << "W: " << out << std::endl;
  512. Server->Pipeline = false;
  513. // we keep the PipelineDepth value so that the rest of the queue can be fixed up as well
  514. }
  515. Rename(Res.Filename, I->DestFile);
  516. Res.Filename = I->DestFile;
  517. BeforeI->Next = I->Next;
  518. I->Next = Queue;
  519. Queue = I;
  520. break;
  521. }
  522. BeforeI = I;
  523. }
  524. }
  525. Res.TakeHashes(*resultHashes);
  526. URIDone(Res);
  527. }
  528. else
  529. {
  530. if (Server->IsOpen() == false)
  531. {
  532. FailCounter++;
  533. _error->Discard();
  534. Server->Close();
  535. if (FailCounter >= 2)
  536. {
  537. Fail(_("Connection failed"),true);
  538. FailCounter = 0;
  539. }
  540. QueueBack = Queue;
  541. }
  542. else
  543. {
  544. Server->Close();
  545. Fail(true);
  546. }
  547. }
  548. break;
  549. }
  550. // IMS hit
  551. case IMS_HIT:
  552. {
  553. URIDone(Res);
  554. break;
  555. }
  556. // Hard server error, not found or something
  557. case ERROR_UNRECOVERABLE:
  558. {
  559. Fail();
  560. break;
  561. }
  562. // Hard internal error, kill the connection and fail
  563. case ERROR_NOT_FROM_SERVER:
  564. {
  565. delete File;
  566. File = 0;
  567. Fail();
  568. RotateDNS();
  569. Server->Close();
  570. break;
  571. }
  572. // We need to flush the data, the header is like a 404 w/ error text
  573. case ERROR_WITH_CONTENT_PAGE:
  574. {
  575. Fail();
  576. // Send to content to dev/null
  577. File = new FileFd("/dev/null",FileFd::WriteExists);
  578. Server->RunData(File);
  579. delete File;
  580. File = 0;
  581. break;
  582. }
  583. // Try again with a new URL
  584. case TRY_AGAIN_OR_REDIRECT:
  585. {
  586. // Clear rest of response if there is content
  587. if (Server->HaveContent)
  588. {
  589. File = new FileFd("/dev/null",FileFd::WriteExists);
  590. Server->RunData(File);
  591. delete File;
  592. File = 0;
  593. }
  594. /* Detect redirect loops. No more redirects are allowed
  595. after the same URI is seen twice in a queue item. */
  596. StringVector &R = Redirected[Queue->DestFile];
  597. bool StopRedirects = false;
  598. if (R.empty() == true)
  599. R.push_back(Queue->Uri);
  600. else if (R[0] == "STOP" || R.size() > 10)
  601. StopRedirects = true;
  602. else
  603. {
  604. for (StringVectorIterator I = R.begin(); I != R.end(); ++I)
  605. if (Queue->Uri == *I)
  606. {
  607. R[0] = "STOP";
  608. break;
  609. }
  610. R.push_back(Queue->Uri);
  611. }
  612. if (StopRedirects == false)
  613. Redirect(NextURI);
  614. else
  615. Fail();
  616. break;
  617. }
  618. default:
  619. Fail(_("Internal error"));
  620. break;
  621. }
  622. FailCounter = 0;
  623. }
  624. return 0;
  625. }
  626. /*}}}*/
  627. /*{{{*/
  628. unsigned long long
  629. ServerMethod::FindMaximumObjectSizeInQueue() const
  630. {
  631. unsigned long long MaxSizeInQueue = 0;
  632. for (FetchItem *I = Queue->Next; I != 0 && I != QueueBack; I = I->Next)
  633. MaxSizeInQueue = std::max(MaxSizeInQueue, I->MaximumSize);
  634. return MaxSizeInQueue;
  635. }
  636. /*}}}*/