http.cc 33 KB

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