http.cc 36 KB

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