http.cc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  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. unsigned long 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 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. ssize_t 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 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. ssize_t 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 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 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. CircleBuf::~CircleBuf()
  251. {
  252. delete [] Buf;
  253. delete Hash;
  254. }
  255. // HttpServerState::HttpServerState - Constructor /*{{{*/
  256. HttpServerState::HttpServerState(URI Srv,HttpMethod *Owner) : ServerState(Srv, Owner), In(64*1024), Out(4*1024)
  257. {
  258. TimeOut = _config->FindI("Acquire::http::Timeout",TimeOut);
  259. Reset();
  260. }
  261. /*}}}*/
  262. // HttpServerState::Open - Open a connection to the server /*{{{*/
  263. // ---------------------------------------------------------------------
  264. /* This opens a connection to the server. */
  265. bool HttpServerState::Open()
  266. {
  267. // Use the already open connection if possible.
  268. if (ServerFd != -1)
  269. return true;
  270. Close();
  271. In.Reset();
  272. Out.Reset();
  273. Persistent = true;
  274. // Determine the proxy setting
  275. string SpecificProxy = _config->Find("Acquire::http::Proxy::" + ServerName.Host);
  276. if (!SpecificProxy.empty())
  277. {
  278. if (SpecificProxy == "DIRECT")
  279. Proxy = "";
  280. else
  281. Proxy = SpecificProxy;
  282. }
  283. else
  284. {
  285. string DefProxy = _config->Find("Acquire::http::Proxy");
  286. if (!DefProxy.empty())
  287. {
  288. Proxy = DefProxy;
  289. }
  290. else
  291. {
  292. char* result = getenv("http_proxy");
  293. Proxy = result ? result : "";
  294. }
  295. }
  296. // Parse no_proxy, a , separated list of domains
  297. if (getenv("no_proxy") != 0)
  298. {
  299. if (CheckDomainList(ServerName.Host,getenv("no_proxy")) == true)
  300. Proxy = "";
  301. }
  302. // Determine what host and port to use based on the proxy settings
  303. int Port = 0;
  304. string Host;
  305. if (Proxy.empty() == true || Proxy.Host.empty() == true)
  306. {
  307. if (ServerName.Port != 0)
  308. Port = ServerName.Port;
  309. Host = ServerName.Host;
  310. }
  311. else
  312. {
  313. if (Proxy.Port != 0)
  314. Port = Proxy.Port;
  315. Host = Proxy.Host;
  316. }
  317. // Connect to the remote server
  318. if (Connect(Host,Port,"http",80,ServerFd,TimeOut,Owner) == false)
  319. return false;
  320. return true;
  321. }
  322. /*}}}*/
  323. // HttpServerState::Close - Close a connection to the server /*{{{*/
  324. // ---------------------------------------------------------------------
  325. /* */
  326. bool HttpServerState::Close()
  327. {
  328. close(ServerFd);
  329. ServerFd = -1;
  330. return true;
  331. }
  332. /*}}}*/
  333. // HttpServerState::RunData - Transfer the data from the socket /*{{{*/
  334. bool HttpServerState::RunData(FileFd * const File)
  335. {
  336. State = Data;
  337. // Chunked transfer encoding is fun..
  338. if (Encoding == Chunked)
  339. {
  340. while (1)
  341. {
  342. // Grab the block size
  343. bool Last = true;
  344. string Data;
  345. In.Limit(-1);
  346. do
  347. {
  348. if (In.WriteTillEl(Data,true) == true)
  349. break;
  350. }
  351. while ((Last = Go(false, File)) == true);
  352. if (Last == false)
  353. return false;
  354. // See if we are done
  355. unsigned long long Len = strtoull(Data.c_str(),0,16);
  356. if (Len == 0)
  357. {
  358. In.Limit(-1);
  359. // We have to remove the entity trailer
  360. Last = true;
  361. do
  362. {
  363. if (In.WriteTillEl(Data,true) == true && Data.length() <= 2)
  364. break;
  365. }
  366. while ((Last = Go(false, File)) == true);
  367. if (Last == false)
  368. return false;
  369. return !_error->PendingError();
  370. }
  371. // Transfer the block
  372. In.Limit(Len);
  373. while (Go(true, File) == true)
  374. if (In.IsLimit() == true)
  375. break;
  376. // Error
  377. if (In.IsLimit() == false)
  378. return false;
  379. // The server sends an extra new line before the next block specifier..
  380. In.Limit(-1);
  381. Last = true;
  382. do
  383. {
  384. if (In.WriteTillEl(Data,true) == true)
  385. break;
  386. }
  387. while ((Last = Go(false, File)) == true);
  388. if (Last == false)
  389. return false;
  390. }
  391. }
  392. else
  393. {
  394. /* Closes encoding is used when the server did not specify a size, the
  395. loss of the connection means we are done */
  396. if (Encoding == Closes)
  397. In.Limit(-1);
  398. else
  399. In.Limit(Size - StartPos);
  400. // Just transfer the whole block.
  401. do
  402. {
  403. if (In.IsLimit() == false)
  404. continue;
  405. In.Limit(-1);
  406. return !_error->PendingError();
  407. }
  408. while (Go(true, File) == true);
  409. }
  410. return Owner->Flush() && !_error->PendingError();
  411. }
  412. /*}}}*/
  413. bool HttpServerState::ReadHeaderLines(std::string &Data) /*{{{*/
  414. {
  415. return In.WriteTillEl(Data);
  416. }
  417. /*}}}*/
  418. bool HttpServerState::LoadNextResponse(bool const ToFile, FileFd * const File)/*{{{*/
  419. {
  420. return Go(ToFile, File);
  421. }
  422. /*}}}*/
  423. bool HttpServerState::WriteResponse(const std::string &Data) /*{{{*/
  424. {
  425. return Out.Read(Data);
  426. }
  427. /*}}}*/
  428. bool HttpServerState::IsOpen() /*{{{*/
  429. {
  430. return (ServerFd != -1);
  431. }
  432. /*}}}*/
  433. bool HttpServerState::InitHashes(FileFd &File) /*{{{*/
  434. {
  435. delete In.Hash;
  436. In.Hash = new Hashes;
  437. // Set the expected size and read file for the hashes
  438. if (StartPos >= 0)
  439. {
  440. File.Truncate(StartPos);
  441. return In.Hash->AddFD(File, StartPos);
  442. }
  443. return true;
  444. }
  445. /*}}}*/
  446. Hashes * HttpServerState::GetHashes() /*{{{*/
  447. {
  448. return In.Hash;
  449. }
  450. /*}}}*/
  451. // HttpServerState::Die - The server has closed the connection. /*{{{*/
  452. bool HttpServerState::Die(FileFd &File)
  453. {
  454. unsigned int LErrno = errno;
  455. // Dump the buffer to the file
  456. if (State == ServerState::Data)
  457. {
  458. // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
  459. // can't be set
  460. if (File.Name() != "/dev/null")
  461. SetNonBlock(File.Fd(),false);
  462. while (In.WriteSpace() == true)
  463. {
  464. if (In.Write(File.Fd()) == false)
  465. return _error->Errno("write",_("Error writing to the file"));
  466. // Done
  467. if (In.IsLimit() == true)
  468. return true;
  469. }
  470. }
  471. // See if this is because the server finished the data stream
  472. if (In.IsLimit() == false && State != HttpServerState::Header &&
  473. Encoding != HttpServerState::Closes)
  474. {
  475. Close();
  476. if (LErrno == 0)
  477. return _error->Error(_("Error reading from server. Remote end closed connection"));
  478. errno = LErrno;
  479. return _error->Errno("read",_("Error reading from server"));
  480. }
  481. else
  482. {
  483. In.Limit(-1);
  484. // Nothing left in the buffer
  485. if (In.WriteSpace() == false)
  486. return false;
  487. // We may have got multiple responses back in one packet..
  488. Close();
  489. return true;
  490. }
  491. return false;
  492. }
  493. /*}}}*/
  494. // HttpServerState::Flush - Dump the buffer into the file /*{{{*/
  495. // ---------------------------------------------------------------------
  496. /* This takes the current input buffer from the Server FD and writes it
  497. into the file */
  498. bool HttpServerState::Flush(FileFd * const File)
  499. {
  500. if (File != NULL)
  501. {
  502. // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
  503. // can't be set
  504. if (File->Name() != "/dev/null")
  505. SetNonBlock(File->Fd(),false);
  506. if (In.WriteSpace() == false)
  507. return true;
  508. while (In.WriteSpace() == true)
  509. {
  510. if (In.Write(File->Fd()) == false)
  511. return _error->Errno("write",_("Error writing to file"));
  512. if (In.IsLimit() == true)
  513. return true;
  514. }
  515. if (In.IsLimit() == true || Encoding == ServerState::Closes)
  516. return true;
  517. }
  518. return false;
  519. }
  520. /*}}}*/
  521. // HttpServerState::Go - Run a single loop /*{{{*/
  522. // ---------------------------------------------------------------------
  523. /* This runs the select loop over the server FDs, Output file FDs and
  524. stdin. */
  525. bool HttpServerState::Go(bool ToFile, FileFd * const File)
  526. {
  527. // Server has closed the connection
  528. if (ServerFd == -1 && (In.WriteSpace() == false ||
  529. ToFile == false))
  530. return false;
  531. fd_set rfds,wfds;
  532. FD_ZERO(&rfds);
  533. FD_ZERO(&wfds);
  534. /* Add the server. We only send more requests if the connection will
  535. be persisting */
  536. if (Out.WriteSpace() == true && ServerFd != -1
  537. && Persistent == true)
  538. FD_SET(ServerFd,&wfds);
  539. if (In.ReadSpace() == true && ServerFd != -1)
  540. FD_SET(ServerFd,&rfds);
  541. // Add the file
  542. int FileFD = -1;
  543. if (File != NULL)
  544. FileFD = File->Fd();
  545. if (In.WriteSpace() == true && ToFile == true && FileFD != -1)
  546. FD_SET(FileFD,&wfds);
  547. // Add stdin
  548. if (_config->FindB("Acquire::http::DependOnSTDIN", true) == true)
  549. FD_SET(STDIN_FILENO,&rfds);
  550. // Figure out the max fd
  551. int MaxFd = FileFD;
  552. if (MaxFd < ServerFd)
  553. MaxFd = ServerFd;
  554. // Select
  555. struct timeval tv;
  556. tv.tv_sec = TimeOut;
  557. tv.tv_usec = 0;
  558. int Res = 0;
  559. if ((Res = select(MaxFd+1,&rfds,&wfds,0,&tv)) < 0)
  560. {
  561. if (errno == EINTR)
  562. return true;
  563. return _error->Errno("select",_("Select failed"));
  564. }
  565. if (Res == 0)
  566. {
  567. _error->Error(_("Connection timed out"));
  568. return Die(*File);
  569. }
  570. // Handle server IO
  571. if (ServerFd != -1 && FD_ISSET(ServerFd,&rfds))
  572. {
  573. errno = 0;
  574. if (In.Read(ServerFd) == false)
  575. return Die(*File);
  576. }
  577. if (ServerFd != -1 && FD_ISSET(ServerFd,&wfds))
  578. {
  579. errno = 0;
  580. if (Out.Write(ServerFd) == false)
  581. return Die(*File);
  582. }
  583. // Send data to the file
  584. if (FileFD != -1 && FD_ISSET(FileFD,&wfds))
  585. {
  586. if (In.Write(FileFD) == false)
  587. return _error->Errno("write",_("Error writing to output file"));
  588. }
  589. // Handle commands from APT
  590. if (FD_ISSET(STDIN_FILENO,&rfds))
  591. {
  592. if (Owner->Run(true) != -1)
  593. exit(100);
  594. }
  595. return true;
  596. }
  597. /*}}}*/
  598. // HttpMethod::SendReq - Send the HTTP request /*{{{*/
  599. // ---------------------------------------------------------------------
  600. /* This places the http request in the outbound buffer */
  601. void HttpMethod::SendReq(FetchItem *Itm)
  602. {
  603. URI Uri = Itm->Uri;
  604. // The HTTP server expects a hostname with a trailing :port
  605. char Buf[1000];
  606. string ProperHost;
  607. if (Uri.Host.find(':') != string::npos)
  608. ProperHost = '[' + Uri.Host + ']';
  609. else
  610. ProperHost = Uri.Host;
  611. if (Uri.Port != 0)
  612. {
  613. sprintf(Buf,":%u",Uri.Port);
  614. ProperHost += Buf;
  615. }
  616. // Just in case.
  617. if (Itm->Uri.length() >= sizeof(Buf))
  618. abort();
  619. /* RFC 2616 §5.1.2 requires absolute URIs for requests to proxies,
  620. but while its a must for all servers to accept absolute URIs,
  621. it is assumed clients will sent an absolute path for non-proxies */
  622. std::string requesturi;
  623. if (Server->Proxy.empty() == true || Server->Proxy.Host.empty())
  624. requesturi = Uri.Path;
  625. else
  626. requesturi = Itm->Uri;
  627. // The "+" is encoded as a workaround for a amazon S3 bug
  628. // see LP bugs #1003633 and #1086997.
  629. requesturi = QuoteString(requesturi, "+~ ");
  630. /* Build the request. No keep-alive is included as it is the default
  631. in 1.1, can cause problems with proxies, and we are an HTTP/1.1
  632. client anyway.
  633. C.f. https://tools.ietf.org/wg/httpbis/trac/ticket/158 */
  634. sprintf(Buf,"GET %s HTTP/1.1\r\nHost: %s\r\n",
  635. requesturi.c_str(),ProperHost.c_str());
  636. // generate a cache control header (if needed)
  637. if (_config->FindB("Acquire::http::No-Cache",false) == true)
  638. {
  639. strcat(Buf,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
  640. }
  641. else
  642. {
  643. if (Itm->IndexFile == true)
  644. {
  645. sprintf(Buf+strlen(Buf),"Cache-Control: max-age=%u\r\n",
  646. _config->FindI("Acquire::http::Max-Age",0));
  647. }
  648. else
  649. {
  650. if (_config->FindB("Acquire::http::No-Store",false) == true)
  651. strcat(Buf,"Cache-Control: no-store\r\n");
  652. }
  653. }
  654. // If we ask for uncompressed files servers might respond with content-
  655. // negotation which lets us end up with compressed files we do not support,
  656. // see 657029, 657560 and co, so if we have no extension on the request
  657. // ask for text only. As a sidenote: If there is nothing to negotate servers
  658. // seem to be nice and ignore it.
  659. if (_config->FindB("Acquire::http::SendAccept", true) == true)
  660. {
  661. size_t const filepos = Itm->Uri.find_last_of('/');
  662. string const file = Itm->Uri.substr(filepos + 1);
  663. if (flExtension(file) == file)
  664. strcat(Buf,"Accept: text/*\r\n");
  665. }
  666. string Req = Buf;
  667. // Check for a partial file
  668. struct stat SBuf;
  669. if (stat(Itm->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
  670. {
  671. // In this case we send an if-range query with a range header
  672. sprintf(Buf,"Range: bytes=%lli-\r\nIf-Range: %s\r\n",(long long)SBuf.st_size,
  673. TimeRFC1123(SBuf.st_mtime).c_str());
  674. Req += Buf;
  675. }
  676. else
  677. {
  678. if (Itm->LastModified != 0)
  679. {
  680. sprintf(Buf,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm->LastModified).c_str());
  681. Req += Buf;
  682. }
  683. }
  684. if (Server->Proxy.User.empty() == false || Server->Proxy.Password.empty() == false)
  685. Req += string("Proxy-Authorization: Basic ") +
  686. Base64Encode(Server->Proxy.User + ":" + Server->Proxy.Password) + "\r\n";
  687. maybe_add_auth (Uri, _config->FindFile("Dir::Etc::netrc"));
  688. if (Uri.User.empty() == false || Uri.Password.empty() == false)
  689. {
  690. Req += string("Authorization: Basic ") +
  691. Base64Encode(Uri.User + ":" + Uri.Password) + "\r\n";
  692. }
  693. Req += "User-Agent: " + _config->Find("Acquire::http::User-Agent",
  694. "Debian APT-HTTP/1.3 (" PACKAGE_VERSION ")") + "\r\n\r\n";
  695. if (Debug == true)
  696. cerr << Req << endl;
  697. Server->WriteResponse(Req);
  698. }
  699. /*}}}*/
  700. // HttpMethod::Configuration - Handle a configuration message /*{{{*/
  701. // ---------------------------------------------------------------------
  702. /* We stash the desired pipeline depth */
  703. bool HttpMethod::Configuration(string Message)
  704. {
  705. if (ServerMethod::Configuration(Message) == false)
  706. return false;
  707. AllowRedirect = _config->FindB("Acquire::http::AllowRedirect",true);
  708. PipelineDepth = _config->FindI("Acquire::http::Pipeline-Depth",
  709. PipelineDepth);
  710. Debug = _config->FindB("Debug::Acquire::http",false);
  711. // Get the proxy to use
  712. AutoDetectProxy();
  713. return true;
  714. }
  715. /*}}}*/
  716. // HttpMethod::AutoDetectProxy - auto detect proxy /*{{{*/
  717. // ---------------------------------------------------------------------
  718. /* */
  719. bool HttpMethod::AutoDetectProxy()
  720. {
  721. // option is "Acquire::http::Proxy-Auto-Detect" but we allow the old
  722. // name without the dash ("-")
  723. AutoDetectProxyCmd = _config->Find("Acquire::http::Proxy-Auto-Detect",
  724. _config->Find("Acquire::http::ProxyAutoDetect"));
  725. if (AutoDetectProxyCmd.empty())
  726. return true;
  727. if (Debug)
  728. clog << "Using auto proxy detect command: " << AutoDetectProxyCmd << endl;
  729. int Pipes[2] = {-1,-1};
  730. if (pipe(Pipes) != 0)
  731. return _error->Errno("pipe", "Failed to create Pipe");
  732. pid_t Process = ExecFork();
  733. if (Process == 0)
  734. {
  735. close(Pipes[0]);
  736. dup2(Pipes[1],STDOUT_FILENO);
  737. SetCloseExec(STDOUT_FILENO,false);
  738. const char *Args[2];
  739. Args[0] = AutoDetectProxyCmd.c_str();
  740. Args[1] = 0;
  741. execv(Args[0],(char **)Args);
  742. cerr << "Failed to exec method " << Args[0] << endl;
  743. _exit(100);
  744. }
  745. char buf[512];
  746. int InFd = Pipes[0];
  747. close(Pipes[1]);
  748. int res = read(InFd, buf, sizeof(buf)-1);
  749. ExecWait(Process, "ProxyAutoDetect", true);
  750. if (res < 0)
  751. return _error->Errno("read", "Failed to read");
  752. if (res == 0)
  753. return _error->Warning("ProxyAutoDetect returned no data");
  754. // add trailing \0
  755. buf[res] = 0;
  756. if (Debug)
  757. clog << "auto detect command returned: '" << buf << "'" << endl;
  758. if (strstr(buf, "http://") == buf)
  759. _config->Set("Acquire::http::proxy", _strstrip(buf));
  760. return true;
  761. }
  762. /*}}}*/
  763. ServerState * HttpMethod::CreateServerState(URI uri) /*{{{*/
  764. {
  765. return new HttpServerState(uri, this);
  766. }
  767. /*}}}*/
  768. void HttpMethod::RotateDNS() /*{{{*/
  769. {
  770. ::RotateDNS();
  771. }
  772. /*}}}*/