http.cc 31 KB

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