http.cc 31 KB

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