1 //-*- mode: cpp; mode: fold -*-
3 // $Id: http.cc,v 1.59 2004/05/08 19:42:35 mdz Exp $
4 /* ######################################################################
6 HTTPS Acquire Method - This is the HTTPS acquire method for APT.
10 ##################################################################### */
12 // Include Files /*{{{*/
15 #include <apt-pkg/fileutl.h>
16 #include <apt-pkg/error.h>
17 #include <apt-pkg/hashes.h>
18 #include <apt-pkg/netrc.h>
19 #include <apt-pkg/configuration.h>
20 #include <apt-pkg/macros.h>
21 #include <apt-pkg/strutl.h>
22 #include <apt-pkg/proxy.h>
39 struct APT_HIDDEN CURLUserPointer
{
40 HttpsMethod
* const https
;
41 HttpsMethod::FetchResult
* const Res
;
42 HttpsMethod::FetchItem
const * const Itm
;
43 CURLUserPointer(HttpsMethod
* const https
, HttpsMethod::FetchResult
* const Res
,
44 HttpsMethod::FetchItem
const * const Itm
) : https(https
), Res(Res
), Itm(Itm
) {}
48 HttpsMethod::parse_header(void *buffer
, size_t size
, size_t nmemb
, void *userp
)
50 size_t len
= size
* nmemb
;
51 CURLUserPointer
*me
= static_cast<CURLUserPointer
*>(userp
);
52 std::string
line((char*) buffer
, len
);
53 for (--len
; len
> 0; --len
)
54 if (isspace_ascii(line
[len
]) == 0)
61 if (line
.empty() == true)
63 me
->https
->Server
->JunkSize
= 0;
64 if (me
->https
->Server
->Result
!= 416 && me
->https
->Server
->StartPos
!= 0)
66 else if (me
->https
->Server
->Result
== 416)
68 bool partialHit
= false;
69 if (me
->Itm
->ExpectedHashes
.usable() == true)
71 Hashes
resultHashes(me
->Itm
->ExpectedHashes
);
72 FileFd
file(me
->Itm
->DestFile
, FileFd::ReadOnly
);
73 me
->https
->Server
->TotalFileSize
= file
.FileSize();
74 me
->https
->Server
->Date
= file
.ModificationTime();
75 resultHashes
.AddFD(file
);
76 HashStringList
const hashList
= resultHashes
.GetHashStringList();
77 partialHit
= (me
->Itm
->ExpectedHashes
== hashList
);
79 else if (me
->https
->Server
->Result
== 416 && me
->https
->Server
->TotalFileSize
== me
->https
->File
->FileSize())
82 if (partialHit
== true)
84 me
->https
->Server
->Result
= 200;
85 me
->https
->Server
->StartPos
= me
->https
->Server
->TotalFileSize
;
86 // the actual size is not important for https as curl will deal with it
87 // by itself and e.g. doesn't bother us with transport-encoding…
88 me
->https
->Server
->JunkSize
= std::numeric_limits
<unsigned long long>::max();
91 me
->https
->Server
->StartPos
= 0;
94 me
->https
->Server
->StartPos
= 0;
96 me
->Res
->LastModified
= me
->https
->Server
->Date
;
97 me
->Res
->Size
= me
->https
->Server
->TotalFileSize
;
98 me
->Res
->ResumePoint
= me
->https
->Server
->StartPos
;
100 // we expect valid data, so tell our caller we get the file now
101 if (me
->https
->Server
->Result
>= 200 && me
->https
->Server
->Result
< 300)
103 if (me
->Res
->Size
!= 0 && me
->Res
->Size
> me
->Res
->ResumePoint
)
104 me
->https
->URIStart(*me
->Res
);
105 if (me
->https
->Server
->AddPartialFileToHashes(*(me
->https
->File
)) == false)
109 me
->https
->Server
->JunkSize
= std::numeric_limits
<decltype(me
->https
->Server
->JunkSize
)>::max();
111 else if (me
->https
->Server
->HeaderLine(line
) == false)
118 HttpsMethod::write_data(void *buffer
, size_t size
, size_t nmemb
, void *userp
)
120 HttpsMethod
*me
= static_cast<HttpsMethod
*>(userp
);
121 size_t buffer_size
= size
* nmemb
;
122 // we don't need to count the junk here, just drop anything we get as
123 // we don't always know how long it would be, e.g. in chunked encoding.
124 if (me
->Server
->JunkSize
!= 0)
127 if(me
->File
->Write(buffer
, buffer_size
) != true)
130 if(me
->Queue
->MaximumSize
> 0)
132 unsigned long long const TotalWritten
= me
->File
->Tell();
133 if (TotalWritten
> me
->Queue
->MaximumSize
)
135 me
->SetFailReason("MaximumSizeExceeded");
136 _error
->Error("Writing more data than expected (%llu > %llu)",
137 TotalWritten
, me
->Queue
->MaximumSize
);
142 if (me
->Server
->GetHashes()->Add((unsigned char const * const)buffer
, buffer_size
) == false)
148 // HttpsServerState::HttpsServerState - Constructor /*{{{*/
149 HttpsServerState::HttpsServerState(URI Srv
,HttpsMethod
* Owner
) : ServerState(Srv
, Owner
), Hash(NULL
)
151 TimeOut
= _config
->FindI("Acquire::https::Timeout",TimeOut
);
155 bool HttpsServerState::InitHashes(HashStringList
const &ExpectedHashes
) /*{{{*/
158 Hash
= new Hashes(ExpectedHashes
);
162 APT_PURE Hashes
* HttpsServerState::GetHashes() /*{{{*/
168 bool HttpsMethod::SetupProxy() /*{{{*/
170 URI ServerName
= Queue
->Uri
;
172 // Determine the proxy setting
173 AutoDetectProxy(ServerName
);
175 // Curl should never read proxy settings from the environment, as
176 // we determine which proxy to use. Do this for consistency among
177 // methods and prevent an environment variable overriding a
178 // no-proxy ("DIRECT") setting in apt.conf.
179 curl_easy_setopt(curl
, CURLOPT_PROXY
, "");
181 // Determine the proxy setting - try https first, fallback to http and use env at last
182 string UseProxy
= _config
->Find("Acquire::https::Proxy::" + ServerName
.Host
,
183 _config
->Find("Acquire::http::Proxy::" + ServerName
.Host
).c_str());
185 if (UseProxy
.empty() == true)
186 UseProxy
= _config
->Find("Acquire::https::Proxy", _config
->Find("Acquire::http::Proxy").c_str());
188 // User want to use NO proxy, so nothing to setup
189 if (UseProxy
== "DIRECT")
192 // Parse no_proxy, a comma (,) separated list of domains we don't want to use
193 // a proxy for so we stop right here if it is in the list
194 if (getenv("no_proxy") != 0 && CheckDomainList(ServerName
.Host
,getenv("no_proxy")) == true)
197 if (UseProxy
.empty() == true)
199 const char* result
= getenv("https_proxy");
200 // FIXME: Fall back to http_proxy is to remain compatible with
201 // existing setups and behaviour of apt.conf. This should be
202 // deprecated in the future (including apt.conf). Most other
203 // programs do not fall back to http proxy settings and neither
206 result
= getenv("http_proxy");
207 UseProxy
= result
== NULL
? "" : result
;
210 // Determine what host and port to use based on the proxy settings
211 if (UseProxy
.empty() == false)
214 if (Proxy
.Access
== "socks5h")
215 curl_easy_setopt(curl
, CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5_HOSTNAME
);
216 else if (Proxy
.Access
== "socks5")
217 curl_easy_setopt(curl
, CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
218 else if (Proxy
.Access
== "socks4a")
219 curl_easy_setopt(curl
, CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4A
);
220 else if (Proxy
.Access
== "socks")
221 curl_easy_setopt(curl
, CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4
);
222 else if (Proxy
.Access
== "http" || Proxy
.Access
== "https")
223 curl_easy_setopt(curl
, CURLOPT_PROXYTYPE
, CURLPROXY_HTTP
);
228 curl_easy_setopt(curl
, CURLOPT_PROXYPORT
, Proxy
.Port
);
229 curl_easy_setopt(curl
, CURLOPT_PROXY
, Proxy
.Host
.c_str());
230 if (Proxy
.User
.empty() == false || Proxy
.Password
.empty() == false)
232 curl_easy_setopt(curl
, CURLOPT_PROXYUSERNAME
, Proxy
.User
.c_str());
233 curl_easy_setopt(curl
, CURLOPT_PROXYPASSWORD
, Proxy
.Password
.c_str());
238 // HttpsMethod::Fetch - Fetch an item /*{{{*/
239 // ---------------------------------------------------------------------
240 /* This adds an item to the pipeline. We keep the pipeline at a fixed
242 bool HttpsMethod::Fetch(FetchItem
*Itm
)
245 struct curl_slist
*headers
=NULL
;
246 char curl_errorstr
[CURL_ERROR_SIZE
];
248 string remotehost
= Uri
.Host
;
251 // - http::Pipeline-Depth
252 // - error checking/reporting
253 // - more debug options? (CURLOPT_DEBUGFUNCTION?)
255 curl_easy_reset(curl
);
256 if (SetupProxy() == false)
257 return _error
->Error("Unsupported proxy configured: %s", URI::SiteOnly(Proxy
).c_str());
259 maybe_add_auth (Uri
, _config
->FindFile("Dir::Etc::netrc"));
262 CURLUserPointer
userp(this, &Res
, Itm
);
264 curl_easy_setopt(curl
, CURLOPT_URL
, static_cast<string
>(Uri
).c_str());
265 curl_easy_setopt(curl
, CURLOPT_HEADERFUNCTION
, parse_header
);
266 curl_easy_setopt(curl
, CURLOPT_WRITEHEADER
, &userp
);
267 curl_easy_setopt(curl
, CURLOPT_WRITEFUNCTION
, write_data
);
268 curl_easy_setopt(curl
, CURLOPT_WRITEDATA
, this);
270 curl_easy_setopt(curl
, CURLOPT_NOPROGRESS
, true);
271 curl_easy_setopt(curl
, CURLOPT_FILETIME
, true);
272 curl_easy_setopt(curl
, CURLOPT_FOLLOWLOCATION
, 0);
273 // only allow curl to handle https, not the other stuff it supports
274 curl_easy_setopt(curl
, CURLOPT_PROTOCOLS
, CURLPROTO_HTTPS
);
275 curl_easy_setopt(curl
, CURLOPT_REDIR_PROTOCOLS
, CURLPROTO_HTTPS
);
277 // SSL parameters are set by default to the common (non mirror-specific) value
278 // if available (or a default one) and gets overload by mirror-specific ones.
280 // File containing the list of trusted CA.
281 string cainfo
= _config
->Find("Acquire::https::CaInfo","");
282 string knob
= "Acquire::https::"+remotehost
+"::CaInfo";
283 cainfo
= _config
->Find(knob
.c_str(),cainfo
.c_str());
284 if(cainfo
.empty() == false)
285 curl_easy_setopt(curl
, CURLOPT_CAINFO
,cainfo
.c_str());
287 // Check server certificate against previous CA list ...
288 bool peer_verify
= _config
->FindB("Acquire::https::Verify-Peer",true);
289 knob
= "Acquire::https::" + remotehost
+ "::Verify-Peer";
290 peer_verify
= _config
->FindB(knob
.c_str(), peer_verify
);
291 curl_easy_setopt(curl
, CURLOPT_SSL_VERIFYPEER
, peer_verify
);
293 // ... and hostname against cert CN or subjectAltName
294 bool verify
= _config
->FindB("Acquire::https::Verify-Host",true);
295 knob
= "Acquire::https::"+remotehost
+"::Verify-Host";
296 verify
= _config
->FindB(knob
.c_str(),verify
);
297 int const default_verify
= (verify
== true) ? 2 : 0;
298 curl_easy_setopt(curl
, CURLOPT_SSL_VERIFYHOST
, default_verify
);
300 // Also enforce issuer of server certificate using its cert
301 string issuercert
= _config
->Find("Acquire::https::IssuerCert","");
302 knob
= "Acquire::https::"+remotehost
+"::IssuerCert";
303 issuercert
= _config
->Find(knob
.c_str(),issuercert
.c_str());
304 if(issuercert
.empty() == false)
305 curl_easy_setopt(curl
, CURLOPT_ISSUERCERT
,issuercert
.c_str());
307 // For client authentication, certificate file ...
308 string pem
= _config
->Find("Acquire::https::SslCert","");
309 knob
= "Acquire::https::"+remotehost
+"::SslCert";
310 pem
= _config
->Find(knob
.c_str(),pem
.c_str());
311 if(pem
.empty() == false)
312 curl_easy_setopt(curl
, CURLOPT_SSLCERT
, pem
.c_str());
314 // ... and associated key.
315 string key
= _config
->Find("Acquire::https::SslKey","");
316 knob
= "Acquire::https::"+remotehost
+"::SslKey";
317 key
= _config
->Find(knob
.c_str(),key
.c_str());
318 if(key
.empty() == false)
319 curl_easy_setopt(curl
, CURLOPT_SSLKEY
, key
.c_str());
321 // Allow forcing SSL version to SSLv3 or TLSv1 (SSLv2 is not
322 // supported by GnuTLS).
323 long final_version
= CURL_SSLVERSION_DEFAULT
;
324 string sslversion
= _config
->Find("Acquire::https::SslForceVersion","");
325 knob
= "Acquire::https::"+remotehost
+"::SslForceVersion";
326 sslversion
= _config
->Find(knob
.c_str(),sslversion
.c_str());
327 if(sslversion
== "TLSv1")
328 final_version
= CURL_SSLVERSION_TLSv1
;
329 else if(sslversion
== "SSLv3")
330 final_version
= CURL_SSLVERSION_SSLv3
;
331 curl_easy_setopt(curl
, CURLOPT_SSLVERSION
, final_version
);
334 string crlfile
= _config
->Find("Acquire::https::CrlFile","");
335 knob
= "Acquire::https::"+remotehost
+"::CrlFile";
336 crlfile
= _config
->Find(knob
.c_str(),crlfile
.c_str());
337 if(crlfile
.empty() == false)
338 curl_easy_setopt(curl
, CURLOPT_CRLFILE
, crlfile
.c_str());
341 if(_config
->FindB("Acquire::https::No-Cache",
342 _config
->FindB("Acquire::http::No-Cache",false)) == false)
345 if (_config
->FindB("Acquire::https::No-Store",
346 _config
->FindB("Acquire::http::No-Store",false)) == true)
347 headers
= curl_slist_append(headers
,"Cache-Control: no-store");
349 ioprintf(ss
, "Cache-Control: max-age=%u", _config
->FindI("Acquire::https::Max-Age",
350 _config
->FindI("Acquire::http::Max-Age",0)));
351 headers
= curl_slist_append(headers
, ss
.str().c_str());
353 // cache disabled by user
354 headers
= curl_slist_append(headers
, "Cache-Control: no-cache");
355 headers
= curl_slist_append(headers
, "Pragma: no-cache");
357 curl_easy_setopt(curl
, CURLOPT_HTTPHEADER
, headers
);
360 int const dlLimit
= _config
->FindI("Acquire::https::Dl-Limit",
361 _config
->FindI("Acquire::http::Dl-Limit",0))*1024;
363 curl_easy_setopt(curl
, CURLOPT_MAX_RECV_SPEED_LARGE
, dlLimit
);
366 curl_easy_setopt(curl
, CURLOPT_USERAGENT
,
367 _config
->Find("Acquire::https::User-Agent",
368 _config
->Find("Acquire::http::User-Agent",
369 "Debian APT-CURL/1.0 (" PACKAGE_VERSION
")").c_str()).c_str());
372 int const timeout
= _config
->FindI("Acquire::https::Timeout",
373 _config
->FindI("Acquire::http::Timeout",120));
374 curl_easy_setopt(curl
, CURLOPT_CONNECTTIMEOUT
, timeout
);
375 //set really low lowspeed timeout (see #497983)
376 curl_easy_setopt(curl
, CURLOPT_LOW_SPEED_LIMIT
, DL_MIN_SPEED
);
377 curl_easy_setopt(curl
, CURLOPT_LOW_SPEED_TIME
, timeout
);
381 curl_easy_setopt(curl
, CURLOPT_VERBOSE
, true);
384 curl_errorstr
[0] = '\0';
385 curl_easy_setopt(curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
387 // If we ask for uncompressed files servers might respond with content-
388 // negotiation which lets us end up with compressed files we do not support,
389 // see 657029, 657560 and co, so if we have no extension on the request
390 // ask for text only. As a sidenote: If there is nothing to negotate servers
391 // seem to be nice and ignore it.
392 if (_config
->FindB("Acquire::https::SendAccept", _config
->FindB("Acquire::http::SendAccept", true)) == true)
394 size_t const filepos
= Itm
->Uri
.find_last_of('/');
395 string
const file
= Itm
->Uri
.substr(filepos
+ 1);
396 if (flExtension(file
) == file
)
397 headers
= curl_slist_append(headers
, "Accept: text/*");
400 // if we have the file send an if-range query with a range header
401 if (stat(Itm
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
404 strprintf(Buf
, "Range: bytes=%lli-", (long long) SBuf
.st_size
);
405 headers
= curl_slist_append(headers
, Buf
.c_str());
406 strprintf(Buf
, "If-Range: %s", TimeRFC1123(SBuf
.st_mtime
, false).c_str());
407 headers
= curl_slist_append(headers
, Buf
.c_str());
409 else if(Itm
->LastModified
> 0)
411 curl_easy_setopt(curl
, CURLOPT_TIMECONDITION
, CURL_TIMECOND_IFMODSINCE
);
412 curl_easy_setopt(curl
, CURLOPT_TIMEVALUE
, Itm
->LastModified
);
415 // go for it - if the file exists, append on it
416 File
= new FileFd(Itm
->DestFile
, FileFd::WriteAny
);
417 Server
= CreateServerState(Itm
->Uri
);
418 if (Server
->InitHashes(Itm
->ExpectedHashes
) == false)
422 Res
.Filename
= Itm
->DestFile
;
425 CURLcode success
= curl_easy_perform(curl
);
427 // If the server returns 200 OK but the If-Modified-Since condition is not
428 // met, CURLINFO_CONDITION_UNMET will be set to 1
429 long curl_condition_unmet
= 0;
430 curl_easy_getinfo(curl
, CURLINFO_CONDITION_UNMET
, &curl_condition_unmet
);
431 if (curl_condition_unmet
== 1)
432 Server
->Result
= 304;
435 curl_slist_free_all(headers
);
438 if (success
!= CURLE_OK
)
440 #pragma GCC diagnostic push
441 #pragma GCC diagnostic ignored "-Wswitch"
444 case CURLE_COULDNT_RESOLVE_PROXY
:
445 case CURLE_COULDNT_RESOLVE_HOST
:
446 SetFailReason("ResolveFailure");
448 case CURLE_COULDNT_CONNECT
:
449 SetFailReason("ConnectionRefused");
451 case CURLE_OPERATION_TIMEDOUT
:
452 SetFailReason("Timeout");
455 #pragma GCC diagnostic pop
456 // only take curls technical errors if we haven't our own
457 // (e.g. for the maximum size limit we have and curls can be confusing)
458 if (_error
->PendingError() == false)
459 _error
->Error("%s", curl_errorstr
);
461 _error
->Warning("curl: %s", curl_errorstr
);
465 switch (DealWithHeaders(Res
))
467 case ServerMethod::IMS_HIT
:
471 case ServerMethod::ERROR_WITH_CONTENT_PAGE
:
472 // unlink, no need keep 401/404 page content in partial/
473 RemoveFile(Binary
.c_str(), File
->Name());
474 case ServerMethod::ERROR_UNRECOVERABLE
:
475 case ServerMethod::ERROR_NOT_FROM_SERVER
:
478 case ServerMethod::TRY_AGAIN_OR_REDIRECT
:
482 case ServerMethod::FILE_IS_OPEN
:
483 struct stat resultStat
;
484 if (unlikely(stat(File
->Name().c_str(), &resultStat
) != 0))
486 _error
->Errno("stat", "Unable to access file %s", File
->Name().c_str());
489 Res
.Size
= resultStat
.st_size
;
492 curl_easy_getinfo(curl
, CURLINFO_FILETIME
, &Res
.LastModified
);
493 if (Res
.LastModified
!= -1)
495 struct timeval times
[2];
496 times
[0].tv_sec
= Res
.LastModified
;
497 times
[1].tv_sec
= Res
.LastModified
;
498 times
[0].tv_usec
= times
[1].tv_usec
= 0;
499 utimes(File
->Name().c_str(), times
);
502 Res
.LastModified
= resultStat
.st_mtime
;
505 Res
.TakeHashes(*(Server
->GetHashes()));
516 // HttpsMethod::Configuration - Handle a configuration message /*{{{*/
517 bool HttpsMethod::Configuration(string Message
)
519 if (ServerMethod::Configuration(Message
) == false)
522 AllowRedirect
= _config
->FindB("Acquire::https::AllowRedirect",
523 _config
->FindB("Acquire::http::AllowRedirect", true));
524 Debug
= _config
->FindB("Debug::Acquire::https",false);
529 std::unique_ptr
<ServerState
> HttpsMethod::CreateServerState(URI
const &uri
)/*{{{*/
531 return std::unique_ptr
<ServerState
>(new HttpsServerState(uri
, this));
537 return HttpsMethod().Run();