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/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>
40 struct APT_HIDDEN CURLUserPointer
{
41 HttpsMethod
* const https
;
42 HttpsMethod::FetchResult
* const Res
;
43 HttpsMethod::FetchItem
const * const Itm
;
44 CURLUserPointer(HttpsMethod
* const https
, HttpsMethod::FetchResult
* const Res
,
45 HttpsMethod::FetchItem
const * const Itm
) : https(https
), Res(Res
), Itm(Itm
) {}
49 HttpsMethod::parse_header(void *buffer
, size_t size
, size_t nmemb
, void *userp
)
51 size_t len
= size
* nmemb
;
52 CURLUserPointer
*me
= static_cast<CURLUserPointer
*>(userp
);
53 std::string
line((char*) buffer
, len
);
54 for (--len
; len
> 0; --len
)
55 if (isspace_ascii(line
[len
]) == 0)
62 if (line
.empty() == true)
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
->https
->Server
->JunkSize
== 0 && 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 else if (me
->https
->Server
->HeaderLine(line
) == false)
116 HttpsMethod::write_data(void *buffer
, size_t size
, size_t nmemb
, void *userp
)
118 HttpsMethod
*me
= static_cast<HttpsMethod
*>(userp
);
119 size_t buffer_size
= size
* nmemb
;
120 // we don't need to count the junk here, just drop anything we get as
121 // we don't always know how long it would be, e.g. in chunked encoding.
122 if (me
->Server
->JunkSize
!= 0)
125 if(me
->File
->Write(buffer
, buffer_size
) != true)
128 if(me
->Queue
->MaximumSize
> 0)
130 unsigned long long const TotalWritten
= me
->File
->Tell();
131 if (TotalWritten
> me
->Queue
->MaximumSize
)
133 me
->SetFailReason("MaximumSizeExceeded");
134 _error
->Error("Writing more data than expected (%llu > %llu)",
135 TotalWritten
, me
->Queue
->MaximumSize
);
140 if (me
->Server
->GetHashes()->Add((unsigned char const * const)buffer
, buffer_size
) == false)
146 // HttpsServerState::HttpsServerState - Constructor /*{{{*/
147 HttpsServerState::HttpsServerState(URI Srv
,HttpsMethod
* Owner
) : ServerState(Srv
, Owner
), Hash(NULL
)
149 TimeOut
= _config
->FindI("Acquire::https::Timeout",TimeOut
);
153 bool HttpsServerState::InitHashes(HashStringList
const &ExpectedHashes
) /*{{{*/
156 Hash
= new Hashes(ExpectedHashes
);
160 APT_PURE Hashes
* HttpsServerState::GetHashes() /*{{{*/
166 void HttpsMethod::SetupProxy() /*{{{*/
168 URI ServerName
= Queue
->Uri
;
170 // Determine the proxy setting
171 AutoDetectProxy(ServerName
);
173 // Curl should never read proxy settings from the environment, as
174 // we determine which proxy to use. Do this for consistency among
175 // methods and prevent an environment variable overriding a
176 // no-proxy ("DIRECT") setting in apt.conf.
177 curl_easy_setopt(curl
, CURLOPT_PROXY
, "");
179 // Determine the proxy setting - try https first, fallback to http and use env at last
180 string UseProxy
= _config
->Find("Acquire::https::Proxy::" + ServerName
.Host
,
181 _config
->Find("Acquire::http::Proxy::" + ServerName
.Host
).c_str());
183 if (UseProxy
.empty() == true)
184 UseProxy
= _config
->Find("Acquire::https::Proxy", _config
->Find("Acquire::http::Proxy").c_str());
186 // User want to use NO proxy, so nothing to setup
187 if (UseProxy
== "DIRECT")
190 if (UseProxy
.empty() == false)
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 const char* result
= getenv("https_proxy");
198 // FIXME: Fall back to http_proxy is to remain compatible with
199 // existing setups and behaviour of apt.conf. This should be
200 // deprecated in the future (including apt.conf). Most other
201 // programs do not fall back to http proxy settings and neither
204 result
= getenv("http_proxy");
205 UseProxy
= result
== NULL
? "" : result
;
208 // Determine what host and port to use based on the proxy settings
209 if (UseProxy
.empty() == false)
213 curl_easy_setopt(curl
, CURLOPT_PROXYPORT
, Proxy
.Port
);
214 curl_easy_setopt(curl
, CURLOPT_PROXY
, Proxy
.Host
.c_str());
215 if (Proxy
.User
.empty() == false || Proxy
.Password
.empty() == false)
217 curl_easy_setopt(curl
, CURLOPT_PROXYUSERNAME
, Proxy
.User
.c_str());
218 curl_easy_setopt(curl
, CURLOPT_PROXYPASSWORD
, Proxy
.Password
.c_str());
222 // HttpsMethod::Fetch - Fetch an item /*{{{*/
223 // ---------------------------------------------------------------------
224 /* This adds an item to the pipeline. We keep the pipeline at a fixed
226 bool HttpsMethod::Fetch(FetchItem
*Itm
)
229 struct curl_slist
*headers
=NULL
;
230 char curl_errorstr
[CURL_ERROR_SIZE
];
232 string remotehost
= Uri
.Host
;
235 // - http::Pipeline-Depth
236 // - error checking/reporting
237 // - more debug options? (CURLOPT_DEBUGFUNCTION?)
239 curl_easy_reset(curl
);
242 maybe_add_auth (Uri
, _config
->FindFile("Dir::Etc::netrc"));
245 CURLUserPointer
userp(this, &Res
, Itm
);
247 curl_easy_setopt(curl
, CURLOPT_URL
, static_cast<string
>(Uri
).c_str());
248 curl_easy_setopt(curl
, CURLOPT_HEADERFUNCTION
, parse_header
);
249 curl_easy_setopt(curl
, CURLOPT_WRITEHEADER
, &userp
);
250 curl_easy_setopt(curl
, CURLOPT_WRITEFUNCTION
, write_data
);
251 curl_easy_setopt(curl
, CURLOPT_WRITEDATA
, this);
253 curl_easy_setopt(curl
, CURLOPT_NOPROGRESS
, true);
254 curl_easy_setopt(curl
, CURLOPT_FILETIME
, true);
255 // only allow curl to handle https, not the other stuff it supports
256 curl_easy_setopt(curl
, CURLOPT_PROTOCOLS
, CURLPROTO_HTTPS
);
257 curl_easy_setopt(curl
, CURLOPT_REDIR_PROTOCOLS
, CURLPROTO_HTTPS
);
259 // SSL parameters are set by default to the common (non mirror-specific) value
260 // if available (or a default one) and gets overload by mirror-specific ones.
262 // File containing the list of trusted CA.
263 string cainfo
= _config
->Find("Acquire::https::CaInfo","");
264 string knob
= "Acquire::https::"+remotehost
+"::CaInfo";
265 cainfo
= _config
->Find(knob
.c_str(),cainfo
.c_str());
266 if(cainfo
.empty() == false)
267 curl_easy_setopt(curl
, CURLOPT_CAINFO
,cainfo
.c_str());
269 // Check server certificate against previous CA list ...
270 bool peer_verify
= _config
->FindB("Acquire::https::Verify-Peer",true);
271 knob
= "Acquire::https::" + remotehost
+ "::Verify-Peer";
272 peer_verify
= _config
->FindB(knob
.c_str(), peer_verify
);
273 curl_easy_setopt(curl
, CURLOPT_SSL_VERIFYPEER
, peer_verify
);
275 // ... and hostname against cert CN or subjectAltName
276 bool verify
= _config
->FindB("Acquire::https::Verify-Host",true);
277 knob
= "Acquire::https::"+remotehost
+"::Verify-Host";
278 verify
= _config
->FindB(knob
.c_str(),verify
);
279 int const default_verify
= (verify
== true) ? 2 : 0;
280 curl_easy_setopt(curl
, CURLOPT_SSL_VERIFYHOST
, default_verify
);
282 // Also enforce issuer of server certificate using its cert
283 string issuercert
= _config
->Find("Acquire::https::IssuerCert","");
284 knob
= "Acquire::https::"+remotehost
+"::IssuerCert";
285 issuercert
= _config
->Find(knob
.c_str(),issuercert
.c_str());
286 if(issuercert
.empty() == false)
287 curl_easy_setopt(curl
, CURLOPT_ISSUERCERT
,issuercert
.c_str());
289 // For client authentication, certificate file ...
290 string pem
= _config
->Find("Acquire::https::SslCert","");
291 knob
= "Acquire::https::"+remotehost
+"::SslCert";
292 pem
= _config
->Find(knob
.c_str(),pem
.c_str());
293 if(pem
.empty() == false)
294 curl_easy_setopt(curl
, CURLOPT_SSLCERT
, pem
.c_str());
296 // ... and associated key.
297 string key
= _config
->Find("Acquire::https::SslKey","");
298 knob
= "Acquire::https::"+remotehost
+"::SslKey";
299 key
= _config
->Find(knob
.c_str(),key
.c_str());
300 if(key
.empty() == false)
301 curl_easy_setopt(curl
, CURLOPT_SSLKEY
, key
.c_str());
303 // Allow forcing SSL version to SSLv3 or TLSv1 (SSLv2 is not
304 // supported by GnuTLS).
305 long final_version
= CURL_SSLVERSION_DEFAULT
;
306 string sslversion
= _config
->Find("Acquire::https::SslForceVersion","");
307 knob
= "Acquire::https::"+remotehost
+"::SslForceVersion";
308 sslversion
= _config
->Find(knob
.c_str(),sslversion
.c_str());
309 if(sslversion
== "TLSv1")
310 final_version
= CURL_SSLVERSION_TLSv1
;
311 else if(sslversion
== "SSLv3")
312 final_version
= CURL_SSLVERSION_SSLv3
;
313 curl_easy_setopt(curl
, CURLOPT_SSLVERSION
, final_version
);
316 string crlfile
= _config
->Find("Acquire::https::CrlFile","");
317 knob
= "Acquire::https::"+remotehost
+"::CrlFile";
318 crlfile
= _config
->Find(knob
.c_str(),crlfile
.c_str());
319 if(crlfile
.empty() == false)
320 curl_easy_setopt(curl
, CURLOPT_CRLFILE
, crlfile
.c_str());
323 if(_config
->FindB("Acquire::https::No-Cache",
324 _config
->FindB("Acquire::http::No-Cache",false)) == false)
327 if (_config
->FindB("Acquire::https::No-Store",
328 _config
->FindB("Acquire::http::No-Store",false)) == true)
329 headers
= curl_slist_append(headers
,"Cache-Control: no-store");
331 ioprintf(ss
, "Cache-Control: max-age=%u", _config
->FindI("Acquire::https::Max-Age",
332 _config
->FindI("Acquire::http::Max-Age",0)));
333 headers
= curl_slist_append(headers
, ss
.str().c_str());
335 // cache disabled by user
336 headers
= curl_slist_append(headers
, "Cache-Control: no-cache");
337 headers
= curl_slist_append(headers
, "Pragma: no-cache");
339 curl_easy_setopt(curl
, CURLOPT_HTTPHEADER
, headers
);
342 int const dlLimit
= _config
->FindI("Acquire::https::Dl-Limit",
343 _config
->FindI("Acquire::http::Dl-Limit",0))*1024;
345 curl_easy_setopt(curl
, CURLOPT_MAX_RECV_SPEED_LARGE
, dlLimit
);
348 curl_easy_setopt(curl
, CURLOPT_USERAGENT
,
349 _config
->Find("Acquire::https::User-Agent",
350 _config
->Find("Acquire::http::User-Agent",
351 "Debian APT-CURL/1.0 (" PACKAGE_VERSION
")").c_str()).c_str());
354 int const timeout
= _config
->FindI("Acquire::https::Timeout",
355 _config
->FindI("Acquire::http::Timeout",120));
356 curl_easy_setopt(curl
, CURLOPT_CONNECTTIMEOUT
, timeout
);
357 //set really low lowspeed timeout (see #497983)
358 curl_easy_setopt(curl
, CURLOPT_LOW_SPEED_LIMIT
, DL_MIN_SPEED
);
359 curl_easy_setopt(curl
, CURLOPT_LOW_SPEED_TIME
, timeout
);
361 // set redirect options and default to 10 redirects
362 curl_easy_setopt(curl
, CURLOPT_FOLLOWLOCATION
, AllowRedirect
);
363 curl_easy_setopt(curl
, CURLOPT_MAXREDIRS
, 10);
367 curl_easy_setopt(curl
, CURLOPT_VERBOSE
, true);
370 curl_errorstr
[0] = '\0';
371 curl_easy_setopt(curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
373 // If we ask for uncompressed files servers might respond with content-
374 // negotiation which lets us end up with compressed files we do not support,
375 // see 657029, 657560 and co, so if we have no extension on the request
376 // ask for text only. As a sidenote: If there is nothing to negotate servers
377 // seem to be nice and ignore it.
378 if (_config
->FindB("Acquire::https::SendAccept", _config
->FindB("Acquire::http::SendAccept", true)) == true)
380 size_t const filepos
= Itm
->Uri
.find_last_of('/');
381 string
const file
= Itm
->Uri
.substr(filepos
+ 1);
382 if (flExtension(file
) == file
)
383 headers
= curl_slist_append(headers
, "Accept: text/*");
386 // if we have the file send an if-range query with a range header
387 if (stat(Itm
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
390 strprintf(Buf
, "Range: bytes=%lli-", (long long) SBuf
.st_size
);
391 headers
= curl_slist_append(headers
, Buf
.c_str());
392 strprintf(Buf
, "If-Range: %s", TimeRFC1123(SBuf
.st_mtime
).c_str());
393 headers
= curl_slist_append(headers
, Buf
.c_str());
395 else if(Itm
->LastModified
> 0)
397 curl_easy_setopt(curl
, CURLOPT_TIMECONDITION
, CURL_TIMECOND_IFMODSINCE
);
398 curl_easy_setopt(curl
, CURLOPT_TIMEVALUE
, Itm
->LastModified
);
401 // go for it - if the file exists, append on it
402 File
= new FileFd(Itm
->DestFile
, FileFd::WriteAny
);
403 Server
= CreateServerState(Itm
->Uri
);
404 if (Server
->InitHashes(Itm
->ExpectedHashes
) == false)
408 Res
.Filename
= Itm
->DestFile
;
411 CURLcode success
= curl_easy_perform(curl
);
413 // If the server returns 200 OK but the If-Modified-Since condition is not
414 // met, CURLINFO_CONDITION_UNMET will be set to 1
415 long curl_condition_unmet
= 0;
416 curl_easy_getinfo(curl
, CURLINFO_CONDITION_UNMET
, &curl_condition_unmet
);
419 curl_slist_free_all(headers
);
422 if (success
!= CURLE_OK
)
424 #pragma GCC diagnostic push
425 #pragma GCC diagnostic ignored "-Wswitch"
428 case CURLE_COULDNT_RESOLVE_PROXY
:
429 case CURLE_COULDNT_RESOLVE_HOST
:
430 SetFailReason("ResolveFailure");
432 case CURLE_COULDNT_CONNECT
:
433 SetFailReason("ConnectionRefused");
435 case CURLE_OPERATION_TIMEDOUT
:
436 SetFailReason("Timeout");
439 #pragma GCC diagnostic pop
440 return _error
->Error("%s", curl_errorstr
);
443 // server says file not modified
444 if (Server
->Result
== 304 || curl_condition_unmet
== 1)
446 RemoveFile("https", File
->Name());
448 Res
.LastModified
= Itm
->LastModified
;
455 if (Server
->Result
!= 200 && // OK
456 Server
->Result
!= 206 && // Partial
457 Server
->Result
!= 416) // invalid Range
460 snprintf(err
, sizeof(err
) - 1, "HttpError%i", Server
->Result
);
462 _error
->Error("%i %s", Server
->Result
, Server
->Code
);
463 // unlink, no need keep 401/404 page content in partial/
464 RemoveFile("https", File
->Name());
468 // invalid range-request
469 if (Server
->Result
== 416)
471 RemoveFile("https", File
->Name());
477 struct stat resultStat
;
478 if (unlikely(stat(File
->Name().c_str(), &resultStat
) != 0))
480 _error
->Errno("stat", "Unable to access file %s", File
->Name().c_str());
483 Res
.Size
= resultStat
.st_size
;
486 curl_easy_getinfo(curl
, CURLINFO_FILETIME
, &Res
.LastModified
);
487 if (Res
.LastModified
!= -1)
489 struct timeval times
[2];
490 times
[0].tv_sec
= Res
.LastModified
;
491 times
[1].tv_sec
= Res
.LastModified
;
492 times
[0].tv_usec
= times
[1].tv_usec
= 0;
493 utimes(File
->Name().c_str(), times
);
496 Res
.LastModified
= resultStat
.st_mtime
;
499 Res
.TakeHashes(*(Server
->GetHashes()));
510 // HttpsMethod::Configuration - Handle a configuration message /*{{{*/
511 bool HttpsMethod::Configuration(string Message
)
513 if (ServerMethod::Configuration(Message
) == false)
516 AllowRedirect
= _config
->FindB("Acquire::https::AllowRedirect",
517 _config
->FindB("Acquire::http::AllowRedirect", true));
518 Debug
= _config
->FindB("Debug::Acquire::https",false);
523 std::unique_ptr
<ServerState
> HttpsMethod::CreateServerState(URI
const &uri
)/*{{{*/
525 return std::unique_ptr
<ServerState
>(new HttpsServerState(uri
, this));
531 setlocale(LC_ALL
, "");
534 curl_global_init(CURL_GLOBAL_SSL
) ;