server.cc 17 KB

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