http.cc 35 KB

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