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