http.cc 36 KB

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