https.cc 16 KB

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