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