https.cc 18 KB

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