http.cc 31 KB

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