http.cc 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: http.cc,v 1.59 2004/05/08 19:42:35 mdz Exp $
  4. /* ######################################################################
  5. HTTP Acquire Method - This is the HTTP aquire method for APT.
  6. It uses HTTP/1.1 and many of the fancy options there-in, such as
  7. pipelining, range, if-range and so on.
  8. It is based on a doubly buffered select loop. A groupe of requests are
  9. fed into a single output buffer that is constantly fed out the
  10. socket. This provides ideal pipelining as in many cases all of the
  11. requests will fit into a single packet. The input socket is buffered
  12. the same way and fed into the fd for the file (may be a pipe in future).
  13. This double buffering provides fairly substantial transfer rates,
  14. compared to wget the http method is about 4% faster. Most importantly,
  15. when HTTP is compared with FTP as a protocol the speed difference is
  16. huge. In tests over the internet from two sites to llug (via ATM) this
  17. program got 230k/s sustained http transfer rates. FTP on the other
  18. hand topped out at 170k/s. That combined with the time to setup the
  19. FTP connection makes HTTP a vastly superior protocol.
  20. ##################################################################### */
  21. /*}}}*/
  22. // Include Files /*{{{*/
  23. #include <config.h>
  24. #include <apt-pkg/fileutl.h>
  25. #include <apt-pkg/acquire-method.h>
  26. #include <apt-pkg/configuration.h>
  27. #include <apt-pkg/error.h>
  28. #include <apt-pkg/hashes.h>
  29. #include <apt-pkg/netrc.h>
  30. #include <sys/stat.h>
  31. #include <sys/time.h>
  32. #include <utime.h>
  33. #include <unistd.h>
  34. #include <signal.h>
  35. #include <stdio.h>
  36. #include <errno.h>
  37. #include <string.h>
  38. #include <climits>
  39. #include <iostream>
  40. #include <map>
  41. // Internet stuff
  42. #include <netdb.h>
  43. #include "config.h"
  44. #include "connect.h"
  45. #include "rfc2553emu.h"
  46. #include "http.h"
  47. #include <apti18n.h>
  48. /*}}}*/
  49. using namespace std;
  50. string HttpMethod::FailFile;
  51. int HttpMethod::FailFd = -1;
  52. time_t HttpMethod::FailTime = 0;
  53. unsigned long PipelineDepth = 0;
  54. unsigned long TimeOut = 120;
  55. bool AllowRedirect = false;
  56. bool Debug = false;
  57. URI Proxy;
  58. unsigned long long CircleBuf::BwReadLimit=0;
  59. unsigned long long CircleBuf::BwTickReadData=0;
  60. struct timeval CircleBuf::BwReadTick={0,0};
  61. const unsigned int CircleBuf::BW_HZ=10;
  62. // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
  63. // ---------------------------------------------------------------------
  64. /* */
  65. CircleBuf::CircleBuf(unsigned long long Size) : Size(Size), Hash(0)
  66. {
  67. Buf = new unsigned char[Size];
  68. Reset();
  69. CircleBuf::BwReadLimit = _config->FindI("Acquire::http::Dl-Limit",0)*1024;
  70. }
  71. /*}}}*/
  72. // CircleBuf::Reset - Reset to the default state /*{{{*/
  73. // ---------------------------------------------------------------------
  74. /* */
  75. void CircleBuf::Reset()
  76. {
  77. InP = 0;
  78. OutP = 0;
  79. StrPos = 0;
  80. MaxGet = (unsigned long long)-1;
  81. OutQueue = string();
  82. if (Hash != 0)
  83. {
  84. delete Hash;
  85. Hash = new Hashes;
  86. }
  87. };
  88. /*}}}*/
  89. // CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
  90. // ---------------------------------------------------------------------
  91. /* This fills up the buffer with as much data as is in the FD, assuming it
  92. is non-blocking.. */
  93. bool CircleBuf::Read(int Fd)
  94. {
  95. unsigned long long BwReadMax;
  96. while (1)
  97. {
  98. // Woops, buffer is full
  99. if (InP - OutP == Size)
  100. return true;
  101. // what's left to read in this tick
  102. BwReadMax = CircleBuf::BwReadLimit/BW_HZ;
  103. if(CircleBuf::BwReadLimit) {
  104. struct timeval now;
  105. gettimeofday(&now,0);
  106. unsigned long long d = (now.tv_sec-CircleBuf::BwReadTick.tv_sec)*1000000 +
  107. now.tv_usec-CircleBuf::BwReadTick.tv_usec;
  108. if(d > 1000000/BW_HZ) {
  109. CircleBuf::BwReadTick = now;
  110. CircleBuf::BwTickReadData = 0;
  111. }
  112. if(CircleBuf::BwTickReadData >= BwReadMax) {
  113. usleep(1000000/BW_HZ);
  114. return true;
  115. }
  116. }
  117. // Write the buffer segment
  118. ssize_t Res;
  119. if(CircleBuf::BwReadLimit) {
  120. Res = read(Fd,Buf + (InP%Size),
  121. BwReadMax > LeftRead() ? LeftRead() : BwReadMax);
  122. } else
  123. Res = read(Fd,Buf + (InP%Size),LeftRead());
  124. if(Res > 0 && BwReadLimit > 0)
  125. CircleBuf::BwTickReadData += Res;
  126. if (Res == 0)
  127. return false;
  128. if (Res < 0)
  129. {
  130. if (errno == EAGAIN)
  131. return true;
  132. return false;
  133. }
  134. if (InP == 0)
  135. gettimeofday(&Start,0);
  136. InP += Res;
  137. }
  138. }
  139. /*}}}*/
  140. // CircleBuf::Read - Put the string into the buffer /*{{{*/
  141. // ---------------------------------------------------------------------
  142. /* This will hold the string in and fill the buffer with it as it empties */
  143. bool CircleBuf::Read(string Data)
  144. {
  145. OutQueue += Data;
  146. FillOut();
  147. return true;
  148. }
  149. /*}}}*/
  150. // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
  151. // ---------------------------------------------------------------------
  152. /* */
  153. void CircleBuf::FillOut()
  154. {
  155. if (OutQueue.empty() == true)
  156. return;
  157. while (1)
  158. {
  159. // Woops, buffer is full
  160. if (InP - OutP == Size)
  161. return;
  162. // Write the buffer segment
  163. unsigned long long Sz = LeftRead();
  164. if (OutQueue.length() - StrPos < Sz)
  165. Sz = OutQueue.length() - StrPos;
  166. memcpy(Buf + (InP%Size),OutQueue.c_str() + StrPos,Sz);
  167. // Advance
  168. StrPos += Sz;
  169. InP += Sz;
  170. if (OutQueue.length() == StrPos)
  171. {
  172. StrPos = 0;
  173. OutQueue = "";
  174. return;
  175. }
  176. }
  177. }
  178. /*}}}*/
  179. // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
  180. // ---------------------------------------------------------------------
  181. /* This empties the buffer into the FD. */
  182. bool CircleBuf::Write(int Fd)
  183. {
  184. while (1)
  185. {
  186. FillOut();
  187. // Woops, buffer is empty
  188. if (OutP == InP)
  189. return true;
  190. if (OutP == MaxGet)
  191. return true;
  192. // Write the buffer segment
  193. ssize_t Res;
  194. Res = write(Fd,Buf + (OutP%Size),LeftWrite());
  195. if (Res == 0)
  196. return false;
  197. if (Res < 0)
  198. {
  199. if (errno == EAGAIN)
  200. return true;
  201. return false;
  202. }
  203. if (Hash != 0)
  204. Hash->Add(Buf + (OutP%Size),Res);
  205. OutP += Res;
  206. }
  207. }
  208. /*}}}*/
  209. // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
  210. // ---------------------------------------------------------------------
  211. /* This copies till the first empty line */
  212. bool CircleBuf::WriteTillEl(string &Data,bool Single)
  213. {
  214. // We cheat and assume it is unneeded to have more than one buffer load
  215. for (unsigned long long I = OutP; I < InP; I++)
  216. {
  217. if (Buf[I%Size] != '\n')
  218. continue;
  219. ++I;
  220. if (Single == false)
  221. {
  222. if (I < InP && Buf[I%Size] == '\r')
  223. ++I;
  224. if (I >= InP || Buf[I%Size] != '\n')
  225. continue;
  226. ++I;
  227. }
  228. Data = "";
  229. while (OutP < I)
  230. {
  231. unsigned long long Sz = LeftWrite();
  232. if (Sz == 0)
  233. return false;
  234. if (I - OutP < Sz)
  235. Sz = I - OutP;
  236. Data += string((char *)(Buf + (OutP%Size)),Sz);
  237. OutP += Sz;
  238. }
  239. return true;
  240. }
  241. return false;
  242. }
  243. /*}}}*/
  244. // CircleBuf::Stats - Print out stats information /*{{{*/
  245. // ---------------------------------------------------------------------
  246. /* */
  247. void CircleBuf::Stats()
  248. {
  249. if (InP == 0)
  250. return;
  251. struct timeval Stop;
  252. gettimeofday(&Stop,0);
  253. /* float Diff = Stop.tv_sec - Start.tv_sec +
  254. (float)(Stop.tv_usec - Start.tv_usec)/1000000;
  255. clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
  256. }
  257. /*}}}*/
  258. CircleBuf::~CircleBuf()
  259. {
  260. delete [] Buf;
  261. delete Hash;
  262. }
  263. // ServerState::ServerState - Constructor /*{{{*/
  264. // ---------------------------------------------------------------------
  265. /* */
  266. ServerState::ServerState(URI Srv,HttpMethod *Owner) : Owner(Owner),
  267. In(64*1024), Out(4*1024),
  268. ServerName(Srv)
  269. {
  270. Reset();
  271. }
  272. /*}}}*/
  273. // ServerState::Open - Open a connection to the server /*{{{*/
  274. // ---------------------------------------------------------------------
  275. /* This opens a connection to the server. */
  276. bool ServerState::Open()
  277. {
  278. // Use the already open connection if possible.
  279. if (ServerFd != -1)
  280. return true;
  281. Close();
  282. In.Reset();
  283. Out.Reset();
  284. Persistent = true;
  285. // Determine the proxy setting
  286. string SpecificProxy = _config->Find("Acquire::http::Proxy::" + ServerName.Host);
  287. if (!SpecificProxy.empty())
  288. {
  289. if (SpecificProxy == "DIRECT")
  290. Proxy = "";
  291. else
  292. Proxy = SpecificProxy;
  293. }
  294. else
  295. {
  296. string DefProxy = _config->Find("Acquire::http::Proxy");
  297. if (!DefProxy.empty())
  298. {
  299. Proxy = DefProxy;
  300. }
  301. else
  302. {
  303. char* result = getenv("http_proxy");
  304. Proxy = result ? result : "";
  305. }
  306. }
  307. // Parse no_proxy, a , separated list of domains
  308. if (getenv("no_proxy") != 0)
  309. {
  310. if (CheckDomainList(ServerName.Host,getenv("no_proxy")) == true)
  311. Proxy = "";
  312. }
  313. // Determine what host and port to use based on the proxy settings
  314. int Port = 0;
  315. string Host;
  316. if (Proxy.empty() == true || Proxy.Host.empty() == true)
  317. {
  318. if (ServerName.Port != 0)
  319. Port = ServerName.Port;
  320. Host = ServerName.Host;
  321. }
  322. else
  323. {
  324. if (Proxy.Port != 0)
  325. Port = Proxy.Port;
  326. Host = Proxy.Host;
  327. }
  328. // Connect to the remote server
  329. if (Connect(Host,Port,"http",80,ServerFd,TimeOut,Owner) == false)
  330. return false;
  331. return true;
  332. }
  333. /*}}}*/
  334. // ServerState::Close - Close a connection to the server /*{{{*/
  335. // ---------------------------------------------------------------------
  336. /* */
  337. bool ServerState::Close()
  338. {
  339. close(ServerFd);
  340. ServerFd = -1;
  341. return true;
  342. }
  343. /*}}}*/
  344. // ServerState::RunHeaders - Get the headers before the data /*{{{*/
  345. // ---------------------------------------------------------------------
  346. /* Returns 0 if things are OK, 1 if an IO error occurred and 2 if a header
  347. parse error occurred */
  348. ServerState::RunHeadersResult ServerState::RunHeaders()
  349. {
  350. State = Header;
  351. Owner->Status(_("Waiting for headers"));
  352. Major = 0;
  353. Minor = 0;
  354. Result = 0;
  355. Size = 0;
  356. StartPos = 0;
  357. Encoding = Closes;
  358. HaveContent = false;
  359. time(&Date);
  360. do
  361. {
  362. string Data;
  363. if (In.WriteTillEl(Data) == false)
  364. continue;
  365. if (Debug == true)
  366. clog << Data;
  367. for (string::const_iterator I = Data.begin(); I < Data.end(); ++I)
  368. {
  369. string::const_iterator J = I;
  370. for (; J != Data.end() && *J != '\n' && *J != '\r'; ++J);
  371. if (HeaderLine(string(I,J)) == false)
  372. return RUN_HEADERS_PARSE_ERROR;
  373. I = J;
  374. }
  375. // 100 Continue is a Nop...
  376. if (Result == 100)
  377. continue;
  378. // Tidy up the connection persistance state.
  379. if (Encoding == Closes && HaveContent == true)
  380. Persistent = false;
  381. return RUN_HEADERS_OK;
  382. }
  383. while (Owner->Go(false,this) == true);
  384. return RUN_HEADERS_IO_ERROR;
  385. }
  386. /*}}}*/
  387. // ServerState::RunData - Transfer the data from the socket /*{{{*/
  388. // ---------------------------------------------------------------------
  389. /* */
  390. bool ServerState::RunData()
  391. {
  392. State = Data;
  393. // Chunked transfer encoding is fun..
  394. if (Encoding == Chunked)
  395. {
  396. while (1)
  397. {
  398. // Grab the block size
  399. bool Last = true;
  400. string Data;
  401. In.Limit(-1);
  402. do
  403. {
  404. if (In.WriteTillEl(Data,true) == true)
  405. break;
  406. }
  407. while ((Last = Owner->Go(false,this)) == true);
  408. if (Last == false)
  409. return false;
  410. // See if we are done
  411. unsigned long long Len = strtoull(Data.c_str(),0,16);
  412. if (Len == 0)
  413. {
  414. In.Limit(-1);
  415. // We have to remove the entity trailer
  416. Last = true;
  417. do
  418. {
  419. if (In.WriteTillEl(Data,true) == true && Data.length() <= 2)
  420. break;
  421. }
  422. while ((Last = Owner->Go(false,this)) == true);
  423. if (Last == false)
  424. return false;
  425. return !_error->PendingError();
  426. }
  427. // Transfer the block
  428. In.Limit(Len);
  429. while (Owner->Go(true,this) == true)
  430. if (In.IsLimit() == true)
  431. break;
  432. // Error
  433. if (In.IsLimit() == false)
  434. return false;
  435. // The server sends an extra new line before the next block specifier..
  436. In.Limit(-1);
  437. Last = true;
  438. do
  439. {
  440. if (In.WriteTillEl(Data,true) == true)
  441. break;
  442. }
  443. while ((Last = Owner->Go(false,this)) == true);
  444. if (Last == false)
  445. return false;
  446. }
  447. }
  448. else
  449. {
  450. /* Closes encoding is used when the server did not specify a size, the
  451. loss of the connection means we are done */
  452. if (Encoding == Closes)
  453. In.Limit(-1);
  454. else
  455. In.Limit(Size - StartPos);
  456. // Just transfer the whole block.
  457. do
  458. {
  459. if (In.IsLimit() == false)
  460. continue;
  461. In.Limit(-1);
  462. return !_error->PendingError();
  463. }
  464. while (Owner->Go(true,this) == true);
  465. }
  466. return Owner->Flush(this) && !_error->PendingError();
  467. }
  468. /*}}}*/
  469. // ServerState::HeaderLine - Process a header line /*{{{*/
  470. // ---------------------------------------------------------------------
  471. /* */
  472. bool ServerState::HeaderLine(string Line)
  473. {
  474. if (Line.empty() == true)
  475. return true;
  476. string::size_type Pos = Line.find(' ');
  477. if (Pos == string::npos || Pos+1 > Line.length())
  478. {
  479. // Blah, some servers use "connection:closes", evil.
  480. Pos = Line.find(':');
  481. if (Pos == string::npos || Pos + 2 > Line.length())
  482. return _error->Error(_("Bad header line"));
  483. Pos++;
  484. }
  485. // Parse off any trailing spaces between the : and the next word.
  486. string::size_type Pos2 = Pos;
  487. while (Pos2 < Line.length() && isspace(Line[Pos2]) != 0)
  488. Pos2++;
  489. string Tag = string(Line,0,Pos);
  490. string Val = string(Line,Pos2);
  491. if (stringcasecmp(Tag.c_str(),Tag.c_str()+4,"HTTP") == 0)
  492. {
  493. // Evil servers return no version
  494. if (Line[4] == '/')
  495. {
  496. int const elements = sscanf(Line.c_str(),"HTTP/%3u.%3u %3u%359[^\n]",&Major,&Minor,&Result,Code);
  497. if (elements == 3)
  498. {
  499. Code[0] = '\0';
  500. if (Debug == true)
  501. clog << "HTTP server doesn't give Reason-Phrase for " << Result << std::endl;
  502. }
  503. else if (elements != 4)
  504. return _error->Error(_("The HTTP server sent an invalid reply header"));
  505. }
  506. else
  507. {
  508. Major = 0;
  509. Minor = 9;
  510. if (sscanf(Line.c_str(),"HTTP %3u%359[^\n]",&Result,Code) != 2)
  511. return _error->Error(_("The HTTP server sent an invalid reply header"));
  512. }
  513. /* Check the HTTP response header to get the default persistance
  514. state. */
  515. if (Major < 1)
  516. Persistent = false;
  517. else
  518. {
  519. if (Major == 1 && Minor == 0)
  520. Persistent = false;
  521. else
  522. Persistent = true;
  523. }
  524. return true;
  525. }
  526. if (stringcasecmp(Tag,"Content-Length:") == 0)
  527. {
  528. if (Encoding == Closes)
  529. Encoding = Stream;
  530. HaveContent = true;
  531. // The length is already set from the Content-Range header
  532. if (StartPos != 0)
  533. return true;
  534. Size = strtoull(Val.c_str(), NULL, 10);
  535. if (Size >= std::numeric_limits<unsigned long long>::max())
  536. return _error->Errno("HeaderLine", _("The HTTP server sent an invalid Content-Length header"));
  537. return true;
  538. }
  539. if (stringcasecmp(Tag,"Content-Type:") == 0)
  540. {
  541. HaveContent = true;
  542. return true;
  543. }
  544. if (stringcasecmp(Tag,"Content-Range:") == 0)
  545. {
  546. HaveContent = true;
  547. if (sscanf(Val.c_str(),"bytes %llu-%*u/%llu",&StartPos,&Size) != 2)
  548. return _error->Error(_("The HTTP server sent an invalid Content-Range header"));
  549. if ((unsigned long long)StartPos > Size)
  550. return _error->Error(_("This HTTP server has broken range support"));
  551. return true;
  552. }
  553. if (stringcasecmp(Tag,"Transfer-Encoding:") == 0)
  554. {
  555. HaveContent = true;
  556. if (stringcasecmp(Val,"chunked") == 0)
  557. Encoding = Chunked;
  558. return true;
  559. }
  560. if (stringcasecmp(Tag,"Connection:") == 0)
  561. {
  562. if (stringcasecmp(Val,"close") == 0)
  563. Persistent = false;
  564. if (stringcasecmp(Val,"keep-alive") == 0)
  565. Persistent = true;
  566. return true;
  567. }
  568. if (stringcasecmp(Tag,"Last-Modified:") == 0)
  569. {
  570. if (RFC1123StrToTime(Val.c_str(), Date) == false)
  571. return _error->Error(_("Unknown date format"));
  572. return true;
  573. }
  574. if (stringcasecmp(Tag,"Location:") == 0)
  575. {
  576. Location = Val;
  577. return true;
  578. }
  579. return true;
  580. }
  581. /*}}}*/
  582. // HttpMethod::SendReq - Send the HTTP request /*{{{*/
  583. // ---------------------------------------------------------------------
  584. /* This places the http request in the outbound buffer */
  585. void HttpMethod::SendReq(FetchItem *Itm,CircleBuf &Out)
  586. {
  587. URI Uri = Itm->Uri;
  588. // The HTTP server expects a hostname with a trailing :port
  589. char Buf[1000];
  590. string ProperHost;
  591. if (Uri.Host.find(':') != string::npos)
  592. ProperHost = '[' + Uri.Host + ']';
  593. else
  594. ProperHost = Uri.Host;
  595. if (Uri.Port != 0)
  596. {
  597. sprintf(Buf,":%u",Uri.Port);
  598. ProperHost += Buf;
  599. }
  600. // Just in case.
  601. if (Itm->Uri.length() >= sizeof(Buf))
  602. abort();
  603. /* Build the request. No keep-alive is included as it is the default
  604. in 1.1, can cause problems with proxies, and we are an HTTP/1.1
  605. client anyway.
  606. C.f. https://tools.ietf.org/wg/httpbis/trac/ticket/158 */
  607. // see LP bugs #1003633 and #1086997. The "+" is encoded as a workaround
  608. // for a amazon S3 bug
  609. sprintf(Buf,"GET %s HTTP/1.1\r\nHost: %s\r\n",
  610. QuoteString(Uri.Path,"+~ ").c_str(),ProperHost.c_str());
  611. // generate a cache control header (if needed)
  612. if (_config->FindB("Acquire::http::No-Cache",false) == true)
  613. {
  614. strcat(Buf,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
  615. }
  616. else
  617. {
  618. if (Itm->IndexFile == true)
  619. {
  620. sprintf(Buf+strlen(Buf),"Cache-Control: max-age=%u\r\n",
  621. _config->FindI("Acquire::http::Max-Age",0));
  622. }
  623. else
  624. {
  625. if (_config->FindB("Acquire::http::No-Store",false) == true)
  626. strcat(Buf,"Cache-Control: no-store\r\n");
  627. }
  628. }
  629. // If we ask for uncompressed files servers might respond with content-
  630. // negotation which lets us end up with compressed files we do not support,
  631. // see 657029, 657560 and co, so if we have no extension on the request
  632. // ask for text only. As a sidenote: If there is nothing to negotate servers
  633. // seem to be nice and ignore it.
  634. if (_config->FindB("Acquire::http::SendAccept", true) == true)
  635. {
  636. size_t const filepos = Itm->Uri.find_last_of('/');
  637. string const file = Itm->Uri.substr(filepos + 1);
  638. if (flExtension(file) == file)
  639. strcat(Buf,"Accept: text/*\r\n");
  640. }
  641. string Req = Buf;
  642. // Check for a partial file
  643. struct stat SBuf;
  644. if (stat(Itm->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
  645. {
  646. // In this case we send an if-range query with a range header
  647. sprintf(Buf,"Range: bytes=%lli-\r\nIf-Range: %s\r\n",(long long)SBuf.st_size - 1,
  648. TimeRFC1123(SBuf.st_mtime).c_str());
  649. Req += Buf;
  650. }
  651. else
  652. {
  653. if (Itm->LastModified != 0)
  654. {
  655. sprintf(Buf,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm->LastModified).c_str());
  656. Req += Buf;
  657. }
  658. }
  659. if (Proxy.User.empty() == false || Proxy.Password.empty() == false)
  660. Req += string("Proxy-Authorization: Basic ") +
  661. Base64Encode(Proxy.User + ":" + Proxy.Password) + "\r\n";
  662. maybe_add_auth (Uri, _config->FindFile("Dir::Etc::netrc"));
  663. if (Uri.User.empty() == false || Uri.Password.empty() == false)
  664. {
  665. Req += string("Authorization: Basic ") +
  666. Base64Encode(Uri.User + ":" + Uri.Password) + "\r\n";
  667. }
  668. Req += "User-Agent: " + _config->Find("Acquire::http::User-Agent",
  669. "Debian APT-HTTP/1.3 (" PACKAGE_VERSION ")") + "\r\n\r\n";
  670. if (Debug == true)
  671. cerr << Req << endl;
  672. Out.Read(Req);
  673. }
  674. /*}}}*/
  675. // HttpMethod::Go - Run a single loop /*{{{*/
  676. // ---------------------------------------------------------------------
  677. /* This runs the select loop over the server FDs, Output file FDs and
  678. stdin. */
  679. bool HttpMethod::Go(bool ToFile,ServerState *Srv)
  680. {
  681. // Server has closed the connection
  682. if (Srv->ServerFd == -1 && (Srv->In.WriteSpace() == false ||
  683. ToFile == false))
  684. return false;
  685. fd_set rfds,wfds;
  686. FD_ZERO(&rfds);
  687. FD_ZERO(&wfds);
  688. /* Add the server. We only send more requests if the connection will
  689. be persisting */
  690. if (Srv->Out.WriteSpace() == true && Srv->ServerFd != -1
  691. && Srv->Persistent == true)
  692. FD_SET(Srv->ServerFd,&wfds);
  693. if (Srv->In.ReadSpace() == true && Srv->ServerFd != -1)
  694. FD_SET(Srv->ServerFd,&rfds);
  695. // Add the file
  696. int FileFD = -1;
  697. if (File != 0)
  698. FileFD = File->Fd();
  699. if (Srv->In.WriteSpace() == true && ToFile == true && FileFD != -1)
  700. FD_SET(FileFD,&wfds);
  701. // Add stdin
  702. if (_config->FindB("Acquire::http::DependOnSTDIN", true) == true)
  703. FD_SET(STDIN_FILENO,&rfds);
  704. // Figure out the max fd
  705. int MaxFd = FileFD;
  706. if (MaxFd < Srv->ServerFd)
  707. MaxFd = Srv->ServerFd;
  708. // Select
  709. struct timeval tv;
  710. tv.tv_sec = TimeOut;
  711. tv.tv_usec = 0;
  712. int Res = 0;
  713. if ((Res = select(MaxFd+1,&rfds,&wfds,0,&tv)) < 0)
  714. {
  715. if (errno == EINTR)
  716. return true;
  717. return _error->Errno("select",_("Select failed"));
  718. }
  719. if (Res == 0)
  720. {
  721. _error->Error(_("Connection timed out"));
  722. return ServerDie(Srv);
  723. }
  724. // Handle server IO
  725. if (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&rfds))
  726. {
  727. errno = 0;
  728. if (Srv->In.Read(Srv->ServerFd) == false)
  729. return ServerDie(Srv);
  730. }
  731. if (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&wfds))
  732. {
  733. errno = 0;
  734. if (Srv->Out.Write(Srv->ServerFd) == false)
  735. return ServerDie(Srv);
  736. }
  737. // Send data to the file
  738. if (FileFD != -1 && FD_ISSET(FileFD,&wfds))
  739. {
  740. if (Srv->In.Write(FileFD) == false)
  741. return _error->Errno("write",_("Error writing to output file"));
  742. }
  743. // Handle commands from APT
  744. if (FD_ISSET(STDIN_FILENO,&rfds))
  745. {
  746. if (Run(true) != -1)
  747. exit(100);
  748. }
  749. return true;
  750. }
  751. /*}}}*/
  752. // HttpMethod::Flush - Dump the buffer into the file /*{{{*/
  753. // ---------------------------------------------------------------------
  754. /* This takes the current input buffer from the Server FD and writes it
  755. into the file */
  756. bool HttpMethod::Flush(ServerState *Srv)
  757. {
  758. if (File != 0)
  759. {
  760. // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
  761. // can't be set
  762. if (File->Name() != "/dev/null")
  763. SetNonBlock(File->Fd(),false);
  764. if (Srv->In.WriteSpace() == false)
  765. return true;
  766. while (Srv->In.WriteSpace() == true)
  767. {
  768. if (Srv->In.Write(File->Fd()) == false)
  769. return _error->Errno("write",_("Error writing to file"));
  770. if (Srv->In.IsLimit() == true)
  771. return true;
  772. }
  773. if (Srv->In.IsLimit() == true || Srv->Encoding == ServerState::Closes)
  774. return true;
  775. }
  776. return false;
  777. }
  778. /*}}}*/
  779. // HttpMethod::ServerDie - The server has closed the connection. /*{{{*/
  780. // ---------------------------------------------------------------------
  781. /* */
  782. bool HttpMethod::ServerDie(ServerState *Srv)
  783. {
  784. unsigned int LErrno = errno;
  785. // Dump the buffer to the file
  786. if (Srv->State == ServerState::Data)
  787. {
  788. // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
  789. // can't be set
  790. if (File->Name() != "/dev/null")
  791. SetNonBlock(File->Fd(),false);
  792. while (Srv->In.WriteSpace() == true)
  793. {
  794. if (Srv->In.Write(File->Fd()) == false)
  795. return _error->Errno("write",_("Error writing to the file"));
  796. // Done
  797. if (Srv->In.IsLimit() == true)
  798. return true;
  799. }
  800. }
  801. // See if this is because the server finished the data stream
  802. if (Srv->In.IsLimit() == false && Srv->State != ServerState::Header &&
  803. Srv->Encoding != ServerState::Closes)
  804. {
  805. Srv->Close();
  806. if (LErrno == 0)
  807. return _error->Error(_("Error reading from server. Remote end closed connection"));
  808. errno = LErrno;
  809. return _error->Errno("read",_("Error reading from server"));
  810. }
  811. else
  812. {
  813. Srv->In.Limit(-1);
  814. // Nothing left in the buffer
  815. if (Srv->In.WriteSpace() == false)
  816. return false;
  817. // We may have got multiple responses back in one packet..
  818. Srv->Close();
  819. return true;
  820. }
  821. return false;
  822. }
  823. /*}}}*/
  824. // HttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
  825. // ---------------------------------------------------------------------
  826. /* We look at the header data we got back from the server and decide what
  827. to do. Returns DealWithHeadersResult (see http.h for details).
  828. */
  829. HttpMethod::DealWithHeadersResult
  830. HttpMethod::DealWithHeaders(FetchResult &Res,ServerState *Srv)
  831. {
  832. // Not Modified
  833. if (Srv->Result == 304)
  834. {
  835. unlink(Queue->DestFile.c_str());
  836. Res.IMSHit = true;
  837. Res.LastModified = Queue->LastModified;
  838. return IMS_HIT;
  839. }
  840. /* Redirect
  841. *
  842. * Note that it is only OK for us to treat all redirection the same
  843. * because we *always* use GET, not other HTTP methods. There are
  844. * three redirection codes for which it is not appropriate that we
  845. * redirect. Pass on those codes so the error handling kicks in.
  846. */
  847. if (AllowRedirect
  848. && (Srv->Result > 300 && Srv->Result < 400)
  849. && (Srv->Result != 300 // Multiple Choices
  850. && Srv->Result != 304 // Not Modified
  851. && Srv->Result != 306)) // (Not part of HTTP/1.1, reserved)
  852. {
  853. if (Srv->Location.empty() == true);
  854. else if (Srv->Location[0] == '/' && Queue->Uri.empty() == false)
  855. {
  856. URI Uri = Queue->Uri;
  857. if (Uri.Host.empty() == false)
  858. NextURI = URI::SiteOnly(Uri);
  859. else
  860. NextURI.clear();
  861. NextURI.append(DeQuoteString(Srv->Location));
  862. return TRY_AGAIN_OR_REDIRECT;
  863. }
  864. else
  865. {
  866. NextURI = DeQuoteString(Srv->Location);
  867. URI tmpURI = NextURI;
  868. // Do not allow a redirection to switch protocol
  869. if (tmpURI.Access == "http")
  870. return TRY_AGAIN_OR_REDIRECT;
  871. }
  872. /* else pass through for error message */
  873. }
  874. /* We have a reply we dont handle. This should indicate a perm server
  875. failure */
  876. if (Srv->Result < 200 || Srv->Result >= 300)
  877. {
  878. char err[255];
  879. snprintf(err,sizeof(err)-1,"HttpError%i",Srv->Result);
  880. SetFailReason(err);
  881. _error->Error("%u %s",Srv->Result,Srv->Code);
  882. if (Srv->HaveContent == true)
  883. return ERROR_WITH_CONTENT_PAGE;
  884. return ERROR_UNRECOVERABLE;
  885. }
  886. // This is some sort of 2xx 'data follows' reply
  887. Res.LastModified = Srv->Date;
  888. Res.Size = Srv->Size;
  889. // Open the file
  890. delete File;
  891. File = new FileFd(Queue->DestFile,FileFd::WriteAny);
  892. if (_error->PendingError() == true)
  893. return ERROR_NOT_FROM_SERVER;
  894. FailFile = Queue->DestFile;
  895. FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
  896. FailFd = File->Fd();
  897. FailTime = Srv->Date;
  898. delete Srv->In.Hash;
  899. Srv->In.Hash = new Hashes;
  900. // Set the expected size and read file for the hashes
  901. if (Srv->StartPos >= 0)
  902. {
  903. Res.ResumePoint = Srv->StartPos;
  904. File->Truncate(Srv->StartPos);
  905. if (Srv->In.Hash->AddFD(*File,Srv->StartPos) == false)
  906. {
  907. _error->Errno("read",_("Problem hashing file"));
  908. return ERROR_NOT_FROM_SERVER;
  909. }
  910. }
  911. SetNonBlock(File->Fd(),true);
  912. return FILE_IS_OPEN;
  913. }
  914. /*}}}*/
  915. // HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
  916. // ---------------------------------------------------------------------
  917. /* This closes and timestamps the open file. This is neccessary to get
  918. resume behavoir on user abort */
  919. void HttpMethod::SigTerm(int)
  920. {
  921. if (FailFd == -1)
  922. _exit(100);
  923. close(FailFd);
  924. // Timestamp
  925. struct utimbuf UBuf;
  926. UBuf.actime = FailTime;
  927. UBuf.modtime = FailTime;
  928. utime(FailFile.c_str(),&UBuf);
  929. _exit(100);
  930. }
  931. /*}}}*/
  932. // HttpMethod::Fetch - Fetch an item /*{{{*/
  933. // ---------------------------------------------------------------------
  934. /* This adds an item to the pipeline. We keep the pipeline at a fixed
  935. depth. */
  936. bool HttpMethod::Fetch(FetchItem *)
  937. {
  938. if (Server == 0)
  939. return true;
  940. // Queue the requests
  941. int Depth = -1;
  942. for (FetchItem *I = Queue; I != 0 && Depth < (signed)PipelineDepth;
  943. I = I->Next, Depth++)
  944. {
  945. // If pipelining is disabled, we only queue 1 request
  946. if (Server->Pipeline == false && Depth >= 0)
  947. break;
  948. // Make sure we stick with the same server
  949. if (Server->Comp(I->Uri) == false)
  950. break;
  951. if (QueueBack == I)
  952. {
  953. QueueBack = I->Next;
  954. SendReq(I,Server->Out);
  955. continue;
  956. }
  957. }
  958. return true;
  959. };
  960. /*}}}*/
  961. // HttpMethod::Configuration - Handle a configuration message /*{{{*/
  962. // ---------------------------------------------------------------------
  963. /* We stash the desired pipeline depth */
  964. bool HttpMethod::Configuration(string Message)
  965. {
  966. if (pkgAcqMethod::Configuration(Message) == false)
  967. return false;
  968. AllowRedirect = _config->FindB("Acquire::http::AllowRedirect",true);
  969. TimeOut = _config->FindI("Acquire::http::Timeout",TimeOut);
  970. PipelineDepth = _config->FindI("Acquire::http::Pipeline-Depth",
  971. PipelineDepth);
  972. Debug = _config->FindB("Debug::Acquire::http",false);
  973. AutoDetectProxyCmd = _config->Find("Acquire::http::ProxyAutoDetect");
  974. // Get the proxy to use
  975. AutoDetectProxy();
  976. return true;
  977. }
  978. /*}}}*/
  979. // HttpMethod::Loop - Main loop /*{{{*/
  980. // ---------------------------------------------------------------------
  981. /* */
  982. int HttpMethod::Loop()
  983. {
  984. typedef vector<string> StringVector;
  985. typedef vector<string>::iterator StringVectorIterator;
  986. map<string, StringVector> Redirected;
  987. signal(SIGTERM,SigTerm);
  988. signal(SIGINT,SigTerm);
  989. Server = 0;
  990. int FailCounter = 0;
  991. while (1)
  992. {
  993. // We have no commands, wait for some to arrive
  994. if (Queue == 0)
  995. {
  996. if (WaitFd(STDIN_FILENO) == false)
  997. return 0;
  998. }
  999. /* Run messages, we can accept 0 (no message) if we didn't
  1000. do a WaitFd above.. Otherwise the FD is closed. */
  1001. int Result = Run(true);
  1002. if (Result != -1 && (Result != 0 || Queue == 0))
  1003. {
  1004. if(FailReason.empty() == false ||
  1005. _config->FindB("Acquire::http::DependOnSTDIN", true) == true)
  1006. return 100;
  1007. else
  1008. return 0;
  1009. }
  1010. if (Queue == 0)
  1011. continue;
  1012. // Connect to the server
  1013. if (Server == 0 || Server->Comp(Queue->Uri) == false)
  1014. {
  1015. delete Server;
  1016. Server = new ServerState(Queue->Uri,this);
  1017. }
  1018. /* If the server has explicitly said this is the last connection
  1019. then we pre-emptively shut down the pipeline and tear down
  1020. the connection. This will speed up HTTP/1.0 servers a tad
  1021. since we don't have to wait for the close sequence to
  1022. complete */
  1023. if (Server->Persistent == false)
  1024. Server->Close();
  1025. // Reset the pipeline
  1026. if (Server->ServerFd == -1)
  1027. QueueBack = Queue;
  1028. // Connnect to the host
  1029. if (Server->Open() == false)
  1030. {
  1031. Fail(true);
  1032. delete Server;
  1033. Server = 0;
  1034. continue;
  1035. }
  1036. // Fill the pipeline.
  1037. Fetch(0);
  1038. // Fetch the next URL header data from the server.
  1039. switch (Server->RunHeaders())
  1040. {
  1041. case ServerState::RUN_HEADERS_OK:
  1042. break;
  1043. // The header data is bad
  1044. case ServerState::RUN_HEADERS_PARSE_ERROR:
  1045. {
  1046. _error->Error(_("Bad header data"));
  1047. Fail(true);
  1048. RotateDNS();
  1049. continue;
  1050. }
  1051. // The server closed a connection during the header get..
  1052. default:
  1053. case ServerState::RUN_HEADERS_IO_ERROR:
  1054. {
  1055. FailCounter++;
  1056. _error->Discard();
  1057. Server->Close();
  1058. Server->Pipeline = false;
  1059. if (FailCounter >= 2)
  1060. {
  1061. Fail(_("Connection failed"),true);
  1062. FailCounter = 0;
  1063. }
  1064. RotateDNS();
  1065. continue;
  1066. }
  1067. };
  1068. // Decide what to do.
  1069. FetchResult Res;
  1070. Res.Filename = Queue->DestFile;
  1071. switch (DealWithHeaders(Res,Server))
  1072. {
  1073. // Ok, the file is Open
  1074. case FILE_IS_OPEN:
  1075. {
  1076. URIStart(Res);
  1077. // Run the data
  1078. bool Result = Server->RunData();
  1079. /* If the server is sending back sizeless responses then fill in
  1080. the size now */
  1081. if (Res.Size == 0)
  1082. Res.Size = File->Size();
  1083. // Close the file, destroy the FD object and timestamp it
  1084. FailFd = -1;
  1085. delete File;
  1086. File = 0;
  1087. // Timestamp
  1088. struct utimbuf UBuf;
  1089. time(&UBuf.actime);
  1090. UBuf.actime = Server->Date;
  1091. UBuf.modtime = Server->Date;
  1092. utime(Queue->DestFile.c_str(),&UBuf);
  1093. // Send status to APT
  1094. if (Result == true)
  1095. {
  1096. Res.TakeHashes(*Server->In.Hash);
  1097. URIDone(Res);
  1098. }
  1099. else
  1100. {
  1101. if (Server->ServerFd == -1)
  1102. {
  1103. FailCounter++;
  1104. _error->Discard();
  1105. Server->Close();
  1106. if (FailCounter >= 2)
  1107. {
  1108. Fail(_("Connection failed"),true);
  1109. FailCounter = 0;
  1110. }
  1111. QueueBack = Queue;
  1112. }
  1113. else
  1114. Fail(true);
  1115. }
  1116. break;
  1117. }
  1118. // IMS hit
  1119. case IMS_HIT:
  1120. {
  1121. URIDone(Res);
  1122. break;
  1123. }
  1124. // Hard server error, not found or something
  1125. case ERROR_UNRECOVERABLE:
  1126. {
  1127. Fail();
  1128. break;
  1129. }
  1130. // Hard internal error, kill the connection and fail
  1131. case ERROR_NOT_FROM_SERVER:
  1132. {
  1133. delete File;
  1134. File = 0;
  1135. Fail();
  1136. RotateDNS();
  1137. Server->Close();
  1138. break;
  1139. }
  1140. // We need to flush the data, the header is like a 404 w/ error text
  1141. case ERROR_WITH_CONTENT_PAGE:
  1142. {
  1143. Fail();
  1144. // Send to content to dev/null
  1145. File = new FileFd("/dev/null",FileFd::WriteExists);
  1146. Server->RunData();
  1147. delete File;
  1148. File = 0;
  1149. break;
  1150. }
  1151. // Try again with a new URL
  1152. case TRY_AGAIN_OR_REDIRECT:
  1153. {
  1154. // Clear rest of response if there is content
  1155. if (Server->HaveContent)
  1156. {
  1157. File = new FileFd("/dev/null",FileFd::WriteExists);
  1158. Server->RunData();
  1159. delete File;
  1160. File = 0;
  1161. }
  1162. /* Detect redirect loops. No more redirects are allowed
  1163. after the same URI is seen twice in a queue item. */
  1164. StringVector &R = Redirected[Queue->DestFile];
  1165. bool StopRedirects = false;
  1166. if (R.empty() == true)
  1167. R.push_back(Queue->Uri);
  1168. else if (R[0] == "STOP" || R.size() > 10)
  1169. StopRedirects = true;
  1170. else
  1171. {
  1172. for (StringVectorIterator I = R.begin(); I != R.end(); ++I)
  1173. if (Queue->Uri == *I)
  1174. {
  1175. R[0] = "STOP";
  1176. break;
  1177. }
  1178. R.push_back(Queue->Uri);
  1179. }
  1180. if (StopRedirects == false)
  1181. Redirect(NextURI);
  1182. else
  1183. Fail();
  1184. break;
  1185. }
  1186. default:
  1187. Fail(_("Internal error"));
  1188. break;
  1189. }
  1190. FailCounter = 0;
  1191. }
  1192. return 0;
  1193. }
  1194. /*}}}*/
  1195. // HttpMethod::AutoDetectProxy - auto detect proxy /*{{{*/
  1196. // ---------------------------------------------------------------------
  1197. /* */
  1198. bool HttpMethod::AutoDetectProxy()
  1199. {
  1200. if (AutoDetectProxyCmd.empty())
  1201. return true;
  1202. if (Debug)
  1203. clog << "Using auto proxy detect command: " << AutoDetectProxyCmd << endl;
  1204. int Pipes[2] = {-1,-1};
  1205. if (pipe(Pipes) != 0)
  1206. return _error->Errno("pipe", "Failed to create Pipe");
  1207. pid_t Process = ExecFork();
  1208. if (Process == 0)
  1209. {
  1210. close(Pipes[0]);
  1211. dup2(Pipes[1],STDOUT_FILENO);
  1212. SetCloseExec(STDOUT_FILENO,false);
  1213. const char *Args[2];
  1214. Args[0] = AutoDetectProxyCmd.c_str();
  1215. Args[1] = 0;
  1216. execv(Args[0],(char **)Args);
  1217. cerr << "Failed to exec method " << Args[0] << endl;
  1218. _exit(100);
  1219. }
  1220. char buf[512];
  1221. int InFd = Pipes[0];
  1222. close(Pipes[1]);
  1223. int res = read(InFd, buf, sizeof(buf));
  1224. ExecWait(Process, "ProxyAutoDetect", true);
  1225. if (res < 0)
  1226. return _error->Errno("read", "Failed to read");
  1227. if (res == 0)
  1228. return _error->Warning("ProxyAutoDetect returned no data");
  1229. // add trailing \0
  1230. buf[res] = 0;
  1231. if (Debug)
  1232. clog << "auto detect command returned: '" << buf << "'" << endl;
  1233. if (strstr(buf, "http://") == buf)
  1234. _config->Set("Acquire::http::proxy", _strstrip(buf));
  1235. return true;
  1236. }
  1237. /*}}}*/