https.cc 15 KB

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