http.cc 33 KB

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