http.cc 29 KB

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