server.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  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. char err[255];
  290. snprintf(err,sizeof(err)-1,"HttpError%i",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 pipelining is disabled, we only queue 1 request
  351. if (Server->Pipeline == false && Depth >= 0)
  352. break;
  353. // Make sure we stick with the same server
  354. if (Server->Comp(I->Uri) == false)
  355. break;
  356. if (QueueBack == I)
  357. {
  358. QueueBack = I->Next;
  359. SendReq(I);
  360. continue;
  361. }
  362. }
  363. return true;
  364. }
  365. /*}}}*/
  366. // ServerMethod::Loop - Main loop /*{{{*/
  367. int ServerMethod::Loop()
  368. {
  369. typedef vector<string> StringVector;
  370. typedef vector<string>::iterator StringVectorIterator;
  371. map<string, StringVector> Redirected;
  372. signal(SIGTERM,SigTerm);
  373. signal(SIGINT,SigTerm);
  374. Server = 0;
  375. int FailCounter = 0;
  376. while (1)
  377. {
  378. // We have no commands, wait for some to arrive
  379. if (Queue == 0)
  380. {
  381. if (WaitFd(STDIN_FILENO) == false)
  382. return 0;
  383. }
  384. /* Run messages, we can accept 0 (no message) if we didn't
  385. do a WaitFd above.. Otherwise the FD is closed. */
  386. int Result = Run(true);
  387. if (Result != -1 && (Result != 0 || Queue == 0))
  388. {
  389. if(FailReason.empty() == false ||
  390. _config->FindB("Acquire::http::DependOnSTDIN", true) == true)
  391. return 100;
  392. else
  393. return 0;
  394. }
  395. if (Queue == 0)
  396. continue;
  397. // Connect to the server
  398. if (Server == 0 || Server->Comp(Queue->Uri) == false)
  399. {
  400. delete Server;
  401. Server = CreateServerState(Queue->Uri);
  402. }
  403. /* If the server has explicitly said this is the last connection
  404. then we pre-emptively shut down the pipeline and tear down
  405. the connection. This will speed up HTTP/1.0 servers a tad
  406. since we don't have to wait for the close sequence to
  407. complete */
  408. if (Server->Persistent == false)
  409. Server->Close();
  410. // Reset the pipeline
  411. if (Server->IsOpen() == false)
  412. QueueBack = Queue;
  413. // Connnect to the host
  414. if (Server->Open() == false)
  415. {
  416. Fail(true);
  417. delete Server;
  418. Server = 0;
  419. continue;
  420. }
  421. // Fill the pipeline.
  422. Fetch(0);
  423. // Fetch the next URL header data from the server.
  424. switch (Server->RunHeaders(File, Queue->Uri))
  425. {
  426. case ServerState::RUN_HEADERS_OK:
  427. break;
  428. // The header data is bad
  429. case ServerState::RUN_HEADERS_PARSE_ERROR:
  430. {
  431. _error->Error(_("Bad header data"));
  432. Fail(true);
  433. RotateDNS();
  434. continue;
  435. }
  436. // The server closed a connection during the header get..
  437. default:
  438. case ServerState::RUN_HEADERS_IO_ERROR:
  439. {
  440. FailCounter++;
  441. _error->Discard();
  442. Server->Close();
  443. Server->Pipeline = false;
  444. if (FailCounter >= 2)
  445. {
  446. Fail(_("Connection failed"),true);
  447. FailCounter = 0;
  448. }
  449. RotateDNS();
  450. continue;
  451. }
  452. };
  453. // Decide what to do.
  454. FetchResult Res;
  455. Res.Filename = Queue->DestFile;
  456. switch (DealWithHeaders(Res))
  457. {
  458. // Ok, the file is Open
  459. case FILE_IS_OPEN:
  460. {
  461. URIStart(Res);
  462. // Run the data
  463. bool Result = true;
  464. if (Server->HaveContent)
  465. Result = Server->RunData(File);
  466. /* If the server is sending back sizeless responses then fill in
  467. the size now */
  468. if (Res.Size == 0)
  469. Res.Size = File->Size();
  470. // Close the file, destroy the FD object and timestamp it
  471. FailFd = -1;
  472. delete File;
  473. File = 0;
  474. // Timestamp
  475. struct timeval times[2];
  476. times[0].tv_sec = times[1].tv_sec = Server->Date;
  477. times[0].tv_usec = times[1].tv_usec = 0;
  478. utimes(Queue->DestFile.c_str(), times);
  479. // Send status to APT
  480. if (Result == true)
  481. {
  482. Res.TakeHashes(*Server->GetHashes());
  483. URIDone(Res);
  484. }
  485. else
  486. {
  487. if (Server->IsOpen() == false)
  488. {
  489. FailCounter++;
  490. _error->Discard();
  491. Server->Close();
  492. if (FailCounter >= 2)
  493. {
  494. Fail(_("Connection failed"),true);
  495. FailCounter = 0;
  496. }
  497. QueueBack = Queue;
  498. }
  499. else
  500. Fail(true);
  501. }
  502. break;
  503. }
  504. // IMS hit
  505. case IMS_HIT:
  506. {
  507. URIDone(Res);
  508. break;
  509. }
  510. // Hard server error, not found or something
  511. case ERROR_UNRECOVERABLE:
  512. {
  513. Fail();
  514. break;
  515. }
  516. // Hard internal error, kill the connection and fail
  517. case ERROR_NOT_FROM_SERVER:
  518. {
  519. delete File;
  520. File = 0;
  521. Fail();
  522. RotateDNS();
  523. Server->Close();
  524. break;
  525. }
  526. // We need to flush the data, the header is like a 404 w/ error text
  527. case ERROR_WITH_CONTENT_PAGE:
  528. {
  529. Fail();
  530. // Send to content to dev/null
  531. File = new FileFd("/dev/null",FileFd::WriteExists);
  532. Server->RunData(File);
  533. delete File;
  534. File = 0;
  535. break;
  536. }
  537. // Try again with a new URL
  538. case TRY_AGAIN_OR_REDIRECT:
  539. {
  540. // Clear rest of response if there is content
  541. if (Server->HaveContent)
  542. {
  543. File = new FileFd("/dev/null",FileFd::WriteExists);
  544. Server->RunData(File);
  545. delete File;
  546. File = 0;
  547. }
  548. /* Detect redirect loops. No more redirects are allowed
  549. after the same URI is seen twice in a queue item. */
  550. StringVector &R = Redirected[Queue->DestFile];
  551. bool StopRedirects = false;
  552. if (R.empty() == true)
  553. R.push_back(Queue->Uri);
  554. else if (R[0] == "STOP" || R.size() > 10)
  555. StopRedirects = true;
  556. else
  557. {
  558. for (StringVectorIterator I = R.begin(); I != R.end(); ++I)
  559. if (Queue->Uri == *I)
  560. {
  561. R[0] = "STOP";
  562. break;
  563. }
  564. R.push_back(Queue->Uri);
  565. }
  566. if (StopRedirects == false)
  567. Redirect(NextURI);
  568. else
  569. Fail();
  570. break;
  571. }
  572. default:
  573. Fail(_("Internal error"));
  574. break;
  575. }
  576. FailCounter = 0;
  577. }
  578. return 0;
  579. }
  580. /*}}}*/