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