http.cc 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: http.cc,v 1.58 2004/02/27 00:52:41 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. for (I++; I < InP && Buf[I%Size] == '\r'; I++);
  184. if (Single == false)
  185. {
  186. if (Buf[I%Size] != '\n')
  187. continue;
  188. for (I++; I < InP && Buf[I%Size] == '\r'; I++);
  189. }
  190. if (I > InP)
  191. I = InP;
  192. Data = "";
  193. while (OutP < I)
  194. {
  195. unsigned long Sz = LeftWrite();
  196. if (Sz == 0)
  197. return false;
  198. if (I - OutP < LeftWrite())
  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. if (_config->FindB("Acquire::http::No-Cache",false) == true)
  561. strcat(Buf,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
  562. else
  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. string Req = Buf;
  575. // Check for a partial file
  576. struct stat SBuf;
  577. if (stat(Itm->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
  578. {
  579. // In this case we send an if-range query with a range header
  580. sprintf(Buf,"Range: bytes=%li-\r\nIf-Range: %s\r\n",(long)SBuf.st_size - 1,
  581. TimeRFC1123(SBuf.st_mtime).c_str());
  582. Req += Buf;
  583. }
  584. else
  585. {
  586. if (Itm->LastModified != 0)
  587. {
  588. sprintf(Buf,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm->LastModified).c_str());
  589. Req += Buf;
  590. }
  591. }
  592. if (Proxy.User.empty() == false || Proxy.Password.empty() == false)
  593. Req += string("Proxy-Authorization: Basic ") +
  594. Base64Encode(Proxy.User + ":" + Proxy.Password) + "\r\n";
  595. if (Uri.User.empty() == false || Uri.Password.empty() == false)
  596. Req += string("Authorization: Basic ") +
  597. Base64Encode(Uri.User + ":" + Uri.Password) + "\r\n";
  598. Req += "User-Agent: Debian APT-HTTP/1.3\r\n\r\n";
  599. if (Debug == true)
  600. cerr << Req << endl;
  601. Out.Read(Req);
  602. }
  603. /*}}}*/
  604. // HttpMethod::Go - Run a single loop /*{{{*/
  605. // ---------------------------------------------------------------------
  606. /* This runs the select loop over the server FDs, Output file FDs and
  607. stdin. */
  608. bool HttpMethod::Go(bool ToFile,ServerState *Srv)
  609. {
  610. // Server has closed the connection
  611. if (Srv->ServerFd == -1 && (Srv->In.WriteSpace() == false ||
  612. ToFile == false))
  613. return false;
  614. fd_set rfds,wfds;
  615. FD_ZERO(&rfds);
  616. FD_ZERO(&wfds);
  617. /* Add the server. We only send more requests if the connection will
  618. be persisting */
  619. if (Srv->Out.WriteSpace() == true && Srv->ServerFd != -1
  620. && Srv->Persistent == true)
  621. FD_SET(Srv->ServerFd,&wfds);
  622. if (Srv->In.ReadSpace() == true && Srv->ServerFd != -1)
  623. FD_SET(Srv->ServerFd,&rfds);
  624. // Add the file
  625. int FileFD = -1;
  626. if (File != 0)
  627. FileFD = File->Fd();
  628. if (Srv->In.WriteSpace() == true && ToFile == true && FileFD != -1)
  629. FD_SET(FileFD,&wfds);
  630. // Add stdin
  631. FD_SET(STDIN_FILENO,&rfds);
  632. // Figure out the max fd
  633. int MaxFd = FileFD;
  634. if (MaxFd < Srv->ServerFd)
  635. MaxFd = Srv->ServerFd;
  636. // Select
  637. struct timeval tv;
  638. tv.tv_sec = TimeOut;
  639. tv.tv_usec = 0;
  640. int Res = 0;
  641. if ((Res = select(MaxFd+1,&rfds,&wfds,0,&tv)) < 0)
  642. {
  643. if (errno == EINTR)
  644. return true;
  645. return _error->Errno("select",_("Select failed"));
  646. }
  647. if (Res == 0)
  648. {
  649. _error->Error(_("Connection timed out"));
  650. return ServerDie(Srv);
  651. }
  652. // Handle server IO
  653. if (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&rfds))
  654. {
  655. errno = 0;
  656. if (Srv->In.Read(Srv->ServerFd) == false)
  657. return ServerDie(Srv);
  658. }
  659. if (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&wfds))
  660. {
  661. errno = 0;
  662. if (Srv->Out.Write(Srv->ServerFd) == false)
  663. return ServerDie(Srv);
  664. }
  665. // Send data to the file
  666. if (FileFD != -1 && FD_ISSET(FileFD,&wfds))
  667. {
  668. if (Srv->In.Write(FileFD) == false)
  669. return _error->Errno("write",_("Error writing to output file"));
  670. }
  671. // Handle commands from APT
  672. if (FD_ISSET(STDIN_FILENO,&rfds))
  673. {
  674. if (Run(true) != -1)
  675. exit(100);
  676. }
  677. return true;
  678. }
  679. /*}}}*/
  680. // HttpMethod::Flush - Dump the buffer into the file /*{{{*/
  681. // ---------------------------------------------------------------------
  682. /* This takes the current input buffer from the Server FD and writes it
  683. into the file */
  684. bool HttpMethod::Flush(ServerState *Srv)
  685. {
  686. if (File != 0)
  687. {
  688. SetNonBlock(File->Fd(),false);
  689. if (Srv->In.WriteSpace() == false)
  690. return true;
  691. while (Srv->In.WriteSpace() == true)
  692. {
  693. if (Srv->In.Write(File->Fd()) == false)
  694. return _error->Errno("write",_("Error writing to file"));
  695. if (Srv->In.IsLimit() == true)
  696. return true;
  697. }
  698. if (Srv->In.IsLimit() == true || Srv->Encoding == ServerState::Closes)
  699. return true;
  700. }
  701. return false;
  702. }
  703. /*}}}*/
  704. // HttpMethod::ServerDie - The server has closed the connection. /*{{{*/
  705. // ---------------------------------------------------------------------
  706. /* */
  707. bool HttpMethod::ServerDie(ServerState *Srv)
  708. {
  709. unsigned int LErrno = errno;
  710. // Dump the buffer to the file
  711. if (Srv->State == ServerState::Data)
  712. {
  713. SetNonBlock(File->Fd(),false);
  714. while (Srv->In.WriteSpace() == true)
  715. {
  716. if (Srv->In.Write(File->Fd()) == false)
  717. return _error->Errno("write",_("Error writing to the file"));
  718. // Done
  719. if (Srv->In.IsLimit() == true)
  720. return true;
  721. }
  722. }
  723. // See if this is because the server finished the data stream
  724. if (Srv->In.IsLimit() == false && Srv->State != ServerState::Header &&
  725. Srv->Encoding != ServerState::Closes)
  726. {
  727. Srv->Close();
  728. if (LErrno == 0)
  729. return _error->Error(_("Error reading from server Remote end closed connection"));
  730. errno = LErrno;
  731. return _error->Errno("read",_("Error reading from server"));
  732. }
  733. else
  734. {
  735. Srv->In.Limit(-1);
  736. // Nothing left in the buffer
  737. if (Srv->In.WriteSpace() == false)
  738. return false;
  739. // We may have got multiple responses back in one packet..
  740. Srv->Close();
  741. return true;
  742. }
  743. return false;
  744. }
  745. /*}}}*/
  746. // HttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
  747. // ---------------------------------------------------------------------
  748. /* We look at the header data we got back from the server and decide what
  749. to do. Returns
  750. 0 - File is open,
  751. 1 - IMS hit
  752. 3 - Unrecoverable error
  753. 4 - Error with error content page
  754. 5 - Unrecoverable non-server error (close the connection) */
  755. int HttpMethod::DealWithHeaders(FetchResult &Res,ServerState *Srv)
  756. {
  757. // Not Modified
  758. if (Srv->Result == 304)
  759. {
  760. unlink(Queue->DestFile.c_str());
  761. Res.IMSHit = true;
  762. Res.LastModified = Queue->LastModified;
  763. return 1;
  764. }
  765. /* We have a reply we dont handle. This should indicate a perm server
  766. failure */
  767. if (Srv->Result < 200 || Srv->Result >= 300)
  768. {
  769. _error->Error("%u %s",Srv->Result,Srv->Code);
  770. if (Srv->HaveContent == true)
  771. return 4;
  772. return 3;
  773. }
  774. // This is some sort of 2xx 'data follows' reply
  775. Res.LastModified = Srv->Date;
  776. Res.Size = Srv->Size;
  777. // Open the file
  778. delete File;
  779. File = new FileFd(Queue->DestFile,FileFd::WriteAny);
  780. if (_error->PendingError() == true)
  781. return 5;
  782. FailFile = Queue->DestFile;
  783. FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
  784. FailFd = File->Fd();
  785. FailTime = Srv->Date;
  786. // Set the expected size
  787. if (Srv->StartPos >= 0)
  788. {
  789. Res.ResumePoint = Srv->StartPos;
  790. ftruncate(File->Fd(),Srv->StartPos);
  791. }
  792. // Set the start point
  793. lseek(File->Fd(),0,SEEK_END);
  794. delete Srv->In.Hash;
  795. Srv->In.Hash = new Hashes;
  796. // Fill the Hash if the file is non-empty (resume)
  797. if (Srv->StartPos > 0)
  798. {
  799. lseek(File->Fd(),0,SEEK_SET);
  800. if (Srv->In.Hash->AddFD(File->Fd(),Srv->StartPos) == false)
  801. {
  802. _error->Errno("read",_("Problem hashing file"));
  803. return 5;
  804. }
  805. lseek(File->Fd(),0,SEEK_END);
  806. }
  807. SetNonBlock(File->Fd(),true);
  808. return 0;
  809. }
  810. /*}}}*/
  811. // HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
  812. // ---------------------------------------------------------------------
  813. /* This closes and timestamps the open file. This is neccessary to get
  814. resume behavoir on user abort */
  815. void HttpMethod::SigTerm(int)
  816. {
  817. if (FailFd == -1)
  818. _exit(100);
  819. close(FailFd);
  820. // Timestamp
  821. struct utimbuf UBuf;
  822. UBuf.actime = FailTime;
  823. UBuf.modtime = FailTime;
  824. utime(FailFile.c_str(),&UBuf);
  825. _exit(100);
  826. }
  827. /*}}}*/
  828. // HttpMethod::Fetch - Fetch an item /*{{{*/
  829. // ---------------------------------------------------------------------
  830. /* This adds an item to the pipeline. We keep the pipeline at a fixed
  831. depth. */
  832. bool HttpMethod::Fetch(FetchItem *)
  833. {
  834. if (Server == 0)
  835. return true;
  836. // Queue the requests
  837. int Depth = -1;
  838. bool Tail = false;
  839. for (FetchItem *I = Queue; I != 0 && Depth < (signed)PipelineDepth;
  840. I = I->Next, Depth++)
  841. {
  842. // If pipelining is disabled, we only queue 1 request
  843. if (Server->Pipeline == false && Depth >= 0)
  844. break;
  845. // Make sure we stick with the same server
  846. if (Server->Comp(I->Uri) == false)
  847. break;
  848. if (QueueBack == I)
  849. Tail = true;
  850. if (Tail == true)
  851. {
  852. QueueBack = I->Next;
  853. SendReq(I,Server->Out);
  854. continue;
  855. }
  856. }
  857. return true;
  858. };
  859. /*}}}*/
  860. // HttpMethod::Configuration - Handle a configuration message /*{{{*/
  861. // ---------------------------------------------------------------------
  862. /* We stash the desired pipeline depth */
  863. bool HttpMethod::Configuration(string Message)
  864. {
  865. if (pkgAcqMethod::Configuration(Message) == false)
  866. return false;
  867. TimeOut = _config->FindI("Acquire::http::Timeout",TimeOut);
  868. PipelineDepth = _config->FindI("Acquire::http::Pipeline-Depth",
  869. PipelineDepth);
  870. Debug = _config->FindB("Debug::Acquire::http",false);
  871. return true;
  872. }
  873. /*}}}*/
  874. // HttpMethod::Loop - Main loop /*{{{*/
  875. // ---------------------------------------------------------------------
  876. /* */
  877. int HttpMethod::Loop()
  878. {
  879. signal(SIGTERM,SigTerm);
  880. signal(SIGINT,SigTerm);
  881. Server = 0;
  882. int FailCounter = 0;
  883. while (1)
  884. {
  885. // We have no commands, wait for some to arrive
  886. if (Queue == 0)
  887. {
  888. if (WaitFd(STDIN_FILENO) == false)
  889. return 0;
  890. }
  891. /* Run messages, we can accept 0 (no message) if we didn't
  892. do a WaitFd above.. Otherwise the FD is closed. */
  893. int Result = Run(true);
  894. if (Result != -1 && (Result != 0 || Queue == 0))
  895. return 100;
  896. if (Queue == 0)
  897. continue;
  898. // Connect to the server
  899. if (Server == 0 || Server->Comp(Queue->Uri) == false)
  900. {
  901. delete Server;
  902. Server = new ServerState(Queue->Uri,this);
  903. }
  904. /* If the server has explicitly said this is the last connection
  905. then we pre-emptively shut down the pipeline and tear down
  906. the connection. This will speed up HTTP/1.0 servers a tad
  907. since we don't have to wait for the close sequence to
  908. complete */
  909. if (Server->Persistent == false)
  910. Server->Close();
  911. // Reset the pipeline
  912. if (Server->ServerFd == -1)
  913. QueueBack = Queue;
  914. // Connnect to the host
  915. if (Server->Open() == false)
  916. {
  917. Fail(true);
  918. delete Server;
  919. Server = 0;
  920. continue;
  921. }
  922. // Fill the pipeline.
  923. Fetch(0);
  924. // Fetch the next URL header data from the server.
  925. switch (Server->RunHeaders())
  926. {
  927. case 0:
  928. break;
  929. // The header data is bad
  930. case 2:
  931. {
  932. _error->Error(_("Bad header Data"));
  933. Fail(true);
  934. RotateDNS();
  935. continue;
  936. }
  937. // The server closed a connection during the header get..
  938. default:
  939. case 1:
  940. {
  941. FailCounter++;
  942. _error->Discard();
  943. Server->Close();
  944. Server->Pipeline = false;
  945. if (FailCounter >= 2)
  946. {
  947. Fail(_("Connection failed"),true);
  948. FailCounter = 0;
  949. }
  950. RotateDNS();
  951. continue;
  952. }
  953. };
  954. // Decide what to do.
  955. FetchResult Res;
  956. Res.Filename = Queue->DestFile;
  957. switch (DealWithHeaders(Res,Server))
  958. {
  959. // Ok, the file is Open
  960. case 0:
  961. {
  962. URIStart(Res);
  963. // Run the data
  964. bool Result = Server->RunData();
  965. /* If the server is sending back sizeless responses then fill in
  966. the size now */
  967. if (Res.Size == 0)
  968. Res.Size = File->Size();
  969. // Close the file, destroy the FD object and timestamp it
  970. FailFd = -1;
  971. delete File;
  972. File = 0;
  973. // Timestamp
  974. struct utimbuf UBuf;
  975. time(&UBuf.actime);
  976. UBuf.actime = Server->Date;
  977. UBuf.modtime = Server->Date;
  978. utime(Queue->DestFile.c_str(),&UBuf);
  979. // Send status to APT
  980. if (Result == true)
  981. {
  982. Res.TakeHashes(*Server->In.Hash);
  983. URIDone(Res);
  984. }
  985. else
  986. Fail(true);
  987. break;
  988. }
  989. // IMS hit
  990. case 1:
  991. {
  992. URIDone(Res);
  993. break;
  994. }
  995. // Hard server error, not found or something
  996. case 3:
  997. {
  998. Fail();
  999. break;
  1000. }
  1001. // Hard internal error, kill the connection and fail
  1002. case 5:
  1003. {
  1004. delete File;
  1005. File = 0;
  1006. Fail();
  1007. RotateDNS();
  1008. Server->Close();
  1009. break;
  1010. }
  1011. // We need to flush the data, the header is like a 404 w/ error text
  1012. case 4:
  1013. {
  1014. Fail();
  1015. // Send to content to dev/null
  1016. File = new FileFd("/dev/null",FileFd::WriteExists);
  1017. Server->RunData();
  1018. delete File;
  1019. File = 0;
  1020. break;
  1021. }
  1022. default:
  1023. Fail(_("Internal error"));
  1024. break;
  1025. }
  1026. FailCounter = 0;
  1027. }
  1028. return 0;
  1029. }
  1030. /*}}}*/
  1031. int main()
  1032. {
  1033. HttpMethod Mth;
  1034. return Mth.Loop();
  1035. }