https.cc 14 KB

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