http.cc 27 KB

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