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