http.cc 29 KB

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