http.cc 29 KB

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