http.cc 30 KB

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