http.cc 29 KB

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