server.cc 18 KB

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