https.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. long curl_responsecode;
  108. URI Uri = Itm->Uri;
  109. string remotehost = Uri.Host;
  110. // TODO:
  111. // - http::Pipeline-Depth
  112. // - error checking/reporting
  113. // - more debug options? (CURLOPT_DEBUGFUNCTION?)
  114. curl_easy_reset(curl);
  115. SetupProxy();
  116. maybe_add_auth (Uri, _config->FindFile("Dir::Etc::netrc"));
  117. // callbacks
  118. curl_easy_setopt(curl, CURLOPT_URL, static_cast<string>(Uri).c_str());
  119. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
  120. curl_easy_setopt(curl, CURLOPT_WRITEDATA, this);
  121. curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_callback);
  122. curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, this);
  123. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false);
  124. curl_easy_setopt(curl, CURLOPT_FILETIME, true);
  125. // SSL parameters are set by default to the common (non mirror-specific) value
  126. // if available (or a default one) and gets overload by mirror-specific ones.
  127. // File containing the list of trusted CA.
  128. string cainfo = _config->Find("Acquire::https::CaInfo","");
  129. string knob = "Acquire::https::"+remotehost+"::CaInfo";
  130. cainfo = _config->Find(knob.c_str(),cainfo.c_str());
  131. if(cainfo.empty() == false)
  132. curl_easy_setopt(curl, CURLOPT_CAINFO,cainfo.c_str());
  133. // Check server certificate against previous CA list ...
  134. bool peer_verify = _config->FindB("Acquire::https::Verify-Peer",true);
  135. knob = "Acquire::https::" + remotehost + "::Verify-Peer";
  136. peer_verify = _config->FindB(knob.c_str(), peer_verify);
  137. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, peer_verify);
  138. // ... and hostname against cert CN or subjectAltName
  139. bool verify = _config->FindB("Acquire::https::Verify-Host",true);
  140. knob = "Acquire::https::"+remotehost+"::Verify-Host";
  141. verify = _config->FindB(knob.c_str(),verify);
  142. int const default_verify = (verify == true) ? 2 : 0;
  143. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, default_verify);
  144. // Also enforce issuer of server certificate using its cert
  145. string issuercert = _config->Find("Acquire::https::IssuerCert","");
  146. knob = "Acquire::https::"+remotehost+"::IssuerCert";
  147. issuercert = _config->Find(knob.c_str(),issuercert.c_str());
  148. if(issuercert.empty() == false)
  149. curl_easy_setopt(curl, CURLOPT_ISSUERCERT,issuercert.c_str());
  150. // For client authentication, certificate file ...
  151. string pem = _config->Find("Acquire::https::SslCert","");
  152. knob = "Acquire::https::"+remotehost+"::SslCert";
  153. pem = _config->Find(knob.c_str(),pem.c_str());
  154. if(pem.empty() == false)
  155. curl_easy_setopt(curl, CURLOPT_SSLCERT, pem.c_str());
  156. // ... and associated key.
  157. string key = _config->Find("Acquire::https::SslKey","");
  158. knob = "Acquire::https::"+remotehost+"::SslKey";
  159. key = _config->Find(knob.c_str(),key.c_str());
  160. if(key.empty() == false)
  161. curl_easy_setopt(curl, CURLOPT_SSLKEY, key.c_str());
  162. // Allow forcing SSL version to SSLv3 or TLSv1 (SSLv2 is not
  163. // supported by GnuTLS).
  164. long final_version = CURL_SSLVERSION_DEFAULT;
  165. string sslversion = _config->Find("Acquire::https::SslForceVersion","");
  166. knob = "Acquire::https::"+remotehost+"::SslForceVersion";
  167. sslversion = _config->Find(knob.c_str(),sslversion.c_str());
  168. if(sslversion == "TLSv1")
  169. final_version = CURL_SSLVERSION_TLSv1;
  170. else if(sslversion == "SSLv3")
  171. final_version = CURL_SSLVERSION_SSLv3;
  172. curl_easy_setopt(curl, CURLOPT_SSLVERSION, final_version);
  173. // CRL file
  174. string crlfile = _config->Find("Acquire::https::CrlFile","");
  175. knob = "Acquire::https::"+remotehost+"::CrlFile";
  176. crlfile = _config->Find(knob.c_str(),crlfile.c_str());
  177. if(crlfile.empty() == false)
  178. curl_easy_setopt(curl, CURLOPT_CRLFILE, crlfile.c_str());
  179. // cache-control
  180. if(_config->FindB("Acquire::https::No-Cache",
  181. _config->FindB("Acquire::http::No-Cache",false)) == false)
  182. {
  183. // cache enabled
  184. if (_config->FindB("Acquire::https::No-Store",
  185. _config->FindB("Acquire::http::No-Store",false)) == true)
  186. headers = curl_slist_append(headers,"Cache-Control: no-store");
  187. stringstream ss;
  188. ioprintf(ss, "Cache-Control: max-age=%u", _config->FindI("Acquire::https::Max-Age",
  189. _config->FindI("Acquire::http::Max-Age",0)));
  190. headers = curl_slist_append(headers, ss.str().c_str());
  191. } else {
  192. // cache disabled by user
  193. headers = curl_slist_append(headers, "Cache-Control: no-cache");
  194. headers = curl_slist_append(headers, "Pragma: no-cache");
  195. }
  196. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  197. // speed limit
  198. int const dlLimit = _config->FindI("Acquire::https::Dl-Limit",
  199. _config->FindI("Acquire::http::Dl-Limit",0))*1024;
  200. if (dlLimit > 0)
  201. curl_easy_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE, dlLimit);
  202. // set header
  203. curl_easy_setopt(curl, CURLOPT_USERAGENT,
  204. _config->Find("Acquire::https::User-Agent",
  205. _config->Find("Acquire::http::User-Agent",
  206. "Debian APT-CURL/1.0 (" PACKAGE_VERSION ")").c_str()).c_str());
  207. // set timeout
  208. int const timeout = _config->FindI("Acquire::https::Timeout",
  209. _config->FindI("Acquire::http::Timeout",120));
  210. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, timeout);
  211. //set really low lowspeed timeout (see #497983)
  212. curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, DL_MIN_SPEED);
  213. curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, timeout);
  214. // set redirect options and default to 10 redirects
  215. bool const AllowRedirect = _config->FindB("Acquire::https::AllowRedirect",
  216. _config->FindB("Acquire::http::AllowRedirect",true));
  217. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, AllowRedirect);
  218. curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 10);
  219. // debug
  220. if(_config->FindB("Debug::Acquire::https", false))
  221. curl_easy_setopt(curl, CURLOPT_VERBOSE, true);
  222. // error handling
  223. curl_errorstr[0] = '\0';
  224. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_errorstr);
  225. // If we ask for uncompressed files servers might respond with content-
  226. // negotation which lets us end up with compressed files we do not support,
  227. // see 657029, 657560 and co, so if we have no extension on the request
  228. // ask for text only. As a sidenote: If there is nothing to negotate servers
  229. // seem to be nice and ignore it.
  230. if (_config->FindB("Acquire::https::SendAccept", _config->FindB("Acquire::http::SendAccept", true)) == true)
  231. {
  232. size_t const filepos = Itm->Uri.find_last_of('/');
  233. string const file = Itm->Uri.substr(filepos + 1);
  234. if (flExtension(file) == file)
  235. headers = curl_slist_append(headers, "Accept: text/*");
  236. }
  237. // if we have the file send an if-range query with a range header
  238. if (stat(Itm->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
  239. {
  240. char Buf[1000];
  241. sprintf(Buf, "Range: bytes=%li-", (long) SBuf.st_size - 1);
  242. headers = curl_slist_append(headers, Buf);
  243. sprintf(Buf, "If-Range: %s", TimeRFC1123(SBuf.st_mtime).c_str());
  244. headers = curl_slist_append(headers, Buf);
  245. }
  246. else if(Itm->LastModified > 0)
  247. {
  248. curl_easy_setopt(curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
  249. curl_easy_setopt(curl, CURLOPT_TIMEVALUE, Itm->LastModified);
  250. }
  251. // go for it - if the file exists, append on it
  252. File = new FileFd(Itm->DestFile, FileFd::WriteAny);
  253. if (File->Size() > 0)
  254. File->Seek(File->Size() - 1);
  255. // keep apt updated
  256. Res.Filename = Itm->DestFile;
  257. // get it!
  258. CURLcode success = curl_easy_perform(curl);
  259. curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &curl_responsecode);
  260. long curl_servdate;
  261. curl_easy_getinfo(curl, CURLINFO_FILETIME, &curl_servdate);
  262. // If the server returns 200 OK but the If-Modified-Since condition is not
  263. // met, CURLINFO_CONDITION_UNMET will be set to 1
  264. long curl_condition_unmet = 0;
  265. curl_easy_getinfo(curl, CURLINFO_CONDITION_UNMET, &curl_condition_unmet);
  266. File->Close();
  267. // cleanup
  268. if(success != 0 || (curl_responsecode != 200 && curl_responsecode != 304))
  269. {
  270. _error->Error("%s", curl_errorstr);
  271. // unlink, no need keep 401/404 page content in partial/
  272. unlink(File->Name().c_str());
  273. Fail();
  274. return true;
  275. }
  276. // Timestamp
  277. struct utimbuf UBuf;
  278. if (curl_servdate != -1) {
  279. UBuf.actime = curl_servdate;
  280. UBuf.modtime = curl_servdate;
  281. utime(File->Name().c_str(),&UBuf);
  282. }
  283. // check the downloaded result
  284. struct stat Buf;
  285. if (stat(File->Name().c_str(),&Buf) == 0)
  286. {
  287. Res.Filename = File->Name();
  288. Res.LastModified = Buf.st_mtime;
  289. Res.IMSHit = false;
  290. if (curl_responsecode == 304 || curl_condition_unmet)
  291. {
  292. unlink(File->Name().c_str());
  293. Res.IMSHit = true;
  294. Res.LastModified = Itm->LastModified;
  295. Res.Size = 0;
  296. URIDone(Res);
  297. return true;
  298. }
  299. Res.Size = Buf.st_size;
  300. }
  301. // take hashes
  302. Hashes Hash;
  303. FileFd Fd(Res.Filename, FileFd::ReadOnly);
  304. Hash.AddFD(Fd);
  305. Res.TakeHashes(Hash);
  306. // keep apt updated
  307. URIDone(Res);
  308. // cleanup
  309. Res.Size = 0;
  310. delete File;
  311. curl_slist_free_all(headers);
  312. return true;
  313. };
  314. int main()
  315. {
  316. setlocale(LC_ALL, "");
  317. HttpsMethod Mth;
  318. curl_global_init(CURL_GLOBAL_SSL) ;
  319. return Mth.Run();
  320. }