https.cc 15 KB

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