https.cc 15 KB

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