https.cc 16 KB

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