http.cc 31 KB

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