http.cc 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  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::DlLimit",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. if (_config->FindB("Acquire::http::No-Cache",false) == true)
  593. strcat(Buf,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
  594. else
  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. string Req = Buf;
  607. // Check for a partial file
  608. struct stat SBuf;
  609. if (stat(Itm->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
  610. {
  611. // In this case we send an if-range query with a range header
  612. sprintf(Buf,"Range: bytes=%li-\r\nIf-Range: %s\r\n",(long)SBuf.st_size - 1,
  613. TimeRFC1123(SBuf.st_mtime).c_str());
  614. Req += Buf;
  615. }
  616. else
  617. {
  618. if (Itm->LastModified != 0)
  619. {
  620. sprintf(Buf,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm->LastModified).c_str());
  621. Req += Buf;
  622. }
  623. }
  624. if (Proxy.User.empty() == false || Proxy.Password.empty() == false)
  625. Req += string("Proxy-Authorization: Basic ") +
  626. Base64Encode(Proxy.User + ":" + Proxy.Password) + "\r\n";
  627. if (Uri.User.empty() == false || Uri.Password.empty() == false)
  628. Req += string("Authorization: Basic ") +
  629. Base64Encode(Uri.User + ":" + Uri.Password) + "\r\n";
  630. Req += "User-Agent: Debian APT-HTTP/1.3\r\n\r\n";
  631. if (Debug == true)
  632. cerr << Req << endl;
  633. Out.Read(Req);
  634. }
  635. /*}}}*/
  636. // HttpMethod::Go - Run a single loop /*{{{*/
  637. // ---------------------------------------------------------------------
  638. /* This runs the select loop over the server FDs, Output file FDs and
  639. stdin. */
  640. bool HttpMethod::Go(bool ToFile,ServerState *Srv)
  641. {
  642. // Server has closed the connection
  643. if (Srv->ServerFd == -1 && (Srv->In.WriteSpace() == false ||
  644. ToFile == false))
  645. return false;
  646. fd_set rfds,wfds;
  647. FD_ZERO(&rfds);
  648. FD_ZERO(&wfds);
  649. /* Add the server. We only send more requests if the connection will
  650. be persisting */
  651. if (Srv->Out.WriteSpace() == true && Srv->ServerFd != -1
  652. && Srv->Persistent == true)
  653. FD_SET(Srv->ServerFd,&wfds);
  654. if (Srv->In.ReadSpace() == true && Srv->ServerFd != -1)
  655. FD_SET(Srv->ServerFd,&rfds);
  656. // Add the file
  657. int FileFD = -1;
  658. if (File != 0)
  659. FileFD = File->Fd();
  660. if (Srv->In.WriteSpace() == true && ToFile == true && FileFD != -1)
  661. FD_SET(FileFD,&wfds);
  662. // Add stdin
  663. FD_SET(STDIN_FILENO,&rfds);
  664. // Figure out the max fd
  665. int MaxFd = FileFD;
  666. if (MaxFd < Srv->ServerFd)
  667. MaxFd = Srv->ServerFd;
  668. // Select
  669. struct timeval tv;
  670. tv.tv_sec = TimeOut;
  671. tv.tv_usec = 0;
  672. int Res = 0;
  673. if ((Res = select(MaxFd+1,&rfds,&wfds,0,&tv)) < 0)
  674. {
  675. if (errno == EINTR)
  676. return true;
  677. return _error->Errno("select",_("Select failed"));
  678. }
  679. if (Res == 0)
  680. {
  681. _error->Error(_("Connection timed out"));
  682. return ServerDie(Srv);
  683. }
  684. // Handle server IO
  685. if (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&rfds))
  686. {
  687. errno = 0;
  688. if (Srv->In.Read(Srv->ServerFd) == false)
  689. return ServerDie(Srv);
  690. }
  691. if (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&wfds))
  692. {
  693. errno = 0;
  694. if (Srv->Out.Write(Srv->ServerFd) == false)
  695. return ServerDie(Srv);
  696. }
  697. // Send data to the file
  698. if (FileFD != -1 && FD_ISSET(FileFD,&wfds))
  699. {
  700. if (Srv->In.Write(FileFD) == false)
  701. return _error->Errno("write",_("Error writing to output file"));
  702. }
  703. // Handle commands from APT
  704. if (FD_ISSET(STDIN_FILENO,&rfds))
  705. {
  706. if (Run(true) != -1)
  707. exit(100);
  708. }
  709. return true;
  710. }
  711. /*}}}*/
  712. // HttpMethod::Flush - Dump the buffer into the file /*{{{*/
  713. // ---------------------------------------------------------------------
  714. /* This takes the current input buffer from the Server FD and writes it
  715. into the file */
  716. bool HttpMethod::Flush(ServerState *Srv)
  717. {
  718. if (File != 0)
  719. {
  720. SetNonBlock(File->Fd(),false);
  721. if (Srv->In.WriteSpace() == false)
  722. return true;
  723. while (Srv->In.WriteSpace() == true)
  724. {
  725. if (Srv->In.Write(File->Fd()) == false)
  726. return _error->Errno("write",_("Error writing to file"));
  727. if (Srv->In.IsLimit() == true)
  728. return true;
  729. }
  730. if (Srv->In.IsLimit() == true || Srv->Encoding == ServerState::Closes)
  731. return true;
  732. }
  733. return false;
  734. }
  735. /*}}}*/
  736. // HttpMethod::ServerDie - The server has closed the connection. /*{{{*/
  737. // ---------------------------------------------------------------------
  738. /* */
  739. bool HttpMethod::ServerDie(ServerState *Srv)
  740. {
  741. unsigned int LErrno = errno;
  742. // Dump the buffer to the file
  743. if (Srv->State == ServerState::Data)
  744. {
  745. SetNonBlock(File->Fd(),false);
  746. while (Srv->In.WriteSpace() == true)
  747. {
  748. if (Srv->In.Write(File->Fd()) == false)
  749. return _error->Errno("write",_("Error writing to the file"));
  750. // Done
  751. if (Srv->In.IsLimit() == true)
  752. return true;
  753. }
  754. }
  755. // See if this is because the server finished the data stream
  756. if (Srv->In.IsLimit() == false && Srv->State != ServerState::Header &&
  757. Srv->Encoding != ServerState::Closes)
  758. {
  759. Srv->Close();
  760. if (LErrno == 0)
  761. return _error->Error(_("Error reading from server. Remote end closed connection"));
  762. errno = LErrno;
  763. return _error->Errno("read",_("Error reading from server"));
  764. }
  765. else
  766. {
  767. Srv->In.Limit(-1);
  768. // Nothing left in the buffer
  769. if (Srv->In.WriteSpace() == false)
  770. return false;
  771. // We may have got multiple responses back in one packet..
  772. Srv->Close();
  773. return true;
  774. }
  775. return false;
  776. }
  777. /*}}}*/
  778. // HttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
  779. // ---------------------------------------------------------------------
  780. /* We look at the header data we got back from the server and decide what
  781. to do. Returns
  782. 0 - File is open,
  783. 1 - IMS hit
  784. 3 - Unrecoverable error
  785. 4 - Error with error content page
  786. 5 - Unrecoverable non-server error (close the connection) */
  787. int HttpMethod::DealWithHeaders(FetchResult &Res,ServerState *Srv)
  788. {
  789. // Not Modified
  790. if (Srv->Result == 304)
  791. {
  792. unlink(Queue->DestFile.c_str());
  793. Res.IMSHit = true;
  794. Res.LastModified = Queue->LastModified;
  795. return 1;
  796. }
  797. /* We have a reply we dont handle. This should indicate a perm server
  798. failure */
  799. if (Srv->Result < 200 || Srv->Result >= 300)
  800. {
  801. _error->Error("%u %s",Srv->Result,Srv->Code);
  802. if (Srv->HaveContent == true)
  803. return 4;
  804. return 3;
  805. }
  806. // This is some sort of 2xx 'data follows' reply
  807. Res.LastModified = Srv->Date;
  808. Res.Size = Srv->Size;
  809. // Open the file
  810. delete File;
  811. File = new FileFd(Queue->DestFile,FileFd::WriteAny);
  812. if (_error->PendingError() == true)
  813. return 5;
  814. FailFile = Queue->DestFile;
  815. FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
  816. FailFd = File->Fd();
  817. FailTime = Srv->Date;
  818. // Set the expected size
  819. if (Srv->StartPos >= 0)
  820. {
  821. Res.ResumePoint = Srv->StartPos;
  822. ftruncate(File->Fd(),Srv->StartPos);
  823. }
  824. // Set the start point
  825. lseek(File->Fd(),0,SEEK_END);
  826. delete Srv->In.Hash;
  827. Srv->In.Hash = new Hashes;
  828. // Fill the Hash if the file is non-empty (resume)
  829. if (Srv->StartPos > 0)
  830. {
  831. lseek(File->Fd(),0,SEEK_SET);
  832. if (Srv->In.Hash->AddFD(File->Fd(),Srv->StartPos) == false)
  833. {
  834. _error->Errno("read",_("Problem hashing file"));
  835. return 5;
  836. }
  837. lseek(File->Fd(),0,SEEK_END);
  838. }
  839. SetNonBlock(File->Fd(),true);
  840. return 0;
  841. }
  842. /*}}}*/
  843. // HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
  844. // ---------------------------------------------------------------------
  845. /* This closes and timestamps the open file. This is neccessary to get
  846. resume behavoir on user abort */
  847. void HttpMethod::SigTerm(int)
  848. {
  849. if (FailFd == -1)
  850. _exit(100);
  851. close(FailFd);
  852. // Timestamp
  853. struct utimbuf UBuf;
  854. UBuf.actime = FailTime;
  855. UBuf.modtime = FailTime;
  856. utime(FailFile.c_str(),&UBuf);
  857. _exit(100);
  858. }
  859. /*}}}*/
  860. // HttpMethod::Fetch - Fetch an item /*{{{*/
  861. // ---------------------------------------------------------------------
  862. /* This adds an item to the pipeline. We keep the pipeline at a fixed
  863. depth. */
  864. bool HttpMethod::Fetch(FetchItem *)
  865. {
  866. if (Server == 0)
  867. return true;
  868. // Queue the requests
  869. int Depth = -1;
  870. bool Tail = false;
  871. for (FetchItem *I = Queue; I != 0 && Depth < (signed)PipelineDepth;
  872. I = I->Next, Depth++)
  873. {
  874. // If pipelining is disabled, we only queue 1 request
  875. if (Server->Pipeline == false && Depth >= 0)
  876. break;
  877. // Make sure we stick with the same server
  878. if (Server->Comp(I->Uri) == false)
  879. break;
  880. if (QueueBack == I)
  881. Tail = true;
  882. if (Tail == true)
  883. {
  884. QueueBack = I->Next;
  885. SendReq(I,Server->Out);
  886. continue;
  887. }
  888. }
  889. return true;
  890. };
  891. /*}}}*/
  892. // HttpMethod::Configuration - Handle a configuration message /*{{{*/
  893. // ---------------------------------------------------------------------
  894. /* We stash the desired pipeline depth */
  895. bool HttpMethod::Configuration(string Message)
  896. {
  897. if (pkgAcqMethod::Configuration(Message) == false)
  898. return false;
  899. TimeOut = _config->FindI("Acquire::http::Timeout",TimeOut);
  900. PipelineDepth = _config->FindI("Acquire::http::Pipeline-Depth",
  901. PipelineDepth);
  902. Debug = _config->FindB("Debug::Acquire::http",false);
  903. return true;
  904. }
  905. /*}}}*/
  906. // HttpMethod::Loop - Main loop /*{{{*/
  907. // ---------------------------------------------------------------------
  908. /* */
  909. int HttpMethod::Loop()
  910. {
  911. signal(SIGTERM,SigTerm);
  912. signal(SIGINT,SigTerm);
  913. Server = 0;
  914. int FailCounter = 0;
  915. while (1)
  916. {
  917. // We have no commands, wait for some to arrive
  918. if (Queue == 0)
  919. {
  920. if (WaitFd(STDIN_FILENO) == false)
  921. return 0;
  922. }
  923. /* Run messages, we can accept 0 (no message) if we didn't
  924. do a WaitFd above.. Otherwise the FD is closed. */
  925. int Result = Run(true);
  926. if (Result != -1 && (Result != 0 || Queue == 0))
  927. return 100;
  928. if (Queue == 0)
  929. continue;
  930. // Connect to the server
  931. if (Server == 0 || Server->Comp(Queue->Uri) == false)
  932. {
  933. delete Server;
  934. Server = new ServerState(Queue->Uri,this);
  935. }
  936. /* If the server has explicitly said this is the last connection
  937. then we pre-emptively shut down the pipeline and tear down
  938. the connection. This will speed up HTTP/1.0 servers a tad
  939. since we don't have to wait for the close sequence to
  940. complete */
  941. if (Server->Persistent == false)
  942. Server->Close();
  943. // Reset the pipeline
  944. if (Server->ServerFd == -1)
  945. QueueBack = Queue;
  946. // Connnect to the host
  947. if (Server->Open() == false)
  948. {
  949. Fail(true);
  950. delete Server;
  951. Server = 0;
  952. continue;
  953. }
  954. // Fill the pipeline.
  955. Fetch(0);
  956. // Fetch the next URL header data from the server.
  957. switch (Server->RunHeaders())
  958. {
  959. case 0:
  960. break;
  961. // The header data is bad
  962. case 2:
  963. {
  964. _error->Error(_("Bad header data"));
  965. Fail(true);
  966. RotateDNS();
  967. continue;
  968. }
  969. // The server closed a connection during the header get..
  970. default:
  971. case 1:
  972. {
  973. FailCounter++;
  974. _error->Discard();
  975. Server->Close();
  976. Server->Pipeline = false;
  977. if (FailCounter >= 2)
  978. {
  979. Fail(_("Connection failed"),true);
  980. FailCounter = 0;
  981. }
  982. RotateDNS();
  983. continue;
  984. }
  985. };
  986. // Decide what to do.
  987. FetchResult Res;
  988. Res.Filename = Queue->DestFile;
  989. switch (DealWithHeaders(Res,Server))
  990. {
  991. // Ok, the file is Open
  992. case 0:
  993. {
  994. URIStart(Res);
  995. // Run the data
  996. bool Result = Server->RunData();
  997. /* If the server is sending back sizeless responses then fill in
  998. the size now */
  999. if (Res.Size == 0)
  1000. Res.Size = File->Size();
  1001. // Close the file, destroy the FD object and timestamp it
  1002. FailFd = -1;
  1003. delete File;
  1004. File = 0;
  1005. // Timestamp
  1006. struct utimbuf UBuf;
  1007. time(&UBuf.actime);
  1008. UBuf.actime = Server->Date;
  1009. UBuf.modtime = Server->Date;
  1010. utime(Queue->DestFile.c_str(),&UBuf);
  1011. // Send status to APT
  1012. if (Result == true)
  1013. {
  1014. Res.TakeHashes(*Server->In.Hash);
  1015. URIDone(Res);
  1016. }
  1017. else
  1018. Fail(true);
  1019. break;
  1020. }
  1021. // IMS hit
  1022. case 1:
  1023. {
  1024. URIDone(Res);
  1025. break;
  1026. }
  1027. // Hard server error, not found or something
  1028. case 3:
  1029. {
  1030. Fail();
  1031. break;
  1032. }
  1033. // Hard internal error, kill the connection and fail
  1034. case 5:
  1035. {
  1036. delete File;
  1037. File = 0;
  1038. Fail();
  1039. RotateDNS();
  1040. Server->Close();
  1041. break;
  1042. }
  1043. // We need to flush the data, the header is like a 404 w/ error text
  1044. case 4:
  1045. {
  1046. Fail();
  1047. // Send to content to dev/null
  1048. File = new FileFd("/dev/null",FileFd::WriteExists);
  1049. Server->RunData();
  1050. delete File;
  1051. File = 0;
  1052. break;
  1053. }
  1054. default:
  1055. Fail(_("Internal error"));
  1056. break;
  1057. }
  1058. FailCounter = 0;
  1059. }
  1060. return 0;
  1061. }
  1062. /*}}}*/
  1063. int main()
  1064. {
  1065. setlocale(LC_ALL, "");
  1066. HttpMethod Mth;
  1067. return Mth.Loop();
  1068. }