https.cc 15 KB

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