http.cc 26 KB

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