http.cc 31 KB

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