http.cc 29 KB

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