http.cc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: http.cc,v 1.59 2004/05/08 19:42:35 mdz Exp $
  4. /* ######################################################################
  5. HTTP Acquire Method - This is the HTTP aquire method for APT.
  6. It uses HTTP/1.1 and many of the fancy options there-in, such as
  7. pipelining, range, if-range and so on.
  8. It is based on a doubly buffered select loop. A groupe of requests are
  9. fed into a single output buffer that is constantly fed out the
  10. socket. This provides ideal pipelining as in many cases all of the
  11. requests will fit into a single packet. The input socket is buffered
  12. the same way and fed into the fd for the file (may be a pipe in future).
  13. This double buffering provides fairly substantial transfer rates,
  14. compared to wget the http method is about 4% faster. Most importantly,
  15. when HTTP is compared with FTP as a protocol the speed difference is
  16. huge. In tests over the internet from two sites to llug (via ATM) this
  17. program got 230k/s sustained http transfer rates. FTP on the other
  18. hand topped out at 170k/s. That combined with the time to setup the
  19. FTP connection makes HTTP a vastly superior protocol.
  20. ##################################################################### */
  21. /*}}}*/
  22. // Include Files /*{{{*/
  23. #include <config.h>
  24. #include <apt-pkg/fileutl.h>
  25. #include <apt-pkg/acquire-method.h>
  26. #include <apt-pkg/configuration.h>
  27. #include <apt-pkg/error.h>
  28. #include <apt-pkg/hashes.h>
  29. #include <apt-pkg/netrc.h>
  30. #include <sys/stat.h>
  31. #include <sys/time.h>
  32. #include <utime.h>
  33. #include <unistd.h>
  34. #include <signal.h>
  35. #include <stdio.h>
  36. #include <errno.h>
  37. #include <string.h>
  38. #include <climits>
  39. #include <iostream>
  40. #include <map>
  41. // Internet stuff
  42. #include <netdb.h>
  43. #include "config.h"
  44. #include "connect.h"
  45. #include "rfc2553emu.h"
  46. #include "http.h"
  47. #include <apti18n.h>
  48. /*}}}*/
  49. using namespace std;
  50. unsigned long long CircleBuf::BwReadLimit=0;
  51. unsigned long 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 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 long long)-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. while (1)
  88. {
  89. // Woops, buffer is full
  90. if (InP - OutP == Size)
  91. return true;
  92. // what's left to read in this tick
  93. unsigned long long const BwReadMax = CircleBuf::BwReadLimit/BW_HZ;
  94. if(CircleBuf::BwReadLimit) {
  95. struct timeval now;
  96. gettimeofday(&now,0);
  97. unsigned long long d = (now.tv_sec-CircleBuf::BwReadTick.tv_sec)*1000000 +
  98. now.tv_usec-CircleBuf::BwReadTick.tv_usec;
  99. if(d > 1000000/BW_HZ) {
  100. CircleBuf::BwReadTick = now;
  101. CircleBuf::BwTickReadData = 0;
  102. }
  103. if(CircleBuf::BwTickReadData >= BwReadMax) {
  104. usleep(1000000/BW_HZ);
  105. return true;
  106. }
  107. }
  108. // Write the buffer segment
  109. ssize_t Res;
  110. if(CircleBuf::BwReadLimit) {
  111. Res = read(Fd,Buf + (InP%Size),
  112. BwReadMax > LeftRead() ? LeftRead() : BwReadMax);
  113. } else
  114. Res = read(Fd,Buf + (InP%Size),LeftRead());
  115. if(Res > 0 && BwReadLimit > 0)
  116. CircleBuf::BwTickReadData += Res;
  117. if (Res == 0)
  118. return false;
  119. if (Res < 0)
  120. {
  121. if (errno == EAGAIN)
  122. return true;
  123. return false;
  124. }
  125. if (InP == 0)
  126. gettimeofday(&Start,0);
  127. InP += Res;
  128. }
  129. }
  130. /*}}}*/
  131. // CircleBuf::Read - Put the string into the buffer /*{{{*/
  132. // ---------------------------------------------------------------------
  133. /* This will hold the string in and fill the buffer with it as it empties */
  134. bool CircleBuf::Read(string Data)
  135. {
  136. OutQueue += Data;
  137. FillOut();
  138. return true;
  139. }
  140. /*}}}*/
  141. // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
  142. // ---------------------------------------------------------------------
  143. /* */
  144. void CircleBuf::FillOut()
  145. {
  146. if (OutQueue.empty() == true)
  147. return;
  148. while (1)
  149. {
  150. // Woops, buffer is full
  151. if (InP - OutP == Size)
  152. return;
  153. // Write the buffer segment
  154. unsigned long long Sz = LeftRead();
  155. if (OutQueue.length() - StrPos < Sz)
  156. Sz = OutQueue.length() - StrPos;
  157. memcpy(Buf + (InP%Size),OutQueue.c_str() + StrPos,Sz);
  158. // Advance
  159. StrPos += Sz;
  160. InP += Sz;
  161. if (OutQueue.length() == StrPos)
  162. {
  163. StrPos = 0;
  164. OutQueue = "";
  165. return;
  166. }
  167. }
  168. }
  169. /*}}}*/
  170. // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
  171. // ---------------------------------------------------------------------
  172. /* This empties the buffer into the FD. */
  173. bool CircleBuf::Write(int Fd)
  174. {
  175. while (1)
  176. {
  177. FillOut();
  178. // Woops, buffer is empty
  179. if (OutP == InP)
  180. return true;
  181. if (OutP == MaxGet)
  182. return true;
  183. // Write the buffer segment
  184. ssize_t Res;
  185. Res = write(Fd,Buf + (OutP%Size),LeftWrite());
  186. if (Res == 0)
  187. return false;
  188. if (Res < 0)
  189. {
  190. if (errno == EAGAIN)
  191. return true;
  192. return false;
  193. }
  194. if (Hash != 0)
  195. Hash->Add(Buf + (OutP%Size),Res);
  196. OutP += Res;
  197. }
  198. }
  199. /*}}}*/
  200. // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
  201. // ---------------------------------------------------------------------
  202. /* This copies till the first empty line */
  203. bool CircleBuf::WriteTillEl(string &Data,bool Single)
  204. {
  205. // We cheat and assume it is unneeded to have more than one buffer load
  206. for (unsigned long long I = OutP; I < InP; I++)
  207. {
  208. if (Buf[I%Size] != '\n')
  209. continue;
  210. ++I;
  211. if (Single == false)
  212. {
  213. if (I < InP && Buf[I%Size] == '\r')
  214. ++I;
  215. if (I >= InP || Buf[I%Size] != '\n')
  216. continue;
  217. ++I;
  218. }
  219. Data = "";
  220. while (OutP < I)
  221. {
  222. unsigned long long Sz = LeftWrite();
  223. if (Sz == 0)
  224. return false;
  225. if (I - OutP < Sz)
  226. Sz = I - OutP;
  227. Data += string((char *)(Buf + (OutP%Size)),Sz);
  228. OutP += Sz;
  229. }
  230. return true;
  231. }
  232. return false;
  233. }
  234. /*}}}*/
  235. // CircleBuf::Stats - Print out stats information /*{{{*/
  236. // ---------------------------------------------------------------------
  237. /* */
  238. void CircleBuf::Stats()
  239. {
  240. if (InP == 0)
  241. return;
  242. struct timeval Stop;
  243. gettimeofday(&Stop,0);
  244. /* float Diff = Stop.tv_sec - Start.tv_sec +
  245. (float)(Stop.tv_usec - Start.tv_usec)/1000000;
  246. clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
  247. }
  248. /*}}}*/
  249. CircleBuf::~CircleBuf()
  250. {
  251. delete [] Buf;
  252. delete Hash;
  253. }
  254. // HttpServerState::HttpServerState - Constructor /*{{{*/
  255. HttpServerState::HttpServerState(URI Srv,HttpMethod *Owner) : ServerState(Srv, Owner), In(64*1024), Out(4*1024)
  256. {
  257. TimeOut = _config->FindI("Acquire::http::Timeout",TimeOut);
  258. Reset();
  259. }
  260. /*}}}*/
  261. // HttpServerState::Open - Open a connection to the server /*{{{*/
  262. // ---------------------------------------------------------------------
  263. /* This opens a connection to the server. */
  264. bool HttpServerState::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. string SpecificProxy = _config->Find("Acquire::http::Proxy::" + ServerName.Host);
  275. if (!SpecificProxy.empty())
  276. {
  277. if (SpecificProxy == "DIRECT")
  278. Proxy = "";
  279. else
  280. Proxy = SpecificProxy;
  281. }
  282. else
  283. {
  284. string DefProxy = _config->Find("Acquire::http::Proxy");
  285. if (!DefProxy.empty())
  286. {
  287. Proxy = DefProxy;
  288. }
  289. else
  290. {
  291. char* result = getenv("http_proxy");
  292. Proxy = result ? result : "";
  293. }
  294. }
  295. // Parse no_proxy, a , separated list of domains
  296. if (getenv("no_proxy") != 0)
  297. {
  298. if (CheckDomainList(ServerName.Host,getenv("no_proxy")) == true)
  299. Proxy = "";
  300. }
  301. // Determine what host and port to use based on the proxy settings
  302. int Port = 0;
  303. string Host;
  304. if (Proxy.empty() == true || Proxy.Host.empty() == true)
  305. {
  306. if (ServerName.Port != 0)
  307. Port = ServerName.Port;
  308. Host = ServerName.Host;
  309. }
  310. else
  311. {
  312. if (Proxy.Port != 0)
  313. Port = Proxy.Port;
  314. Host = Proxy.Host;
  315. }
  316. // Connect to the remote server
  317. if (Connect(Host,Port,"http",80,ServerFd,TimeOut,Owner) == false)
  318. return false;
  319. return true;
  320. }
  321. /*}}}*/
  322. // HttpServerState::Close - Close a connection to the server /*{{{*/
  323. // ---------------------------------------------------------------------
  324. /* */
  325. bool HttpServerState::Close()
  326. {
  327. close(ServerFd);
  328. ServerFd = -1;
  329. return true;
  330. }
  331. /*}}}*/
  332. // HttpServerState::RunData - Transfer the data from the socket /*{{{*/
  333. bool HttpServerState::RunData(FileFd * const File)
  334. {
  335. State = Data;
  336. // Chunked transfer encoding is fun..
  337. if (Encoding == Chunked)
  338. {
  339. while (1)
  340. {
  341. // Grab the block size
  342. bool Last = true;
  343. string Data;
  344. In.Limit(-1);
  345. do
  346. {
  347. if (In.WriteTillEl(Data,true) == true)
  348. break;
  349. }
  350. while ((Last = Go(false, File)) == true);
  351. if (Last == false)
  352. return false;
  353. // See if we are done
  354. unsigned long long Len = strtoull(Data.c_str(),0,16);
  355. if (Len == 0)
  356. {
  357. In.Limit(-1);
  358. // We have to remove the entity trailer
  359. Last = true;
  360. do
  361. {
  362. if (In.WriteTillEl(Data,true) == true && Data.length() <= 2)
  363. break;
  364. }
  365. while ((Last = Go(false, File)) == true);
  366. if (Last == false)
  367. return false;
  368. return !_error->PendingError();
  369. }
  370. // Transfer the block
  371. In.Limit(Len);
  372. while (Go(true, File) == true)
  373. if (In.IsLimit() == true)
  374. break;
  375. // Error
  376. if (In.IsLimit() == false)
  377. return false;
  378. // The server sends an extra new line before the next block specifier..
  379. In.Limit(-1);
  380. Last = true;
  381. do
  382. {
  383. if (In.WriteTillEl(Data,true) == true)
  384. break;
  385. }
  386. while ((Last = Go(false, File)) == true);
  387. if (Last == false)
  388. return false;
  389. }
  390. }
  391. else
  392. {
  393. /* Closes encoding is used when the server did not specify a size, the
  394. loss of the connection means we are done */
  395. if (Encoding == Closes)
  396. In.Limit(-1);
  397. else
  398. In.Limit(Size - StartPos);
  399. // Just transfer the whole block.
  400. do
  401. {
  402. if (In.IsLimit() == false)
  403. continue;
  404. In.Limit(-1);
  405. return !_error->PendingError();
  406. }
  407. while (Go(true, File) == true);
  408. }
  409. return Owner->Flush() && !_error->PendingError();
  410. }
  411. /*}}}*/
  412. bool HttpServerState::ReadHeaderLines(std::string &Data) /*{{{*/
  413. {
  414. return In.WriteTillEl(Data);
  415. }
  416. /*}}}*/
  417. bool HttpServerState::LoadNextResponse(bool const ToFile, FileFd * const File)/*{{{*/
  418. {
  419. return Go(ToFile, File);
  420. }
  421. /*}}}*/
  422. bool HttpServerState::WriteResponse(const std::string &Data) /*{{{*/
  423. {
  424. return Out.Read(Data);
  425. }
  426. /*}}}*/
  427. bool HttpServerState::IsOpen() /*{{{*/
  428. {
  429. return (ServerFd != -1);
  430. }
  431. /*}}}*/
  432. bool HttpServerState::InitHashes(FileFd &File) /*{{{*/
  433. {
  434. delete In.Hash;
  435. In.Hash = new Hashes;
  436. // Set the expected size and read file for the hashes
  437. if (StartPos >= 0)
  438. {
  439. File.Truncate(StartPos);
  440. return In.Hash->AddFD(File, StartPos);
  441. }
  442. return true;
  443. }
  444. /*}}}*/
  445. Hashes * HttpServerState::GetHashes() /*{{{*/
  446. {
  447. return In.Hash;
  448. }
  449. /*}}}*/
  450. // HttpServerState::Die - The server has closed the connection. /*{{{*/
  451. bool HttpServerState::Die(FileFd &File)
  452. {
  453. unsigned int LErrno = errno;
  454. // Dump the buffer to the file
  455. if (State == ServerState::Data)
  456. {
  457. // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
  458. // can't be set
  459. if (File.Name() != "/dev/null")
  460. SetNonBlock(File.Fd(),false);
  461. while (In.WriteSpace() == true)
  462. {
  463. if (In.Write(File.Fd()) == false)
  464. return _error->Errno("write",_("Error writing to the file"));
  465. // Done
  466. if (In.IsLimit() == true)
  467. return true;
  468. }
  469. }
  470. // See if this is because the server finished the data stream
  471. if (In.IsLimit() == false && State != HttpServerState::Header &&
  472. Encoding != HttpServerState::Closes)
  473. {
  474. Close();
  475. if (LErrno == 0)
  476. return _error->Error(_("Error reading from server. Remote end closed connection"));
  477. errno = LErrno;
  478. return _error->Errno("read",_("Error reading from server"));
  479. }
  480. else
  481. {
  482. In.Limit(-1);
  483. // Nothing left in the buffer
  484. if (In.WriteSpace() == false)
  485. return false;
  486. // We may have got multiple responses back in one packet..
  487. Close();
  488. return true;
  489. }
  490. return false;
  491. }
  492. /*}}}*/
  493. // HttpServerState::Flush - Dump the buffer into the file /*{{{*/
  494. // ---------------------------------------------------------------------
  495. /* This takes the current input buffer from the Server FD and writes it
  496. into the file */
  497. bool HttpServerState::Flush(FileFd * const File)
  498. {
  499. if (File != NULL)
  500. {
  501. // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
  502. // can't be set
  503. if (File->Name() != "/dev/null")
  504. SetNonBlock(File->Fd(),false);
  505. if (In.WriteSpace() == false)
  506. return true;
  507. while (In.WriteSpace() == true)
  508. {
  509. if (In.Write(File->Fd()) == false)
  510. return _error->Errno("write",_("Error writing to file"));
  511. if (In.IsLimit() == true)
  512. return true;
  513. }
  514. if (In.IsLimit() == true || Encoding == ServerState::Closes)
  515. return true;
  516. }
  517. return false;
  518. }
  519. /*}}}*/
  520. // HttpServerState::Go - Run a single loop /*{{{*/
  521. // ---------------------------------------------------------------------
  522. /* This runs the select loop over the server FDs, Output file FDs and
  523. stdin. */
  524. bool HttpServerState::Go(bool ToFile, FileFd * const File)
  525. {
  526. // Server has closed the connection
  527. if (ServerFd == -1 && (In.WriteSpace() == false ||
  528. ToFile == false))
  529. return false;
  530. fd_set rfds,wfds;
  531. FD_ZERO(&rfds);
  532. FD_ZERO(&wfds);
  533. /* Add the server. We only send more requests if the connection will
  534. be persisting */
  535. if (Out.WriteSpace() == true && ServerFd != -1
  536. && Persistent == true)
  537. FD_SET(ServerFd,&wfds);
  538. if (In.ReadSpace() == true && ServerFd != -1)
  539. FD_SET(ServerFd,&rfds);
  540. // Add the file
  541. int FileFD = -1;
  542. if (File != NULL)
  543. FileFD = File->Fd();
  544. if (In.WriteSpace() == true && ToFile == true && FileFD != -1)
  545. FD_SET(FileFD,&wfds);
  546. // Add stdin
  547. if (_config->FindB("Acquire::http::DependOnSTDIN", true) == true)
  548. FD_SET(STDIN_FILENO,&rfds);
  549. // Figure out the max fd
  550. int MaxFd = FileFD;
  551. if (MaxFd < ServerFd)
  552. MaxFd = ServerFd;
  553. // Select
  554. struct timeval tv;
  555. tv.tv_sec = TimeOut;
  556. tv.tv_usec = 0;
  557. int Res = 0;
  558. if ((Res = select(MaxFd+1,&rfds,&wfds,0,&tv)) < 0)
  559. {
  560. if (errno == EINTR)
  561. return true;
  562. return _error->Errno("select",_("Select failed"));
  563. }
  564. if (Res == 0)
  565. {
  566. _error->Error(_("Connection timed out"));
  567. return Die(*File);
  568. }
  569. // Handle server IO
  570. if (ServerFd != -1 && FD_ISSET(ServerFd,&rfds))
  571. {
  572. errno = 0;
  573. if (In.Read(ServerFd) == false)
  574. return Die(*File);
  575. }
  576. if (ServerFd != -1 && FD_ISSET(ServerFd,&wfds))
  577. {
  578. errno = 0;
  579. if (Out.Write(ServerFd) == false)
  580. return Die(*File);
  581. }
  582. // Send data to the file
  583. if (FileFD != -1 && FD_ISSET(FileFD,&wfds))
  584. {
  585. if (In.Write(FileFD) == false)
  586. return _error->Errno("write",_("Error writing to output file"));
  587. }
  588. // Handle commands from APT
  589. if (FD_ISSET(STDIN_FILENO,&rfds))
  590. {
  591. if (Owner->Run(true) != -1)
  592. exit(100);
  593. }
  594. return true;
  595. }
  596. /*}}}*/
  597. // HttpMethod::SendReq - Send the HTTP request /*{{{*/
  598. // ---------------------------------------------------------------------
  599. /* This places the http request in the outbound buffer */
  600. void HttpMethod::SendReq(FetchItem *Itm)
  601. {
  602. URI Uri = Itm->Uri;
  603. // The HTTP server expects a hostname with a trailing :port
  604. char Buf[1000];
  605. string ProperHost;
  606. if (Uri.Host.find(':') != string::npos)
  607. ProperHost = '[' + Uri.Host + ']';
  608. else
  609. ProperHost = Uri.Host;
  610. if (Uri.Port != 0)
  611. {
  612. sprintf(Buf,":%u",Uri.Port);
  613. ProperHost += Buf;
  614. }
  615. // Just in case.
  616. if (Itm->Uri.length() >= sizeof(Buf))
  617. abort();
  618. /* RFC 2616 §5.1.2 requires absolute URIs for requests to proxies,
  619. but while its a must for all servers to accept absolute URIs,
  620. it is assumed clients will sent an absolute path for non-proxies */
  621. std::string requesturi;
  622. if (Server->Proxy.empty() == true || Server->Proxy.Host.empty())
  623. requesturi = Uri.Path;
  624. else
  625. requesturi = Itm->Uri;
  626. // The "+" is encoded as a workaround for a amazon S3 bug
  627. // see LP bugs #1003633 and #1086997.
  628. requesturi = QuoteString(requesturi, "+~ ");
  629. /* Build the request. No keep-alive is included as it is the default
  630. in 1.1, can cause problems with proxies, and we are an HTTP/1.1
  631. client anyway.
  632. C.f. https://tools.ietf.org/wg/httpbis/trac/ticket/158 */
  633. sprintf(Buf,"GET %s HTTP/1.1\r\nHost: %s\r\n",
  634. requesturi.c_str(),ProperHost.c_str());
  635. // generate a cache control header (if needed)
  636. if (_config->FindB("Acquire::http::No-Cache",false) == true)
  637. {
  638. strcat(Buf,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
  639. }
  640. else
  641. {
  642. if (Itm->IndexFile == true)
  643. {
  644. sprintf(Buf+strlen(Buf),"Cache-Control: max-age=%u\r\n",
  645. _config->FindI("Acquire::http::Max-Age",0));
  646. }
  647. else
  648. {
  649. if (_config->FindB("Acquire::http::No-Store",false) == true)
  650. strcat(Buf,"Cache-Control: no-store\r\n");
  651. }
  652. }
  653. // If we ask for uncompressed files servers might respond with content-
  654. // negotation which lets us end up with compressed files we do not support,
  655. // see 657029, 657560 and co, so if we have no extension on the request
  656. // ask for text only. As a sidenote: If there is nothing to negotate servers
  657. // seem to be nice and ignore it.
  658. if (_config->FindB("Acquire::http::SendAccept", true) == true)
  659. {
  660. size_t const filepos = Itm->Uri.find_last_of('/');
  661. string const file = Itm->Uri.substr(filepos + 1);
  662. if (flExtension(file) == file)
  663. strcat(Buf,"Accept: text/*\r\n");
  664. }
  665. string Req = Buf;
  666. // Check for a partial file
  667. struct stat SBuf;
  668. if (stat(Itm->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
  669. {
  670. // In this case we send an if-range query with a range header
  671. sprintf(Buf,"Range: bytes=%lli-\r\nIf-Range: %s\r\n",(long long)SBuf.st_size,
  672. TimeRFC1123(SBuf.st_mtime).c_str());
  673. Req += Buf;
  674. }
  675. else
  676. {
  677. if (Itm->LastModified != 0)
  678. {
  679. sprintf(Buf,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm->LastModified).c_str());
  680. Req += Buf;
  681. }
  682. }
  683. if (Server->Proxy.User.empty() == false || Server->Proxy.Password.empty() == false)
  684. Req += string("Proxy-Authorization: Basic ") +
  685. Base64Encode(Server->Proxy.User + ":" + Server->Proxy.Password) + "\r\n";
  686. maybe_add_auth (Uri, _config->FindFile("Dir::Etc::netrc"));
  687. if (Uri.User.empty() == false || Uri.Password.empty() == false)
  688. {
  689. Req += string("Authorization: Basic ") +
  690. Base64Encode(Uri.User + ":" + Uri.Password) + "\r\n";
  691. }
  692. Req += "User-Agent: " + _config->Find("Acquire::http::User-Agent",
  693. "Debian APT-HTTP/1.3 (" PACKAGE_VERSION ")") + "\r\n\r\n";
  694. if (Debug == true)
  695. cerr << Req << endl;
  696. Server->WriteResponse(Req);
  697. }
  698. /*}}}*/
  699. // HttpMethod::Configuration - Handle a configuration message /*{{{*/
  700. // ---------------------------------------------------------------------
  701. /* We stash the desired pipeline depth */
  702. bool HttpMethod::Configuration(string Message)
  703. {
  704. if (ServerMethod::Configuration(Message) == false)
  705. return false;
  706. AllowRedirect = _config->FindB("Acquire::http::AllowRedirect",true);
  707. PipelineDepth = _config->FindI("Acquire::http::Pipeline-Depth",
  708. PipelineDepth);
  709. Debug = _config->FindB("Debug::Acquire::http",false);
  710. // Get the proxy to use
  711. AutoDetectProxy();
  712. return true;
  713. }
  714. /*}}}*/
  715. // HttpMethod::AutoDetectProxy - auto detect proxy /*{{{*/
  716. // ---------------------------------------------------------------------
  717. /* */
  718. bool HttpMethod::AutoDetectProxy()
  719. {
  720. // option is "Acquire::http::Proxy-Auto-Detect" but we allow the old
  721. // name without the dash ("-")
  722. AutoDetectProxyCmd = _config->Find("Acquire::http::Proxy-Auto-Detect",
  723. _config->Find("Acquire::http::ProxyAutoDetect"));
  724. if (AutoDetectProxyCmd.empty())
  725. return true;
  726. if (Debug)
  727. clog << "Using auto proxy detect command: " << AutoDetectProxyCmd << endl;
  728. int Pipes[2] = {-1,-1};
  729. if (pipe(Pipes) != 0)
  730. return _error->Errno("pipe", "Failed to create Pipe");
  731. pid_t Process = ExecFork();
  732. if (Process == 0)
  733. {
  734. close(Pipes[0]);
  735. dup2(Pipes[1],STDOUT_FILENO);
  736. SetCloseExec(STDOUT_FILENO,false);
  737. const char *Args[2];
  738. Args[0] = AutoDetectProxyCmd.c_str();
  739. Args[1] = 0;
  740. execv(Args[0],(char **)Args);
  741. cerr << "Failed to exec method " << Args[0] << endl;
  742. _exit(100);
  743. }
  744. char buf[512];
  745. int InFd = Pipes[0];
  746. close(Pipes[1]);
  747. int res = read(InFd, buf, sizeof(buf)-1);
  748. ExecWait(Process, "ProxyAutoDetect", true);
  749. if (res < 0)
  750. return _error->Errno("read", "Failed to read");
  751. if (res == 0)
  752. return _error->Warning("ProxyAutoDetect returned no data");
  753. // add trailing \0
  754. buf[res] = 0;
  755. if (Debug)
  756. clog << "auto detect command returned: '" << buf << "'" << endl;
  757. if (strstr(buf, "http://") == buf)
  758. _config->Set("Acquire::http::proxy", _strstrip(buf));
  759. return true;
  760. }
  761. /*}}}*/
  762. ServerState * HttpMethod::CreateServerState(URI uri) /*{{{*/
  763. {
  764. return new HttpServerState(uri, this);
  765. }
  766. /*}}}*/
  767. void HttpMethod::RotateDNS() /*{{{*/
  768. {
  769. ::RotateDNS();
  770. }
  771. /*}}}*/