http.cc 29 KB

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