http.cc 28 KB

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