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