http.cc 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426
  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 = Uri.Host;
  591. if (Uri.Port != 0)
  592. {
  593. sprintf(Buf,":%u",Uri.Port);
  594. ProperHost += Buf;
  595. }
  596. // Just in case.
  597. if (Itm->Uri.length() >= sizeof(Buf))
  598. abort();
  599. /* Build the request. We include a keep-alive header only for non-proxy
  600. requests. This is to tweak old http/1.0 servers that do support keep-alive
  601. but not HTTP/1.1 automatic keep-alive. Doing this with a proxy server
  602. will glitch HTTP/1.0 proxies because they do not filter it out and
  603. pass it on, HTTP/1.1 says the connection should default to keep alive
  604. and we expect the proxy to do this */
  605. if (Proxy.empty() == true || Proxy.Host.empty())
  606. {
  607. // see LP bugs #1003633 and #1086997. The "+" is encoded as a workaround
  608. // for a amazon S3 bug
  609. sprintf(Buf,"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: keep-alive\r\n",
  610. QuoteString(Uri.Path,"+~ ").c_str(),ProperHost.c_str());
  611. }
  612. else
  613. {
  614. /* Generate a cache control header if necessary. We place a max
  615. cache age on index files, optionally set a no-cache directive
  616. and a no-store directive for archives. */
  617. sprintf(Buf,"GET %s HTTP/1.1\r\nHost: %s\r\n",
  618. Itm->Uri.c_str(),ProperHost.c_str());
  619. }
  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. {
  868. if (Uri.Port != 0)
  869. strprintf(NextURI, "http://%s:%u", Uri.Host.c_str(), Uri.Port);
  870. else
  871. NextURI = "http://" + Uri.Host;
  872. }
  873. else
  874. NextURI.clear();
  875. NextURI.append(DeQuoteString(Srv->Location));
  876. return TRY_AGAIN_OR_REDIRECT;
  877. }
  878. else
  879. {
  880. NextURI = DeQuoteString(Srv->Location);
  881. URI tmpURI = NextURI;
  882. // Do not allow a redirection to switch protocol
  883. if (tmpURI.Access == "http")
  884. return TRY_AGAIN_OR_REDIRECT;
  885. }
  886. /* else pass through for error message */
  887. }
  888. /* We have a reply we dont handle. This should indicate a perm server
  889. failure */
  890. if (Srv->Result < 200 || Srv->Result >= 300)
  891. {
  892. char err[255];
  893. snprintf(err,sizeof(err)-1,"HttpError%i",Srv->Result);
  894. SetFailReason(err);
  895. _error->Error("%u %s",Srv->Result,Srv->Code);
  896. if (Srv->HaveContent == true)
  897. return ERROR_WITH_CONTENT_PAGE;
  898. return ERROR_UNRECOVERABLE;
  899. }
  900. // This is some sort of 2xx 'data follows' reply
  901. Res.LastModified = Srv->Date;
  902. Res.Size = Srv->Size;
  903. // Open the file
  904. delete File;
  905. File = new FileFd(Queue->DestFile,FileFd::WriteAny);
  906. if (_error->PendingError() == true)
  907. return ERROR_NOT_FROM_SERVER;
  908. FailFile = Queue->DestFile;
  909. FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
  910. FailFd = File->Fd();
  911. FailTime = Srv->Date;
  912. delete Srv->In.Hash;
  913. Srv->In.Hash = new Hashes;
  914. // Set the expected size and read file for the hashes
  915. if (Srv->StartPos >= 0)
  916. {
  917. Res.ResumePoint = Srv->StartPos;
  918. File->Truncate(Srv->StartPos);
  919. if (Srv->In.Hash->AddFD(*File,Srv->StartPos) == false)
  920. {
  921. _error->Errno("read",_("Problem hashing file"));
  922. return ERROR_NOT_FROM_SERVER;
  923. }
  924. }
  925. SetNonBlock(File->Fd(),true);
  926. return FILE_IS_OPEN;
  927. }
  928. /*}}}*/
  929. // HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
  930. // ---------------------------------------------------------------------
  931. /* This closes and timestamps the open file. This is neccessary to get
  932. resume behavoir on user abort */
  933. void HttpMethod::SigTerm(int)
  934. {
  935. if (FailFd == -1)
  936. _exit(100);
  937. close(FailFd);
  938. // Timestamp
  939. struct utimbuf UBuf;
  940. UBuf.actime = FailTime;
  941. UBuf.modtime = FailTime;
  942. utime(FailFile.c_str(),&UBuf);
  943. _exit(100);
  944. }
  945. /*}}}*/
  946. // HttpMethod::Fetch - Fetch an item /*{{{*/
  947. // ---------------------------------------------------------------------
  948. /* This adds an item to the pipeline. We keep the pipeline at a fixed
  949. depth. */
  950. bool HttpMethod::Fetch(FetchItem *)
  951. {
  952. if (Server == 0)
  953. return true;
  954. // Queue the requests
  955. int Depth = -1;
  956. for (FetchItem *I = Queue; I != 0 && Depth < (signed)PipelineDepth;
  957. I = I->Next, Depth++)
  958. {
  959. // If pipelining is disabled, we only queue 1 request
  960. if (Server->Pipeline == false && Depth >= 0)
  961. break;
  962. // Make sure we stick with the same server
  963. if (Server->Comp(I->Uri) == false)
  964. break;
  965. if (QueueBack == I)
  966. {
  967. QueueBack = I->Next;
  968. SendReq(I,Server->Out);
  969. continue;
  970. }
  971. }
  972. return true;
  973. };
  974. /*}}}*/
  975. // HttpMethod::Configuration - Handle a configuration message /*{{{*/
  976. // ---------------------------------------------------------------------
  977. /* We stash the desired pipeline depth */
  978. bool HttpMethod::Configuration(string Message)
  979. {
  980. if (pkgAcqMethod::Configuration(Message) == false)
  981. return false;
  982. AllowRedirect = _config->FindB("Acquire::http::AllowRedirect",true);
  983. TimeOut = _config->FindI("Acquire::http::Timeout",TimeOut);
  984. PipelineDepth = _config->FindI("Acquire::http::Pipeline-Depth",
  985. PipelineDepth);
  986. Debug = _config->FindB("Debug::Acquire::http",false);
  987. AutoDetectProxyCmd = _config->Find("Acquire::http::ProxyAutoDetect");
  988. // Get the proxy to use
  989. AutoDetectProxy();
  990. return true;
  991. }
  992. /*}}}*/
  993. // HttpMethod::Loop - Main loop /*{{{*/
  994. // ---------------------------------------------------------------------
  995. /* */
  996. int HttpMethod::Loop()
  997. {
  998. typedef vector<string> StringVector;
  999. typedef vector<string>::iterator StringVectorIterator;
  1000. map<string, StringVector> Redirected;
  1001. signal(SIGTERM,SigTerm);
  1002. signal(SIGINT,SigTerm);
  1003. Server = 0;
  1004. int FailCounter = 0;
  1005. while (1)
  1006. {
  1007. // We have no commands, wait for some to arrive
  1008. if (Queue == 0)
  1009. {
  1010. if (WaitFd(STDIN_FILENO) == false)
  1011. return 0;
  1012. }
  1013. /* Run messages, we can accept 0 (no message) if we didn't
  1014. do a WaitFd above.. Otherwise the FD is closed. */
  1015. int Result = Run(true);
  1016. if (Result != -1 && (Result != 0 || Queue == 0))
  1017. {
  1018. if(FailReason.empty() == false ||
  1019. _config->FindB("Acquire::http::DependOnSTDIN", true) == true)
  1020. return 100;
  1021. else
  1022. return 0;
  1023. }
  1024. if (Queue == 0)
  1025. continue;
  1026. // Connect to the server
  1027. if (Server == 0 || Server->Comp(Queue->Uri) == false)
  1028. {
  1029. delete Server;
  1030. Server = new ServerState(Queue->Uri,this);
  1031. }
  1032. /* If the server has explicitly said this is the last connection
  1033. then we pre-emptively shut down the pipeline and tear down
  1034. the connection. This will speed up HTTP/1.0 servers a tad
  1035. since we don't have to wait for the close sequence to
  1036. complete */
  1037. if (Server->Persistent == false)
  1038. Server->Close();
  1039. // Reset the pipeline
  1040. if (Server->ServerFd == -1)
  1041. QueueBack = Queue;
  1042. // Connnect to the host
  1043. if (Server->Open() == false)
  1044. {
  1045. Fail(true);
  1046. delete Server;
  1047. Server = 0;
  1048. continue;
  1049. }
  1050. // Fill the pipeline.
  1051. Fetch(0);
  1052. // Fetch the next URL header data from the server.
  1053. switch (Server->RunHeaders())
  1054. {
  1055. case ServerState::RUN_HEADERS_OK:
  1056. break;
  1057. // The header data is bad
  1058. case ServerState::RUN_HEADERS_PARSE_ERROR:
  1059. {
  1060. _error->Error(_("Bad header data"));
  1061. Fail(true);
  1062. RotateDNS();
  1063. continue;
  1064. }
  1065. // The server closed a connection during the header get..
  1066. default:
  1067. case ServerState::RUN_HEADERS_IO_ERROR:
  1068. {
  1069. FailCounter++;
  1070. _error->Discard();
  1071. Server->Close();
  1072. Server->Pipeline = false;
  1073. if (FailCounter >= 2)
  1074. {
  1075. Fail(_("Connection failed"),true);
  1076. FailCounter = 0;
  1077. }
  1078. RotateDNS();
  1079. continue;
  1080. }
  1081. };
  1082. // Decide what to do.
  1083. FetchResult Res;
  1084. Res.Filename = Queue->DestFile;
  1085. switch (DealWithHeaders(Res,Server))
  1086. {
  1087. // Ok, the file is Open
  1088. case FILE_IS_OPEN:
  1089. {
  1090. URIStart(Res);
  1091. // Run the data
  1092. bool Result = Server->RunData();
  1093. /* If the server is sending back sizeless responses then fill in
  1094. the size now */
  1095. if (Res.Size == 0)
  1096. Res.Size = File->Size();
  1097. // Close the file, destroy the FD object and timestamp it
  1098. FailFd = -1;
  1099. delete File;
  1100. File = 0;
  1101. // Timestamp
  1102. struct utimbuf UBuf;
  1103. time(&UBuf.actime);
  1104. UBuf.actime = Server->Date;
  1105. UBuf.modtime = Server->Date;
  1106. utime(Queue->DestFile.c_str(),&UBuf);
  1107. // Send status to APT
  1108. if (Result == true)
  1109. {
  1110. Res.TakeHashes(*Server->In.Hash);
  1111. URIDone(Res);
  1112. }
  1113. else
  1114. {
  1115. if (Server->ServerFd == -1)
  1116. {
  1117. FailCounter++;
  1118. _error->Discard();
  1119. Server->Close();
  1120. if (FailCounter >= 2)
  1121. {
  1122. Fail(_("Connection failed"),true);
  1123. FailCounter = 0;
  1124. }
  1125. QueueBack = Queue;
  1126. }
  1127. else
  1128. Fail(true);
  1129. }
  1130. break;
  1131. }
  1132. // IMS hit
  1133. case IMS_HIT:
  1134. {
  1135. URIDone(Res);
  1136. break;
  1137. }
  1138. // Hard server error, not found or something
  1139. case ERROR_UNRECOVERABLE:
  1140. {
  1141. Fail();
  1142. break;
  1143. }
  1144. // Hard internal error, kill the connection and fail
  1145. case ERROR_NOT_FROM_SERVER:
  1146. {
  1147. delete File;
  1148. File = 0;
  1149. Fail();
  1150. RotateDNS();
  1151. Server->Close();
  1152. break;
  1153. }
  1154. // We need to flush the data, the header is like a 404 w/ error text
  1155. case ERROR_WITH_CONTENT_PAGE:
  1156. {
  1157. Fail();
  1158. // Send to content to dev/null
  1159. File = new FileFd("/dev/null",FileFd::WriteExists);
  1160. Server->RunData();
  1161. delete File;
  1162. File = 0;
  1163. break;
  1164. }
  1165. // Try again with a new URL
  1166. case TRY_AGAIN_OR_REDIRECT:
  1167. {
  1168. // Clear rest of response if there is content
  1169. if (Server->HaveContent)
  1170. {
  1171. File = new FileFd("/dev/null",FileFd::WriteExists);
  1172. Server->RunData();
  1173. delete File;
  1174. File = 0;
  1175. }
  1176. /* Detect redirect loops. No more redirects are allowed
  1177. after the same URI is seen twice in a queue item. */
  1178. StringVector &R = Redirected[Queue->DestFile];
  1179. bool StopRedirects = false;
  1180. if (R.empty() == true)
  1181. R.push_back(Queue->Uri);
  1182. else if (R[0] == "STOP" || R.size() > 10)
  1183. StopRedirects = true;
  1184. else
  1185. {
  1186. for (StringVectorIterator I = R.begin(); I != R.end(); ++I)
  1187. if (Queue->Uri == *I)
  1188. {
  1189. R[0] = "STOP";
  1190. break;
  1191. }
  1192. R.push_back(Queue->Uri);
  1193. }
  1194. if (StopRedirects == false)
  1195. Redirect(NextURI);
  1196. else
  1197. Fail();
  1198. break;
  1199. }
  1200. default:
  1201. Fail(_("Internal error"));
  1202. break;
  1203. }
  1204. FailCounter = 0;
  1205. }
  1206. return 0;
  1207. }
  1208. /*}}}*/
  1209. // HttpMethod::AutoDetectProxy - auto detect proxy /*{{{*/
  1210. // ---------------------------------------------------------------------
  1211. /* */
  1212. bool HttpMethod::AutoDetectProxy()
  1213. {
  1214. if (AutoDetectProxyCmd.empty())
  1215. return true;
  1216. if (Debug)
  1217. clog << "Using auto proxy detect command: " << AutoDetectProxyCmd << endl;
  1218. int Pipes[2] = {-1,-1};
  1219. if (pipe(Pipes) != 0)
  1220. return _error->Errno("pipe", "Failed to create Pipe");
  1221. pid_t Process = ExecFork();
  1222. if (Process == 0)
  1223. {
  1224. close(Pipes[0]);
  1225. dup2(Pipes[1],STDOUT_FILENO);
  1226. SetCloseExec(STDOUT_FILENO,false);
  1227. const char *Args[2];
  1228. Args[0] = AutoDetectProxyCmd.c_str();
  1229. Args[1] = 0;
  1230. execv(Args[0],(char **)Args);
  1231. cerr << "Failed to exec method " << Args[0] << endl;
  1232. _exit(100);
  1233. }
  1234. char buf[512];
  1235. int InFd = Pipes[0];
  1236. close(Pipes[1]);
  1237. int res = read(InFd, buf, sizeof(buf));
  1238. ExecWait(Process, "ProxyAutoDetect", true);
  1239. if (res < 0)
  1240. return _error->Errno("read", "Failed to read");
  1241. if (res == 0)
  1242. return _error->Warning("ProxyAutoDetect returned no data");
  1243. // add trailing \0
  1244. buf[res] = 0;
  1245. if (Debug)
  1246. clog << "auto detect command returned: '" << buf << "'" << endl;
  1247. if (strstr(buf, "http://") == buf)
  1248. _config->Set("Acquire::http::proxy", _strstrip(buf));
  1249. return true;
  1250. }
  1251. /*}}}*/