http.cc 29 KB

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