http.cc 29 KB

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