http.cc 28 KB

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