http.cc 35 KB

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