http.cc 25 KB

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