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