You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

542 lines
18 KiB

  1. //-*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: http.cc,v 1.59 2004/05/08 19:42:35 mdz Exp $
  4. /* ######################################################################
  5. HTTPS Acquire Method - This is the HTTPS acquire method for APT.
  6. It uses libcurl
  7. ##################################################################### */
  8. /*}}}*/
  9. // Include Files /*{{{*/
  10. #include <config.h>
  11. #include <apt-pkg/fileutl.h>
  12. #include <apt-pkg/error.h>
  13. #include <apt-pkg/hashes.h>
  14. #include <apt-pkg/netrc.h>
  15. #include <apt-pkg/configuration.h>
  16. #include <apt-pkg/macros.h>
  17. #include <apt-pkg/strutl.h>
  18. #include <apt-pkg/proxy.h>
  19. #include <sys/stat.h>
  20. #include <sys/time.h>
  21. #include <unistd.h>
  22. #include <stdio.h>
  23. #include <ctype.h>
  24. #include <stdlib.h>
  25. #include <array>
  26. #include <iostream>
  27. #include <sstream>
  28. #include "https.h"
  29. #include <apti18n.h>
  30. /*}}}*/
  31. using namespace std;
  32. struct APT_HIDDEN CURLUserPointer {
  33. HttpsMethod * const https;
  34. HttpsMethod::FetchResult * const Res;
  35. HttpsMethod::FetchItem const * const Itm;
  36. CURLUserPointer(HttpsMethod * const https, HttpsMethod::FetchResult * const Res,
  37. HttpsMethod::FetchItem const * const Itm) : https(https), Res(Res), Itm(Itm) {}
  38. };
  39. size_t
  40. HttpsMethod::parse_header(void *buffer, size_t size, size_t nmemb, void *userp)
  41. {
  42. size_t len = size * nmemb;
  43. CURLUserPointer *me = static_cast<CURLUserPointer *>(userp);
  44. std::string line((char*) buffer, len);
  45. for (--len; len > 0; --len)
  46. if (isspace_ascii(line[len]) == 0)
  47. {
  48. ++len;
  49. break;
  50. }
  51. line.erase(len);
  52. if (line.empty() == true)
  53. {
  54. me->https->Server->JunkSize = 0;
  55. if (me->https->Server->Result != 416 && me->https->Server->StartPos != 0)
  56. ;
  57. else if (me->https->Server->Result == 416)
  58. {
  59. bool partialHit = false;
  60. if (me->Itm->ExpectedHashes.usable() == true)
  61. {
  62. Hashes resultHashes(me->Itm->ExpectedHashes);
  63. FileFd file(me->Itm->DestFile, FileFd::ReadOnly);
  64. me->https->Server->TotalFileSize = file.FileSize();
  65. me->https->Server->Date = file.ModificationTime();
  66. resultHashes.AddFD(file);
  67. HashStringList const hashList = resultHashes.GetHashStringList();
  68. partialHit = (me->Itm->ExpectedHashes == hashList);
  69. }
  70. else if (me->https->Server->Result == 416 && me->https->Server->TotalFileSize == me->https->File->FileSize())
  71. partialHit = true;
  72. if (partialHit == true)
  73. {
  74. me->https->Server->Result = 200;
  75. me->https->Server->StartPos = me->https->Server->TotalFileSize;
  76. // the actual size is not important for https as curl will deal with it
  77. // by itself and e.g. doesn't bother us with transport-encoding…
  78. me->https->Server->JunkSize = std::numeric_limits<unsigned long long>::max();
  79. }
  80. else
  81. me->https->Server->StartPos = 0;
  82. }
  83. else
  84. me->https->Server->StartPos = 0;
  85. me->Res->LastModified = me->https->Server->Date;
  86. me->Res->Size = me->https->Server->TotalFileSize;
  87. me->Res->ResumePoint = me->https->Server->StartPos;
  88. // we expect valid data, so tell our caller we get the file now
  89. if (me->https->Server->Result >= 200 && me->https->Server->Result < 300)
  90. {
  91. if (me->Res->Size != 0 && me->Res->Size > me->Res->ResumePoint)
  92. me->https->URIStart(*me->Res);
  93. if (me->https->Server->AddPartialFileToHashes(*(me->https->File)) == false)
  94. return 0;
  95. }
  96. else
  97. me->https->Server->JunkSize = std::numeric_limits<decltype(me->https->Server->JunkSize)>::max();
  98. }
  99. else if (me->https->Server->HeaderLine(line) == false)
  100. return 0;
  101. return size*nmemb;
  102. }
  103. size_t
  104. HttpsMethod::write_data(void *buffer, size_t size, size_t nmemb, void *userp)
  105. {
  106. HttpsMethod *me = static_cast<HttpsMethod *>(userp);
  107. size_t buffer_size = size * nmemb;
  108. // we don't need to count the junk here, just drop anything we get as
  109. // we don't always know how long it would be, e.g. in chunked encoding.
  110. if (me->Server->JunkSize != 0)
  111. return buffer_size;
  112. if(me->File->Write(buffer, buffer_size) != true)
  113. return 0;
  114. if(me->Queue->MaximumSize > 0)
  115. {
  116. unsigned long long const TotalWritten = me->File->Tell();
  117. if (TotalWritten > me->Queue->MaximumSize)
  118. {
  119. me->SetFailReason("MaximumSizeExceeded");
  120. _error->Error("Writing more data than expected (%llu > %llu)",
  121. TotalWritten, me->Queue->MaximumSize);
  122. return 0;
  123. }
  124. }
  125. if (me->Server->GetHashes()->Add((unsigned char const * const)buffer, buffer_size) == false)
  126. return 0;
  127. return buffer_size;
  128. }
  129. // HttpsServerState::HttpsServerState - Constructor /*{{{*/
  130. HttpsServerState::HttpsServerState(URI Srv,HttpsMethod * Owner) : ServerState(Srv, Owner), Hash(NULL)
  131. {
  132. TimeOut = Owner->ConfigFindI("Timeout", TimeOut);
  133. Reset();
  134. }
  135. /*}}}*/
  136. bool HttpsServerState::InitHashes(HashStringList const &ExpectedHashes) /*{{{*/
  137. {
  138. delete Hash;
  139. Hash = new Hashes(ExpectedHashes);
  140. return true;
  141. }
  142. /*}}}*/
  143. APT_PURE Hashes * HttpsServerState::GetHashes() /*{{{*/
  144. {
  145. return Hash;
  146. }
  147. /*}}}*/
  148. bool HttpsMethod::SetupProxy() /*{{{*/
  149. {
  150. URI ServerName = Queue->Uri;
  151. // Determine the proxy setting
  152. AutoDetectProxy(ServerName);
  153. // Curl should never read proxy settings from the environment, as
  154. // we determine which proxy to use. Do this for consistency among
  155. // methods and prevent an environment variable overriding a
  156. // no-proxy ("DIRECT") setting in apt.conf.
  157. curl_easy_setopt(curl, CURLOPT_PROXY, "");
  158. // Determine the proxy setting - try https first, fallback to http and use env at last
  159. string UseProxy = ConfigFind("Proxy::" + ServerName.Host, "");
  160. if (UseProxy.empty() == true)
  161. UseProxy = ConfigFind("Proxy", "");
  162. // User wants to use NO proxy, so nothing to setup
  163. if (UseProxy == "DIRECT")
  164. return true;
  165. // Parse no_proxy, a comma (,) separated list of domains we don't want to use
  166. // a proxy for so we stop right here if it is in the list
  167. if (getenv("no_proxy") != 0 && CheckDomainList(ServerName.Host,getenv("no_proxy")) == true)
  168. return true;
  169. if (UseProxy.empty() == true)
  170. {
  171. const char* result = nullptr;
  172. if (std::find(methodNames.begin(), methodNames.end(), "https") != methodNames.end())
  173. result = getenv("https_proxy");
  174. // FIXME: Fall back to http_proxy is to remain compatible with
  175. // existing setups and behaviour of apt.conf. This should be
  176. // deprecated in the future (including apt.conf). Most other
  177. // programs do not fall back to http proxy settings and neither
  178. // should Apt.
  179. if (result == nullptr && std::find(methodNames.begin(), methodNames.end(), "http") != methodNames.end())
  180. result = getenv("http_proxy");
  181. UseProxy = result == nullptr ? "" : result;
  182. }
  183. // Determine what host and port to use based on the proxy settings
  184. if (UseProxy.empty() == false)
  185. {
  186. Proxy = UseProxy;
  187. AddProxyAuth(Proxy, ServerName);
  188. if (Proxy.Access == "socks5h")
  189. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
  190. else if (Proxy.Access == "socks5")
  191. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  192. else if (Proxy.Access == "socks4a")
  193. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
  194. else if (Proxy.Access == "socks")
  195. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  196. else if (Proxy.Access == "http" || Proxy.Access == "https")
  197. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
  198. else
  199. return false;
  200. if (Proxy.Port != 1)
  201. curl_easy_setopt(curl, CURLOPT_PROXYPORT, Proxy.Port);
  202. curl_easy_setopt(curl, CURLOPT_PROXY, Proxy.Host.c_str());
  203. if (Proxy.User.empty() == false || Proxy.Password.empty() == false)
  204. {
  205. curl_easy_setopt(curl, CURLOPT_PROXYUSERNAME, Proxy.User.c_str());
  206. curl_easy_setopt(curl, CURLOPT_PROXYPASSWORD, Proxy.Password.c_str());
  207. }
  208. }
  209. return true;
  210. } /*}}}*/
  211. // HttpsMethod::Fetch - Fetch an item /*{{{*/
  212. // ---------------------------------------------------------------------
  213. /* This adds an item to the pipeline. We keep the pipeline at a fixed
  214. depth. */
  215. bool HttpsMethod::Fetch(FetchItem *Itm)
  216. {
  217. struct stat SBuf;
  218. struct curl_slist *headers=NULL;
  219. char curl_errorstr[CURL_ERROR_SIZE];
  220. URI Uri = Itm->Uri;
  221. setPostfixForMethodNames(Uri.Host.c_str());
  222. AllowRedirect = ConfigFindB("AllowRedirect", true);
  223. Debug = DebugEnabled();
  224. // TODO:
  225. // - http::Pipeline-Depth
  226. // - error checking/reporting
  227. // - more debug options? (CURLOPT_DEBUGFUNCTION?)
  228. {
  229. auto const plus = Binary.find('+');
  230. if (plus != std::string::npos)
  231. Uri.Access = Binary.substr(plus + 1);
  232. }
  233. curl_easy_reset(curl);
  234. if (SetupProxy() == false)
  235. return _error->Error("Unsupported proxy configured: %s", URI::SiteOnly(Proxy).c_str());
  236. maybe_add_auth (Uri, _config->FindFile("Dir::Etc::netrc"));
  237. FetchResult Res;
  238. CURLUserPointer userp(this, &Res, Itm);
  239. // callbacks
  240. curl_easy_setopt(curl, CURLOPT_URL, static_cast<string>(Uri).c_str());
  241. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, parse_header);
  242. curl_easy_setopt(curl, CURLOPT_WRITEHEADER, &userp);
  243. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
  244. curl_easy_setopt(curl, CURLOPT_WRITEDATA, this);
  245. // options
  246. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, true);
  247. curl_easy_setopt(curl, CURLOPT_FILETIME, true);
  248. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 0);
  249. if (std::find(methodNames.begin(), methodNames.end(), "https") != methodNames.end())
  250. {
  251. curl_easy_setopt(curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
  252. curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS);
  253. // File containing the list of trusted CA.
  254. std::string const cainfo = ConfigFind("CaInfo", "");
  255. if(cainfo.empty() == false)
  256. curl_easy_setopt(curl, CURLOPT_CAINFO, cainfo.c_str());
  257. // Check server certificate against previous CA list ...
  258. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, ConfigFindB("Verify-Peer", true) ? 1 : 0);
  259. // ... and hostname against cert CN or subjectAltName
  260. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, ConfigFindB("Verify-Host", true) ? 2 : 0);
  261. // Also enforce issuer of server certificate using its cert
  262. std::string const issuercert = ConfigFind("IssuerCert", "");
  263. if(issuercert.empty() == false)
  264. curl_easy_setopt(curl, CURLOPT_ISSUERCERT, issuercert.c_str());
  265. // For client authentication, certificate file ...
  266. std::string const pem = ConfigFind("SslCert", "");
  267. if(pem.empty() == false)
  268. curl_easy_setopt(curl, CURLOPT_SSLCERT, pem.c_str());
  269. // ... and associated key.
  270. std::string const key = ConfigFind("SslKey", "");
  271. if(key.empty() == false)
  272. curl_easy_setopt(curl, CURLOPT_SSLKEY, key.c_str());
  273. // Allow forcing SSL version to SSLv3 or TLSv1
  274. long final_version = CURL_SSLVERSION_DEFAULT;
  275. std::string const sslversion = ConfigFind("SslForceVersion", "");
  276. if(sslversion == "TLSv1")
  277. final_version = CURL_SSLVERSION_TLSv1;
  278. else if(sslversion == "TLSv1.0")
  279. final_version = CURL_SSLVERSION_TLSv1_0;
  280. else if(sslversion == "TLSv1.1")
  281. final_version = CURL_SSLVERSION_TLSv1_1;
  282. else if(sslversion == "TLSv1.2")
  283. final_version = CURL_SSLVERSION_TLSv1_2;
  284. else if(sslversion == "SSLv3")
  285. final_version = CURL_SSLVERSION_SSLv3;
  286. curl_easy_setopt(curl, CURLOPT_SSLVERSION, final_version);
  287. // CRL file
  288. std::string const crlfile = ConfigFind("CrlFile", "");
  289. if(crlfile.empty() == false)
  290. curl_easy_setopt(curl, CURLOPT_CRLFILE, crlfile.c_str());
  291. }
  292. else
  293. {
  294. curl_easy_setopt(curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTP);
  295. curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP);
  296. }
  297. // cache-control
  298. if(ConfigFindB("No-Cache", false) == false)
  299. {
  300. // cache enabled
  301. if (ConfigFindB("No-Store", false) == true)
  302. headers = curl_slist_append(headers,"Cache-Control: no-store");
  303. std::string ss;
  304. strprintf(ss, "Cache-Control: max-age=%u", ConfigFindI("Max-Age", 0));
  305. headers = curl_slist_append(headers, ss.c_str());
  306. } else {
  307. // cache disabled by user
  308. headers = curl_slist_append(headers, "Cache-Control: no-cache");
  309. headers = curl_slist_append(headers, "Pragma: no-cache");
  310. }
  311. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  312. // speed limit
  313. int const dlLimit = ConfigFindI("Dl-Limit", 0) * 1024;
  314. if (dlLimit > 0)
  315. curl_easy_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE, dlLimit);
  316. // set header
  317. curl_easy_setopt(curl, CURLOPT_USERAGENT, ConfigFind("User-Agent", "Debian APT-CURL/1.0 (" PACKAGE_VERSION ")").c_str());
  318. // set timeout
  319. int const timeout = ConfigFindI("Timeout", 120);
  320. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, timeout);
  321. //set really low lowspeed timeout (see #497983)
  322. curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, DL_MIN_SPEED);
  323. curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, timeout);
  324. // debug
  325. if (Debug == true)
  326. curl_easy_setopt(curl, CURLOPT_VERBOSE, true);
  327. // error handling
  328. curl_errorstr[0] = '\0';
  329. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_errorstr);
  330. // If we ask for uncompressed files servers might respond with content-
  331. // negotiation which lets us end up with compressed files we do not support,
  332. // see 657029, 657560 and co, so if we have no extension on the request
  333. // ask for text only. As a sidenote: If there is nothing to negotate servers
  334. // seem to be nice and ignore it.
  335. if (ConfigFindB("SendAccept", true))
  336. {
  337. size_t const filepos = Itm->Uri.find_last_of('/');
  338. string const file = Itm->Uri.substr(filepos + 1);
  339. if (flExtension(file) == file)
  340. headers = curl_slist_append(headers, "Accept: text/*");
  341. }
  342. // go for it - if the file exists, append on it
  343. File = new FileFd(Itm->DestFile, FileFd::WriteAny);
  344. if (Server == nullptr || Server->Comp(Itm->Uri) == false)
  345. Server = CreateServerState(Itm->Uri);
  346. else
  347. Server->Reset(false);
  348. // if we have the file send an if-range query with a range header
  349. if (Server->RangesAllowed && stat(Itm->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
  350. {
  351. std::string Buf;
  352. strprintf(Buf, "Range: bytes=%lli-", (long long) SBuf.st_size);
  353. headers = curl_slist_append(headers, Buf.c_str());
  354. strprintf(Buf, "If-Range: %s", TimeRFC1123(SBuf.st_mtime, false).c_str());
  355. headers = curl_slist_append(headers, Buf.c_str());
  356. }
  357. else if(Itm->LastModified > 0)
  358. {
  359. curl_easy_setopt(curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
  360. curl_easy_setopt(curl, CURLOPT_TIMEVALUE, Itm->LastModified);
  361. }
  362. if (Server->InitHashes(Itm->ExpectedHashes) == false)
  363. return false;
  364. // keep apt updated
  365. Res.Filename = Itm->DestFile;
  366. // get it!
  367. CURLcode success = curl_easy_perform(curl);
  368. // If the server returns 200 OK but the If-Modified-Since condition is not
  369. // met, CURLINFO_CONDITION_UNMET will be set to 1
  370. long curl_condition_unmet = 0;
  371. curl_easy_getinfo(curl, CURLINFO_CONDITION_UNMET, &curl_condition_unmet);
  372. if (curl_condition_unmet == 1)
  373. Server->Result = 304;
  374. File->Close();
  375. curl_slist_free_all(headers);
  376. // cleanup
  377. if (success != CURLE_OK)
  378. {
  379. #pragma GCC diagnostic push
  380. #pragma GCC diagnostic ignored "-Wswitch"
  381. switch (success)
  382. {
  383. case CURLE_COULDNT_RESOLVE_PROXY:
  384. case CURLE_COULDNT_RESOLVE_HOST:
  385. SetFailReason("ResolveFailure");
  386. break;
  387. case CURLE_COULDNT_CONNECT:
  388. SetFailReason("ConnectionRefused");
  389. break;
  390. case CURLE_OPERATION_TIMEDOUT:
  391. SetFailReason("Timeout");
  392. break;
  393. }
  394. #pragma GCC diagnostic pop
  395. // only take curls technical errors if we haven't our own
  396. // (e.g. for the maximum size limit we have and curls can be confusing)
  397. if (_error->PendingError() == false)
  398. _error->Error("%s", curl_errorstr);
  399. else
  400. _error->Warning("curl: %s", curl_errorstr);
  401. return false;
  402. }
  403. switch (DealWithHeaders(Res))
  404. {
  405. case ServerMethod::IMS_HIT:
  406. URIDone(Res);
  407. break;
  408. case ServerMethod::ERROR_WITH_CONTENT_PAGE:
  409. // unlink, no need keep 401/404 page content in partial/
  410. RemoveFile(Binary.c_str(), File->Name());
  411. case ServerMethod::ERROR_UNRECOVERABLE:
  412. case ServerMethod::ERROR_NOT_FROM_SERVER:
  413. return false;
  414. case ServerMethod::TRY_AGAIN_OR_REDIRECT:
  415. Redirect(NextURI);
  416. break;
  417. case ServerMethod::FILE_IS_OPEN:
  418. struct stat resultStat;
  419. if (unlikely(stat(File->Name().c_str(), &resultStat) != 0))
  420. {
  421. _error->Errno("stat", "Unable to access file %s", File->Name().c_str());
  422. return false;
  423. }
  424. Res.Size = resultStat.st_size;
  425. // Timestamp
  426. curl_easy_getinfo(curl, CURLINFO_FILETIME, &Res.LastModified);
  427. if (Res.LastModified != -1)
  428. {
  429. struct timeval times[2];
  430. times[0].tv_sec = Res.LastModified;
  431. times[1].tv_sec = Res.LastModified;
  432. times[0].tv_usec = times[1].tv_usec = 0;
  433. utimes(File->Name().c_str(), times);
  434. }
  435. else
  436. Res.LastModified = resultStat.st_mtime;
  437. // take hashes
  438. Res.TakeHashes(*(Server->GetHashes()));
  439. // keep apt updated
  440. URIDone(Res);
  441. break;
  442. }
  443. delete File;
  444. return true;
  445. }
  446. /*}}}*/
  447. std::unique_ptr<ServerState> HttpsMethod::CreateServerState(URI const &uri)/*{{{*/
  448. {
  449. return std::unique_ptr<ServerState>(new HttpsServerState(uri, this));
  450. }
  451. /*}}}*/
  452. HttpsMethod::HttpsMethod(std::string &&pProg) : ServerMethod(std::move(pProg),"1.2",Pipeline | SendConfig)/*{{{*/
  453. {
  454. auto addName = std::inserter(methodNames, methodNames.begin());
  455. addName = "http";
  456. auto const plus = Binary.find('+');
  457. if (plus != std::string::npos)
  458. {
  459. addName = Binary.substr(plus + 1);
  460. auto base = Binary.substr(0, plus);
  461. if (base != "https")
  462. addName = base;
  463. }
  464. if (std::find(methodNames.begin(), methodNames.end(), "https") != methodNames.end())
  465. curl_global_init(CURL_GLOBAL_SSL);
  466. else
  467. curl_global_init(CURL_GLOBAL_NOTHING);
  468. curl = curl_easy_init();
  469. }
  470. /*}}}*/
  471. HttpsMethod::~HttpsMethod() /*{{{*/
  472. {
  473. curl_easy_cleanup(curl);
  474. }
  475. /*}}}*/
  476. int main(int, const char *argv[]) /*{{{*/
  477. {
  478. std::string Binary = flNotDir(argv[0]);
  479. if (Binary.find('+') == std::string::npos && Binary != "https")
  480. Binary.append("+https");
  481. return HttpsMethod(std::move(Binary)).Run();
  482. }
  483. /*}}}*/