https.cc 15 KB

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