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