https.cc 15 KB

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