http.cc 28 KB

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