http.cc 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  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 occursed and 2 if a header
  331. parse error occured */
  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. ftruncate(File->Fd(),Srv->StartPos);
  830. }
  831. // Set the start point
  832. lseek(File->Fd(),0,SEEK_END);
  833. delete Srv->In.Hash;
  834. Srv->In.Hash = new Hashes;
  835. // Fill the Hash if the file is non-empty (resume)
  836. if (Srv->StartPos > 0)
  837. {
  838. lseek(File->Fd(),0,SEEK_SET);
  839. if (Srv->In.Hash->AddFD(File->Fd(),Srv->StartPos) == false)
  840. {
  841. _error->Errno("read",_("Problem hashing file"));
  842. return 5;
  843. }
  844. lseek(File->Fd(),0,SEEK_END);
  845. }
  846. SetNonBlock(File->Fd(),true);
  847. return 0;
  848. }
  849. /*}}}*/
  850. // HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
  851. // ---------------------------------------------------------------------
  852. /* This closes and timestamps the open file. This is neccessary to get
  853. resume behavoir on user abort */
  854. void HttpMethod::SigTerm(int)
  855. {
  856. if (FailFd == -1)
  857. _exit(100);
  858. close(FailFd);
  859. // Timestamp
  860. struct utimbuf UBuf;
  861. UBuf.actime = FailTime;
  862. UBuf.modtime = FailTime;
  863. utime(FailFile.c_str(),&UBuf);
  864. _exit(100);
  865. }
  866. /*}}}*/
  867. // HttpMethod::Fetch - Fetch an item /*{{{*/
  868. // ---------------------------------------------------------------------
  869. /* This adds an item to the pipeline. We keep the pipeline at a fixed
  870. depth. */
  871. bool HttpMethod::Fetch(FetchItem *)
  872. {
  873. if (Server == 0)
  874. return true;
  875. // Queue the requests
  876. int Depth = -1;
  877. for (FetchItem *I = Queue; I != 0 && Depth < (signed)PipelineDepth;
  878. I = I->Next, Depth++)
  879. {
  880. // If pipelining is disabled, we only queue 1 request
  881. if (Server->Pipeline == false && Depth >= 0)
  882. break;
  883. // Make sure we stick with the same server
  884. if (Server->Comp(I->Uri) == false)
  885. break;
  886. if (QueueBack == I)
  887. {
  888. QueueBack = I->Next;
  889. SendReq(I,Server->Out);
  890. continue;
  891. }
  892. }
  893. return true;
  894. };
  895. /*}}}*/
  896. // HttpMethod::Configuration - Handle a configuration message /*{{{*/
  897. // ---------------------------------------------------------------------
  898. /* We stash the desired pipeline depth */
  899. bool HttpMethod::Configuration(string Message)
  900. {
  901. if (pkgAcqMethod::Configuration(Message) == false)
  902. return false;
  903. TimeOut = _config->FindI("Acquire::http::Timeout",TimeOut);
  904. PipelineDepth = _config->FindI("Acquire::http::Pipeline-Depth",
  905. PipelineDepth);
  906. Debug = _config->FindB("Debug::Acquire::http",false);
  907. return true;
  908. }
  909. /*}}}*/
  910. // HttpMethod::Loop - Main loop /*{{{*/
  911. // ---------------------------------------------------------------------
  912. /* */
  913. int HttpMethod::Loop()
  914. {
  915. signal(SIGTERM,SigTerm);
  916. signal(SIGINT,SigTerm);
  917. Server = 0;
  918. int FailCounter = 0;
  919. while (1)
  920. {
  921. // We have no commands, wait for some to arrive
  922. if (Queue == 0)
  923. {
  924. if (WaitFd(STDIN_FILENO) == false)
  925. return 0;
  926. }
  927. /* Run messages, we can accept 0 (no message) if we didn't
  928. do a WaitFd above.. Otherwise the FD is closed. */
  929. int Result = Run(true);
  930. if (Result != -1 && (Result != 0 || Queue == 0))
  931. return 100;
  932. if (Queue == 0)
  933. continue;
  934. // Connect to the server
  935. if (Server == 0 || Server->Comp(Queue->Uri) == false)
  936. {
  937. delete Server;
  938. Server = new ServerState(Queue->Uri,this);
  939. }
  940. /* If the server has explicitly said this is the last connection
  941. then we pre-emptively shut down the pipeline and tear down
  942. the connection. This will speed up HTTP/1.0 servers a tad
  943. since we don't have to wait for the close sequence to
  944. complete */
  945. if (Server->Persistent == false)
  946. Server->Close();
  947. // Reset the pipeline
  948. if (Server->ServerFd == -1)
  949. QueueBack = Queue;
  950. // Connnect to the host
  951. if (Server->Open() == false)
  952. {
  953. Fail(true);
  954. delete Server;
  955. Server = 0;
  956. continue;
  957. }
  958. // Fill the pipeline.
  959. Fetch(0);
  960. // Fetch the next URL header data from the server.
  961. switch (Server->RunHeaders())
  962. {
  963. case 0:
  964. break;
  965. // The header data is bad
  966. case 2:
  967. {
  968. _error->Error(_("Bad header data"));
  969. Fail(true);
  970. RotateDNS();
  971. continue;
  972. }
  973. // The server closed a connection during the header get..
  974. default:
  975. case 1:
  976. {
  977. FailCounter++;
  978. _error->Discard();
  979. Server->Close();
  980. Server->Pipeline = false;
  981. if (FailCounter >= 2)
  982. {
  983. Fail(_("Connection failed"),true);
  984. FailCounter = 0;
  985. }
  986. RotateDNS();
  987. continue;
  988. }
  989. };
  990. // Decide what to do.
  991. FetchResult Res;
  992. Res.Filename = Queue->DestFile;
  993. switch (DealWithHeaders(Res,Server))
  994. {
  995. // Ok, the file is Open
  996. case 0:
  997. {
  998. URIStart(Res);
  999. // Run the data
  1000. bool Result = Server->RunData();
  1001. /* If the server is sending back sizeless responses then fill in
  1002. the size now */
  1003. if (Res.Size == 0)
  1004. Res.Size = File->Size();
  1005. // Close the file, destroy the FD object and timestamp it
  1006. FailFd = -1;
  1007. delete File;
  1008. File = 0;
  1009. // Timestamp
  1010. struct utimbuf UBuf;
  1011. time(&UBuf.actime);
  1012. UBuf.actime = Server->Date;
  1013. UBuf.modtime = Server->Date;
  1014. utime(Queue->DestFile.c_str(),&UBuf);
  1015. // Send status to APT
  1016. if (Result == true)
  1017. {
  1018. Res.TakeHashes(*Server->In.Hash);
  1019. URIDone(Res);
  1020. }
  1021. else
  1022. {
  1023. if (Server->ServerFd == -1)
  1024. {
  1025. FailCounter++;
  1026. _error->Discard();
  1027. Server->Close();
  1028. if (FailCounter >= 2)
  1029. {
  1030. Fail(_("Connection failed"),true);
  1031. FailCounter = 0;
  1032. }
  1033. QueueBack = Queue;
  1034. }
  1035. else
  1036. Fail(true);
  1037. }
  1038. break;
  1039. }
  1040. // IMS hit
  1041. case 1:
  1042. {
  1043. URIDone(Res);
  1044. break;
  1045. }
  1046. // Hard server error, not found or something
  1047. case 3:
  1048. {
  1049. Fail();
  1050. break;
  1051. }
  1052. // Hard internal error, kill the connection and fail
  1053. case 5:
  1054. {
  1055. delete File;
  1056. File = 0;
  1057. Fail();
  1058. RotateDNS();
  1059. Server->Close();
  1060. break;
  1061. }
  1062. // We need to flush the data, the header is like a 404 w/ error text
  1063. case 4:
  1064. {
  1065. Fail();
  1066. // Send to content to dev/null
  1067. File = new FileFd("/dev/null",FileFd::WriteExists);
  1068. Server->RunData();
  1069. delete File;
  1070. File = 0;
  1071. break;
  1072. }
  1073. default:
  1074. Fail(_("Internal error"));
  1075. break;
  1076. }
  1077. FailCounter = 0;
  1078. }
  1079. return 0;
  1080. }
  1081. /*}}}*/
  1082. int main()
  1083. {
  1084. setlocale(LC_ALL, "");
  1085. HttpMethod Mth;
  1086. return Mth.Loop();
  1087. }