http.cc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: http.cc,v 1.59 2004/05/08 19:42:35 mdz Exp $
  4. /* ######################################################################
  5. HTTP Acquire Method - This is the HTTP acquire 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.
  8. It is based on a doubly buffered select loop. A groupe of requests are
  9. fed into a single output buffer that is constantly fed out the
  10. socket. This provides ideal pipelining as in many cases all of the
  11. requests will fit into a single packet. The input socket is buffered
  12. the same way and fed into the fd for the file (may be a pipe in future).
  13. This double buffering provides fairly substantial transfer rates,
  14. compared to wget the http method is about 4% faster. Most importantly,
  15. when HTTP is compared with FTP as a protocol the speed difference is
  16. huge. In tests over the internet from two sites to llug (via ATM) this
  17. program got 230k/s sustained http transfer rates. FTP on the other
  18. hand topped out at 170k/s. That combined with the time to setup the
  19. FTP connection makes HTTP a vastly superior protocol.
  20. ##################################################################### */
  21. /*}}}*/
  22. // Include Files /*{{{*/
  23. #include <config.h>
  24. #include <apt-pkg/fileutl.h>
  25. #include <apt-pkg/configuration.h>
  26. #include <apt-pkg/error.h>
  27. #include <apt-pkg/hashes.h>
  28. #include <apt-pkg/netrc.h>
  29. #include <apt-pkg/strutl.h>
  30. #include <apt-pkg/proxy.h>
  31. #include <stddef.h>
  32. #include <stdlib.h>
  33. #include <sys/select.h>
  34. #include <cstring>
  35. #include <sys/stat.h>
  36. #include <sys/time.h>
  37. #include <unistd.h>
  38. #include <stdio.h>
  39. #include <errno.h>
  40. #include <arpa/inet.h>
  41. #include <iostream>
  42. #include <sstream>
  43. #include "config.h"
  44. #include "connect.h"
  45. #include "http.h"
  46. #include <apti18n.h>
  47. /*}}}*/
  48. using namespace std;
  49. unsigned long long CircleBuf::BwReadLimit=0;
  50. unsigned long long CircleBuf::BwTickReadData=0;
  51. struct timeval CircleBuf::BwReadTick={0,0};
  52. const unsigned int CircleBuf::BW_HZ=10;
  53. // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
  54. // ---------------------------------------------------------------------
  55. /* */
  56. CircleBuf::CircleBuf(HttpMethod const * const Owner, unsigned long long Size)
  57. : Size(Size), Hash(NULL), TotalWriten(0)
  58. {
  59. Buf = new unsigned char[Size];
  60. Reset();
  61. CircleBuf::BwReadLimit = Owner->ConfigFindI("Dl-Limit", 0) * 1024;
  62. }
  63. /*}}}*/
  64. // CircleBuf::Reset - Reset to the default state /*{{{*/
  65. // ---------------------------------------------------------------------
  66. /* */
  67. void CircleBuf::Reset()
  68. {
  69. InP = 0;
  70. OutP = 0;
  71. StrPos = 0;
  72. TotalWriten = 0;
  73. MaxGet = (unsigned long long)-1;
  74. OutQueue = string();
  75. if (Hash != NULL)
  76. {
  77. delete Hash;
  78. Hash = NULL;
  79. }
  80. }
  81. /*}}}*/
  82. // CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
  83. // ---------------------------------------------------------------------
  84. /* This fills up the buffer with as much data as is in the FD, assuming it
  85. is non-blocking.. */
  86. bool CircleBuf::Read(int Fd)
  87. {
  88. while (1)
  89. {
  90. // Woops, buffer is full
  91. if (InP - OutP == Size)
  92. return true;
  93. // what's left to read in this tick
  94. unsigned long long const BwReadMax = CircleBuf::BwReadLimit/BW_HZ;
  95. if(CircleBuf::BwReadLimit) {
  96. struct timeval now;
  97. gettimeofday(&now,0);
  98. unsigned long long d = (now.tv_sec-CircleBuf::BwReadTick.tv_sec)*1000000 +
  99. now.tv_usec-CircleBuf::BwReadTick.tv_usec;
  100. if(d > 1000000/BW_HZ) {
  101. CircleBuf::BwReadTick = now;
  102. CircleBuf::BwTickReadData = 0;
  103. }
  104. if(CircleBuf::BwTickReadData >= BwReadMax) {
  105. usleep(1000000/BW_HZ);
  106. return true;
  107. }
  108. }
  109. // Write the buffer segment
  110. ssize_t Res;
  111. if(CircleBuf::BwReadLimit) {
  112. Res = read(Fd,Buf + (InP%Size),
  113. BwReadMax > LeftRead() ? LeftRead() : BwReadMax);
  114. } else
  115. Res = read(Fd,Buf + (InP%Size),LeftRead());
  116. if(Res > 0 && BwReadLimit > 0)
  117. CircleBuf::BwTickReadData += Res;
  118. if (Res == 0)
  119. return false;
  120. if (Res < 0)
  121. {
  122. if (errno == EAGAIN)
  123. return true;
  124. return false;
  125. }
  126. if (InP == 0)
  127. gettimeofday(&Start,0);
  128. InP += Res;
  129. }
  130. }
  131. /*}}}*/
  132. // CircleBuf::Read - Put the string into the buffer /*{{{*/
  133. // ---------------------------------------------------------------------
  134. /* This will hold the string in and fill the buffer with it as it empties */
  135. bool CircleBuf::Read(string const &Data)
  136. {
  137. OutQueue.append(Data);
  138. FillOut();
  139. return true;
  140. }
  141. /*}}}*/
  142. // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
  143. // ---------------------------------------------------------------------
  144. /* */
  145. void CircleBuf::FillOut()
  146. {
  147. if (OutQueue.empty() == true)
  148. return;
  149. while (1)
  150. {
  151. // Woops, buffer is full
  152. if (InP - OutP == Size)
  153. return;
  154. // Write the buffer segment
  155. unsigned long long Sz = LeftRead();
  156. if (OutQueue.length() - StrPos < Sz)
  157. Sz = OutQueue.length() - StrPos;
  158. memcpy(Buf + (InP%Size),OutQueue.c_str() + StrPos,Sz);
  159. // Advance
  160. StrPos += Sz;
  161. InP += Sz;
  162. if (OutQueue.length() == StrPos)
  163. {
  164. StrPos = 0;
  165. OutQueue = "";
  166. return;
  167. }
  168. }
  169. }
  170. /*}}}*/
  171. // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
  172. // ---------------------------------------------------------------------
  173. /* This empties the buffer into the FD. */
  174. bool CircleBuf::Write(int Fd)
  175. {
  176. while (1)
  177. {
  178. FillOut();
  179. // Woops, buffer is empty
  180. if (OutP == InP)
  181. return true;
  182. if (OutP == MaxGet)
  183. return true;
  184. // Write the buffer segment
  185. ssize_t Res;
  186. Res = write(Fd,Buf + (OutP%Size),LeftWrite());
  187. if (Res == 0)
  188. return false;
  189. if (Res < 0)
  190. {
  191. if (errno == EAGAIN)
  192. return true;
  193. return false;
  194. }
  195. TotalWriten += Res;
  196. if (Hash != NULL)
  197. Hash->Add(Buf + (OutP%Size),Res);
  198. OutP += Res;
  199. }
  200. }
  201. /*}}}*/
  202. // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
  203. // ---------------------------------------------------------------------
  204. /* This copies till the first empty line */
  205. bool CircleBuf::WriteTillEl(string &Data,bool Single)
  206. {
  207. // We cheat and assume it is unneeded to have more than one buffer load
  208. for (unsigned long long I = OutP; I < InP; I++)
  209. {
  210. if (Buf[I%Size] != '\n')
  211. continue;
  212. ++I;
  213. if (Single == false)
  214. {
  215. if (I < InP && Buf[I%Size] == '\r')
  216. ++I;
  217. if (I >= InP || Buf[I%Size] != '\n')
  218. continue;
  219. ++I;
  220. }
  221. Data = "";
  222. while (OutP < I)
  223. {
  224. unsigned long long Sz = LeftWrite();
  225. if (Sz == 0)
  226. return false;
  227. if (I - OutP < Sz)
  228. Sz = I - OutP;
  229. Data += string((char *)(Buf + (OutP%Size)),Sz);
  230. OutP += Sz;
  231. }
  232. return true;
  233. }
  234. return false;
  235. }
  236. /*}}}*/
  237. // CircleBuf::Stats - Print out stats information /*{{{*/
  238. // ---------------------------------------------------------------------
  239. /* */
  240. void CircleBuf::Stats()
  241. {
  242. if (InP == 0)
  243. return;
  244. struct timeval Stop;
  245. gettimeofday(&Stop,0);
  246. /* float Diff = Stop.tv_sec - Start.tv_sec +
  247. (float)(Stop.tv_usec - Start.tv_usec)/1000000;
  248. clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
  249. }
  250. /*}}}*/
  251. CircleBuf::~CircleBuf()
  252. {
  253. delete [] Buf;
  254. delete Hash;
  255. }
  256. // HttpServerState::HttpServerState - Constructor /*{{{*/
  257. HttpServerState::HttpServerState(URI Srv,HttpMethod *Owner) : ServerState(Srv, Owner), In(Owner, 64*1024), Out(Owner, 4*1024)
  258. {
  259. TimeOut = Owner->ConfigFindI("Timeout", TimeOut);
  260. Reset();
  261. }
  262. /*}}}*/
  263. // HttpServerState::Open - Open a connection to the server /*{{{*/
  264. // ---------------------------------------------------------------------
  265. /* This opens a connection to the server. */
  266. static bool TalkToSocksProxy(int const ServerFd, std::string const &Proxy,
  267. char const * const type, bool const ReadWrite, uint8_t * const ToFrom,
  268. unsigned int const Size, unsigned int const Timeout)
  269. {
  270. if (WaitFd(ServerFd, ReadWrite, Timeout) == false)
  271. return _error->Error("Waiting for the SOCKS proxy %s to %s timed out", URI::SiteOnly(Proxy).c_str(), type);
  272. if (ReadWrite == false)
  273. {
  274. if (FileFd::Read(ServerFd, ToFrom, Size) == false)
  275. return _error->Error("Reading the %s from SOCKS proxy %s failed", type, URI::SiteOnly(Proxy).c_str());
  276. }
  277. else
  278. {
  279. if (FileFd::Write(ServerFd, ToFrom, Size) == false)
  280. return _error->Error("Writing the %s to SOCKS proxy %s failed", type, URI::SiteOnly(Proxy).c_str());
  281. }
  282. return true;
  283. }
  284. bool HttpServerState::Open()
  285. {
  286. // Use the already open connection if possible.
  287. if (ServerFd != -1)
  288. return true;
  289. Close();
  290. In.Reset();
  291. Out.Reset();
  292. Persistent = true;
  293. // Determine the proxy setting
  294. AutoDetectProxy(ServerName);
  295. string SpecificProxy = Owner->ConfigFind("Proxy::" + ServerName.Host, "");
  296. if (!SpecificProxy.empty())
  297. {
  298. if (SpecificProxy == "DIRECT")
  299. Proxy = "";
  300. else
  301. Proxy = SpecificProxy;
  302. }
  303. else
  304. {
  305. string DefProxy = Owner->ConfigFind("Proxy", "");
  306. if (!DefProxy.empty())
  307. {
  308. Proxy = DefProxy;
  309. }
  310. else
  311. {
  312. char* result = getenv("http_proxy");
  313. Proxy = result ? result : "";
  314. }
  315. }
  316. // Parse no_proxy, a , separated list of domains
  317. if (getenv("no_proxy") != 0)
  318. {
  319. if (CheckDomainList(ServerName.Host,getenv("no_proxy")) == true)
  320. Proxy = "";
  321. }
  322. if (Proxy.Access == "socks5h")
  323. {
  324. if (Connect(Proxy.Host, Proxy.Port, "socks", 1080, ServerFd, TimeOut, Owner) == false)
  325. return false;
  326. /* We implement a very basic SOCKS5 client here complying mostly to RFC1928 expect
  327. * for not offering GSSAPI auth which is a must (we only do no or user/pass auth).
  328. * We also expect the SOCKS5 server to do hostname lookup (aka socks5h) */
  329. std::string const ProxyInfo = URI::SiteOnly(Proxy);
  330. Owner->Status(_("Connecting to %s (%s)"),"SOCKS5h proxy",ProxyInfo.c_str());
  331. auto const Timeout = Owner->ConfigFindI("TimeOut", 120);
  332. #define APT_WriteOrFail(TYPE, DATA, LENGTH) if (TalkToSocksProxy(ServerFd, ProxyInfo, TYPE, true, DATA, LENGTH, Timeout) == false) return false
  333. #define APT_ReadOrFail(TYPE, DATA, LENGTH) if (TalkToSocksProxy(ServerFd, ProxyInfo, TYPE, false, DATA, LENGTH, Timeout) == false) return false
  334. if (ServerName.Host.length() > 255)
  335. return _error->Error("Can't use SOCKS5h as hostname %s is too long!", ServerName.Host.c_str());
  336. if (Proxy.User.length() > 255 || Proxy.Password.length() > 255)
  337. return _error->Error("Can't use user&pass auth as they are too long (%lu and %lu) for the SOCKS5!", Proxy.User.length(), Proxy.Password.length());
  338. if (Proxy.User.empty())
  339. {
  340. uint8_t greeting[] = { 0x05, 0x01, 0x00 };
  341. APT_WriteOrFail("greet-1", greeting, sizeof(greeting));
  342. }
  343. else
  344. {
  345. uint8_t greeting[] = { 0x05, 0x02, 0x00, 0x02 };
  346. APT_WriteOrFail("greet-2", greeting, sizeof(greeting));
  347. }
  348. uint8_t greeting[2];
  349. APT_ReadOrFail("greet back", greeting, sizeof(greeting));
  350. if (greeting[0] != 0x05)
  351. return _error->Error("SOCKS proxy %s greets back with wrong version: %d", ProxyInfo.c_str(), greeting[0]);
  352. if (greeting[1] == 0x00)
  353. ; // no auth has no method-dependent sub-negotiations
  354. else if (greeting[1] == 0x02)
  355. {
  356. if (Proxy.User.empty())
  357. return _error->Error("SOCKS proxy %s negotiated user&pass auth, but we had not offered it!", ProxyInfo.c_str());
  358. // user&pass auth sub-negotiations are defined by RFC1929
  359. std::vector<uint8_t> auth = {{ 0x01, static_cast<uint8_t>(Proxy.User.length()) }};
  360. std::copy(Proxy.User.begin(), Proxy.User.end(), std::back_inserter(auth));
  361. auth.push_back(static_cast<uint8_t>(Proxy.Password.length()));
  362. std::copy(Proxy.Password.begin(), Proxy.Password.end(), std::back_inserter(auth));
  363. APT_WriteOrFail("user&pass auth", auth.data(), auth.size());
  364. uint8_t authstatus[2];
  365. APT_ReadOrFail("auth report", authstatus, sizeof(authstatus));
  366. if (authstatus[0] != 0x01)
  367. return _error->Error("SOCKS proxy %s auth status response with wrong version: %d", ProxyInfo.c_str(), authstatus[0]);
  368. if (authstatus[1] != 0x00)
  369. return _error->Error("SOCKS proxy %s reported authorization failure: username or password incorrect? (%d)", ProxyInfo.c_str(), authstatus[1]);
  370. }
  371. else
  372. return _error->Error("SOCKS proxy %s greets back having not found a common authorization method: %d", ProxyInfo.c_str(), greeting[1]);
  373. union { uint16_t * i; uint8_t * b; } portu;
  374. uint16_t port = htons(static_cast<uint16_t>(ServerName.Port == 0 ? 80 : ServerName.Port));
  375. portu.i = &port;
  376. std::vector<uint8_t> request = {{ 0x05, 0x01, 0x00, 0x03, static_cast<uint8_t>(ServerName.Host.length()) }};
  377. std::copy(ServerName.Host.begin(), ServerName.Host.end(), std::back_inserter(request));
  378. request.push_back(portu.b[0]);
  379. request.push_back(portu.b[1]);
  380. APT_WriteOrFail("request", request.data(), request.size());
  381. uint8_t response[4];
  382. APT_ReadOrFail("first part of response", response, sizeof(response));
  383. if (response[0] != 0x05)
  384. return _error->Error("SOCKS proxy %s response with wrong version: %d", ProxyInfo.c_str(), response[0]);
  385. if (response[2] != 0x00)
  386. return _error->Error("SOCKS proxy %s has unexpected non-zero reserved field value: %d", ProxyInfo.c_str(), response[2]);
  387. std::string bindaddr;
  388. if (response[3] == 0x01) // IPv4 address
  389. {
  390. uint8_t ip4port[6];
  391. APT_ReadOrFail("IPv4+Port of response", ip4port, sizeof(ip4port));
  392. portu.b[0] = ip4port[4];
  393. portu.b[1] = ip4port[5];
  394. port = ntohs(*portu.i);
  395. strprintf(bindaddr, "%d.%d.%d.%d:%d", ip4port[0], ip4port[1], ip4port[2], ip4port[3], port);
  396. }
  397. else if (response[3] == 0x03) // hostname
  398. {
  399. uint8_t namelength;
  400. APT_ReadOrFail("hostname length of response", &namelength, 1);
  401. uint8_t hostname[namelength + 2];
  402. APT_ReadOrFail("hostname of response", hostname, sizeof(hostname));
  403. portu.b[0] = hostname[namelength];
  404. portu.b[1] = hostname[namelength + 1];
  405. port = ntohs(*portu.i);
  406. hostname[namelength] = '\0';
  407. strprintf(bindaddr, "%s:%d", hostname, port);
  408. }
  409. else if (response[3] == 0x04) // IPv6 address
  410. {
  411. uint8_t ip6port[18];
  412. APT_ReadOrFail("IPv6+port of response", ip6port, sizeof(ip6port));
  413. portu.b[0] = ip6port[16];
  414. portu.b[1] = ip6port[17];
  415. port = ntohs(*portu.i);
  416. strprintf(bindaddr, "[%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X]:%d",
  417. ip6port[0], ip6port[1], ip6port[2], ip6port[3], ip6port[4], ip6port[5], ip6port[6], ip6port[7],
  418. ip6port[8], ip6port[9], ip6port[10], ip6port[11], ip6port[12], ip6port[13], ip6port[14], ip6port[15],
  419. port);
  420. }
  421. else
  422. return _error->Error("SOCKS proxy %s destination address is of unknown type: %d",
  423. ProxyInfo.c_str(), response[3]);
  424. if (response[1] != 0x00)
  425. {
  426. char const * errstr;
  427. switch (response[1])
  428. {
  429. case 0x01: errstr = "general SOCKS server failure"; Owner->SetFailReason("SOCKS"); break;
  430. case 0x02: errstr = "connection not allowed by ruleset"; Owner->SetFailReason("SOCKS"); break;
  431. case 0x03: errstr = "Network unreachable"; Owner->SetFailReason("ConnectionTimedOut"); break;
  432. case 0x04: errstr = "Host unreachable"; Owner->SetFailReason("ConnectionTimedOut"); break;
  433. case 0x05: errstr = "Connection refused"; Owner->SetFailReason("ConnectionRefused"); break;
  434. case 0x06: errstr = "TTL expired"; Owner->SetFailReason("Timeout"); break;
  435. case 0x07: errstr = "Command not supported"; Owner->SetFailReason("SOCKS"); break;
  436. case 0x08: errstr = "Address type not supported"; Owner->SetFailReason("SOCKS"); break;
  437. default: errstr = "Unknown error"; Owner->SetFailReason("SOCKS"); break;
  438. }
  439. return _error->Error("SOCKS proxy %s didn't grant the connect to %s due to: %s (%d)", ProxyInfo.c_str(), bindaddr.c_str(), errstr, response[1]);
  440. }
  441. else if (Owner->DebugEnabled())
  442. ioprintf(std::clog, "http: SOCKS proxy %s connection established to %s\n", ProxyInfo.c_str(), bindaddr.c_str());
  443. if (WaitFd(ServerFd, true, Timeout) == false)
  444. return _error->Error("SOCKS proxy %s reported connection, but timed out", ProxyInfo.c_str());
  445. #undef APT_ReadOrFail
  446. #undef APT_WriteOrFail
  447. }
  448. else
  449. {
  450. // Determine what host and port to use based on the proxy settings
  451. int Port = 0;
  452. string Host;
  453. if (Proxy.empty() == true || Proxy.Host.empty() == true)
  454. {
  455. if (ServerName.Port != 0)
  456. Port = ServerName.Port;
  457. Host = ServerName.Host;
  458. }
  459. else if (Proxy.Access != "http")
  460. return _error->Error("Unsupported proxy configured: %s", URI::SiteOnly(Proxy).c_str());
  461. else
  462. {
  463. if (Proxy.Port != 0)
  464. Port = Proxy.Port;
  465. Host = Proxy.Host;
  466. }
  467. return Connect(Host,Port,"http",80,ServerFd,TimeOut,Owner);
  468. }
  469. return true;
  470. }
  471. /*}}}*/
  472. // HttpServerState::Close - Close a connection to the server /*{{{*/
  473. // ---------------------------------------------------------------------
  474. /* */
  475. bool HttpServerState::Close()
  476. {
  477. close(ServerFd);
  478. ServerFd = -1;
  479. return true;
  480. }
  481. /*}}}*/
  482. // HttpServerState::RunData - Transfer the data from the socket /*{{{*/
  483. bool HttpServerState::RunData(FileFd * const File)
  484. {
  485. State = Data;
  486. // Chunked transfer encoding is fun..
  487. if (Encoding == Chunked)
  488. {
  489. while (1)
  490. {
  491. // Grab the block size
  492. bool Last = true;
  493. string Data;
  494. In.Limit(-1);
  495. do
  496. {
  497. if (In.WriteTillEl(Data,true) == true)
  498. break;
  499. }
  500. while ((Last = Go(false, File)) == true);
  501. if (Last == false)
  502. return false;
  503. // See if we are done
  504. unsigned long long Len = strtoull(Data.c_str(),0,16);
  505. if (Len == 0)
  506. {
  507. In.Limit(-1);
  508. // We have to remove the entity trailer
  509. Last = true;
  510. do
  511. {
  512. if (In.WriteTillEl(Data,true) == true && Data.length() <= 2)
  513. break;
  514. }
  515. while ((Last = Go(false, File)) == true);
  516. if (Last == false)
  517. return false;
  518. return !_error->PendingError();
  519. }
  520. // Transfer the block
  521. In.Limit(Len);
  522. while (Go(true, File) == true)
  523. if (In.IsLimit() == true)
  524. break;
  525. // Error
  526. if (In.IsLimit() == false)
  527. return false;
  528. // The server sends an extra new line before the next block specifier..
  529. In.Limit(-1);
  530. Last = true;
  531. do
  532. {
  533. if (In.WriteTillEl(Data,true) == true)
  534. break;
  535. }
  536. while ((Last = Go(false, File)) == true);
  537. if (Last == false)
  538. return false;
  539. }
  540. }
  541. else
  542. {
  543. /* Closes encoding is used when the server did not specify a size, the
  544. loss of the connection means we are done */
  545. if (JunkSize != 0)
  546. In.Limit(JunkSize);
  547. else if (DownloadSize != 0)
  548. In.Limit(DownloadSize);
  549. else if (Persistent == false)
  550. In.Limit(-1);
  551. // Just transfer the whole block.
  552. do
  553. {
  554. if (In.IsLimit() == false)
  555. continue;
  556. In.Limit(-1);
  557. return !_error->PendingError();
  558. }
  559. while (Go(true, File) == true);
  560. }
  561. return Owner->Flush() && !_error->PendingError();
  562. }
  563. /*}}}*/
  564. bool HttpServerState::RunDataToDevNull() /*{{{*/
  565. {
  566. FileFd DevNull("/dev/null", FileFd::WriteOnly);
  567. return RunData(&DevNull);
  568. }
  569. /*}}}*/
  570. bool HttpServerState::ReadHeaderLines(std::string &Data) /*{{{*/
  571. {
  572. return In.WriteTillEl(Data);
  573. }
  574. /*}}}*/
  575. bool HttpServerState::LoadNextResponse(bool const ToFile, FileFd * const File)/*{{{*/
  576. {
  577. return Go(ToFile, File);
  578. }
  579. /*}}}*/
  580. bool HttpServerState::WriteResponse(const std::string &Data) /*{{{*/
  581. {
  582. return Out.Read(Data);
  583. }
  584. /*}}}*/
  585. APT_PURE bool HttpServerState::IsOpen() /*{{{*/
  586. {
  587. return (ServerFd != -1);
  588. }
  589. /*}}}*/
  590. bool HttpServerState::InitHashes(HashStringList const &ExpectedHashes) /*{{{*/
  591. {
  592. delete In.Hash;
  593. In.Hash = new Hashes(ExpectedHashes);
  594. return true;
  595. }
  596. /*}}}*/
  597. APT_PURE Hashes * HttpServerState::GetHashes() /*{{{*/
  598. {
  599. return In.Hash;
  600. }
  601. /*}}}*/
  602. // HttpServerState::Die - The server has closed the connection. /*{{{*/
  603. bool HttpServerState::Die(FileFd * const File)
  604. {
  605. unsigned int LErrno = errno;
  606. // Dump the buffer to the file
  607. if (State == ServerState::Data)
  608. {
  609. if (File == nullptr)
  610. return true;
  611. // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
  612. // can't be set
  613. if (File->Name() != "/dev/null")
  614. SetNonBlock(File->Fd(),false);
  615. while (In.WriteSpace() == true)
  616. {
  617. if (In.Write(File->Fd()) == false)
  618. return _error->Errno("write",_("Error writing to the file"));
  619. // Done
  620. if (In.IsLimit() == true)
  621. return true;
  622. }
  623. }
  624. // See if this is because the server finished the data stream
  625. if (In.IsLimit() == false && State != HttpServerState::Header &&
  626. Persistent == true)
  627. {
  628. Close();
  629. if (LErrno == 0)
  630. return _error->Error(_("Error reading from server. Remote end closed connection"));
  631. errno = LErrno;
  632. return _error->Errno("read",_("Error reading from server"));
  633. }
  634. else
  635. {
  636. In.Limit(-1);
  637. // Nothing left in the buffer
  638. if (In.WriteSpace() == false)
  639. return false;
  640. // We may have got multiple responses back in one packet..
  641. Close();
  642. return true;
  643. }
  644. return false;
  645. }
  646. /*}}}*/
  647. // HttpServerState::Flush - Dump the buffer into the file /*{{{*/
  648. // ---------------------------------------------------------------------
  649. /* This takes the current input buffer from the Server FD and writes it
  650. into the file */
  651. bool HttpServerState::Flush(FileFd * const File)
  652. {
  653. if (File != NULL)
  654. {
  655. // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
  656. // can't be set
  657. if (File->Name() != "/dev/null")
  658. SetNonBlock(File->Fd(),false);
  659. if (In.WriteSpace() == false)
  660. return true;
  661. while (In.WriteSpace() == true)
  662. {
  663. if (In.Write(File->Fd()) == false)
  664. return _error->Errno("write",_("Error writing to file"));
  665. if (In.IsLimit() == true)
  666. return true;
  667. }
  668. if (In.IsLimit() == true || Persistent == false)
  669. return true;
  670. }
  671. return false;
  672. }
  673. /*}}}*/
  674. // HttpServerState::Go - Run a single loop /*{{{*/
  675. // ---------------------------------------------------------------------
  676. /* This runs the select loop over the server FDs, Output file FDs and
  677. stdin. */
  678. bool HttpServerState::Go(bool ToFile, FileFd * const File)
  679. {
  680. // Server has closed the connection
  681. if (ServerFd == -1 && (In.WriteSpace() == false ||
  682. ToFile == false))
  683. return false;
  684. fd_set rfds,wfds;
  685. FD_ZERO(&rfds);
  686. FD_ZERO(&wfds);
  687. /* Add the server. We only send more requests if the connection will
  688. be persisting */
  689. if (Out.WriteSpace() == true && ServerFd != -1
  690. && Persistent == true)
  691. FD_SET(ServerFd,&wfds);
  692. if (In.ReadSpace() == true && ServerFd != -1)
  693. FD_SET(ServerFd,&rfds);
  694. // Add the file
  695. int FileFD = -1;
  696. if (File != NULL)
  697. FileFD = File->Fd();
  698. if (In.WriteSpace() == true && ToFile == true && FileFD != -1)
  699. FD_SET(FileFD,&wfds);
  700. // Add stdin
  701. if (Owner->ConfigFindB("DependOnSTDIN", true) == true)
  702. FD_SET(STDIN_FILENO,&rfds);
  703. // Figure out the max fd
  704. int MaxFd = FileFD;
  705. if (MaxFd < ServerFd)
  706. MaxFd = ServerFd;
  707. // Select
  708. struct timeval tv;
  709. tv.tv_sec = TimeOut;
  710. tv.tv_usec = 0;
  711. int Res = 0;
  712. if ((Res = select(MaxFd+1,&rfds,&wfds,0,&tv)) < 0)
  713. {
  714. if (errno == EINTR)
  715. return true;
  716. return _error->Errno("select",_("Select failed"));
  717. }
  718. if (Res == 0)
  719. {
  720. _error->Error(_("Connection timed out"));
  721. return Die(File);
  722. }
  723. // Handle server IO
  724. if (ServerFd != -1 && FD_ISSET(ServerFd,&rfds))
  725. {
  726. errno = 0;
  727. if (In.Read(ServerFd) == false)
  728. return Die(File);
  729. }
  730. if (ServerFd != -1 && FD_ISSET(ServerFd,&wfds))
  731. {
  732. errno = 0;
  733. if (Out.Write(ServerFd) == false)
  734. return Die(File);
  735. }
  736. // Send data to the file
  737. if (FileFD != -1 && FD_ISSET(FileFD,&wfds))
  738. {
  739. if (In.Write(FileFD) == false)
  740. return _error->Errno("write",_("Error writing to output file"));
  741. }
  742. if (MaximumSize > 0 && File && File->Tell() > MaximumSize)
  743. {
  744. Owner->SetFailReason("MaximumSizeExceeded");
  745. return _error->Error("Writing more data than expected (%llu > %llu)",
  746. File->Tell(), MaximumSize);
  747. }
  748. // Handle commands from APT
  749. if (FD_ISSET(STDIN_FILENO,&rfds))
  750. {
  751. if (Owner->Run(true) != -1)
  752. exit(100);
  753. }
  754. return true;
  755. }
  756. /*}}}*/
  757. // HttpMethod::SendReq - Send the HTTP request /*{{{*/
  758. // ---------------------------------------------------------------------
  759. /* This places the http request in the outbound buffer */
  760. void HttpMethod::SendReq(FetchItem *Itm)
  761. {
  762. URI Uri = Itm->Uri;
  763. {
  764. auto const plus = Binary.find('+');
  765. if (plus != std::string::npos)
  766. Uri.Access = Binary.substr(plus + 1);
  767. }
  768. // The HTTP server expects a hostname with a trailing :port
  769. std::stringstream Req;
  770. string ProperHost;
  771. if (Uri.Host.find(':') != string::npos)
  772. ProperHost = '[' + Uri.Host + ']';
  773. else
  774. ProperHost = Uri.Host;
  775. /* RFC 2616 §5.1.2 requires absolute URIs for requests to proxies,
  776. but while its a must for all servers to accept absolute URIs,
  777. it is assumed clients will sent an absolute path for non-proxies */
  778. std::string requesturi;
  779. if (Server->Proxy.Access != "http" || Server->Proxy.empty() == true || Server->Proxy.Host.empty())
  780. requesturi = Uri.Path;
  781. else
  782. requesturi = Uri;
  783. // The "+" is encoded as a workaround for a amazon S3 bug
  784. // see LP bugs #1003633 and #1086997.
  785. requesturi = QuoteString(requesturi, "+~ ");
  786. /* Build the request. No keep-alive is included as it is the default
  787. in 1.1, can cause problems with proxies, and we are an HTTP/1.1
  788. client anyway.
  789. C.f. https://tools.ietf.org/wg/httpbis/trac/ticket/158 */
  790. Req << "GET " << requesturi << " HTTP/1.1\r\n";
  791. if (Uri.Port != 0)
  792. Req << "Host: " << ProperHost << ":" << std::to_string(Uri.Port) << "\r\n";
  793. else
  794. Req << "Host: " << ProperHost << "\r\n";
  795. // generate a cache control header (if needed)
  796. if (ConfigFindB("No-Cache",false) == true)
  797. Req << "Cache-Control: no-cache\r\n"
  798. << "Pragma: no-cache\r\n";
  799. else if (Itm->IndexFile == true)
  800. Req << "Cache-Control: max-age=" << std::to_string(ConfigFindI("Max-Age", 0)) << "\r\n";
  801. else if (ConfigFindB("No-Store", false) == true)
  802. Req << "Cache-Control: no-store\r\n";
  803. // If we ask for uncompressed files servers might respond with content-
  804. // negotiation which lets us end up with compressed files we do not support,
  805. // see 657029, 657560 and co, so if we have no extension on the request
  806. // ask for text only. As a sidenote: If there is nothing to negotate servers
  807. // seem to be nice and ignore it.
  808. if (ConfigFindB("SendAccept", true) == true)
  809. {
  810. size_t const filepos = Itm->Uri.find_last_of('/');
  811. string const file = Itm->Uri.substr(filepos + 1);
  812. if (flExtension(file) == file)
  813. Req << "Accept: text/*\r\n";
  814. }
  815. // Check for a partial file and send if-queries accordingly
  816. struct stat SBuf;
  817. if (stat(Itm->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
  818. Req << "Range: bytes=" << std::to_string(SBuf.st_size) << "-\r\n"
  819. << "If-Range: " << TimeRFC1123(SBuf.st_mtime, false) << "\r\n";
  820. else if (Itm->LastModified != 0)
  821. Req << "If-Modified-Since: " << TimeRFC1123(Itm->LastModified, false).c_str() << "\r\n";
  822. if (Server->Proxy.Access == "http" &&
  823. (Server->Proxy.User.empty() == false || Server->Proxy.Password.empty() == false))
  824. Req << "Proxy-Authorization: Basic "
  825. << Base64Encode(Server->Proxy.User + ":" + Server->Proxy.Password) << "\r\n";
  826. maybe_add_auth (Uri, _config->FindFile("Dir::Etc::netrc"));
  827. if (Uri.User.empty() == false || Uri.Password.empty() == false)
  828. Req << "Authorization: Basic "
  829. << Base64Encode(Uri.User + ":" + Uri.Password) << "\r\n";
  830. Req << "User-Agent: " << ConfigFind("User-Agent",
  831. "Debian APT-HTTP/1.3 (" PACKAGE_VERSION ")") << "\r\n";
  832. Req << "\r\n";
  833. if (Debug == true)
  834. cerr << Req.str() << endl;
  835. Server->WriteResponse(Req.str());
  836. }
  837. /*}}}*/
  838. std::unique_ptr<ServerState> HttpMethod::CreateServerState(URI const &uri)/*{{{*/
  839. {
  840. return std::unique_ptr<ServerState>(new HttpServerState(uri, this));
  841. }
  842. /*}}}*/
  843. void HttpMethod::RotateDNS() /*{{{*/
  844. {
  845. ::RotateDNS();
  846. }
  847. /*}}}*/
  848. ServerMethod::DealWithHeadersResult HttpMethod::DealWithHeaders(FetchResult &Res)/*{{{*/
  849. {
  850. auto ret = ServerMethod::DealWithHeaders(Res);
  851. if (ret != ServerMethod::FILE_IS_OPEN)
  852. return ret;
  853. // Open the file
  854. delete File;
  855. File = new FileFd(Queue->DestFile,FileFd::WriteAny);
  856. if (_error->PendingError() == true)
  857. return ERROR_NOT_FROM_SERVER;
  858. FailFile = Queue->DestFile;
  859. FailFile.c_str(); // Make sure we don't do a malloc in the signal handler
  860. FailFd = File->Fd();
  861. FailTime = Server->Date;
  862. if (Server->InitHashes(Queue->ExpectedHashes) == false || Server->AddPartialFileToHashes(*File) == false)
  863. {
  864. _error->Errno("read",_("Problem hashing file"));
  865. return ERROR_NOT_FROM_SERVER;
  866. }
  867. if (Server->StartPos > 0)
  868. Res.ResumePoint = Server->StartPos;
  869. SetNonBlock(File->Fd(),true);
  870. return FILE_IS_OPEN;
  871. }
  872. /*}}}*/
  873. HttpMethod::HttpMethod(std::string &&pProg) : ServerMethod(pProg.c_str(), "1.2", Pipeline | SendConfig)/*{{{*/
  874. {
  875. auto addName = std::inserter(methodNames, methodNames.begin());
  876. if (Binary != "http")
  877. addName = "http";
  878. auto const plus = Binary.find('+');
  879. if (plus != std::string::npos)
  880. addName = Binary.substr(0, plus);
  881. File = 0;
  882. Server = 0;
  883. }
  884. /*}}}*/