https.cc 17 KB

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