server.cc 17 KB

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