https.cc 12 KB

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