https.cc 16 KB

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