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