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