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 // Parse no_proxy, a comma (,) separated list of domains we don't want to use
191 // a proxy for so we stop right here if it is in the list
192 if (getenv("no_proxy") != 0 && CheckDomainList(ServerName
.Host
,getenv("no_proxy")) == true)
195 if (UseProxy
.empty() == 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"));
244 // The "+" is encoded as a workaround for a amazon S3 bug
245 // see LP bugs #1003633 and #1086997. (taken from http method)
246 Uri
.Path
= QuoteString(Uri
.Path
, "+~ ");
249 CURLUserPointer
userp(this, &Res
, Itm
);
251 curl_easy_setopt(curl
, CURLOPT_URL
, static_cast<string
>(Uri
).c_str());
252 curl_easy_setopt(curl
, CURLOPT_HEADERFUNCTION
, parse_header
);
253 curl_easy_setopt(curl
, CURLOPT_WRITEHEADER
, &userp
);
254 curl_easy_setopt(curl
, CURLOPT_WRITEFUNCTION
, write_data
);
255 curl_easy_setopt(curl
, CURLOPT_WRITEDATA
, this);
257 curl_easy_setopt(curl
, CURLOPT_NOPROGRESS
, true);
258 curl_easy_setopt(curl
, CURLOPT_FILETIME
, true);
259 // only allow curl to handle https, not the other stuff it supports
260 curl_easy_setopt(curl
, CURLOPT_PROTOCOLS
, CURLPROTO_HTTPS
);
261 curl_easy_setopt(curl
, CURLOPT_REDIR_PROTOCOLS
, CURLPROTO_HTTPS
);
263 // SSL parameters are set by default to the common (non mirror-specific) value
264 // if available (or a default one) and gets overload by mirror-specific ones.
266 // File containing the list of trusted CA.
267 string cainfo
= _config
->Find("Acquire::https::CaInfo","");
268 string knob
= "Acquire::https::"+remotehost
+"::CaInfo";
269 cainfo
= _config
->Find(knob
.c_str(),cainfo
.c_str());
270 if(cainfo
.empty() == false)
271 curl_easy_setopt(curl
, CURLOPT_CAINFO
,cainfo
.c_str());
273 // Check server certificate against previous CA list ...
274 bool peer_verify
= _config
->FindB("Acquire::https::Verify-Peer",true);
275 knob
= "Acquire::https::" + remotehost
+ "::Verify-Peer";
276 peer_verify
= _config
->FindB(knob
.c_str(), peer_verify
);
277 curl_easy_setopt(curl
, CURLOPT_SSL_VERIFYPEER
, peer_verify
);
279 // ... and hostname against cert CN or subjectAltName
280 bool verify
= _config
->FindB("Acquire::https::Verify-Host",true);
281 knob
= "Acquire::https::"+remotehost
+"::Verify-Host";
282 verify
= _config
->FindB(knob
.c_str(),verify
);
283 int const default_verify
= (verify
== true) ? 2 : 0;
284 curl_easy_setopt(curl
, CURLOPT_SSL_VERIFYHOST
, default_verify
);
286 // Also enforce issuer of server certificate using its cert
287 string issuercert
= _config
->Find("Acquire::https::IssuerCert","");
288 knob
= "Acquire::https::"+remotehost
+"::IssuerCert";
289 issuercert
= _config
->Find(knob
.c_str(),issuercert
.c_str());
290 if(issuercert
.empty() == false)
291 curl_easy_setopt(curl
, CURLOPT_ISSUERCERT
,issuercert
.c_str());
293 // For client authentication, certificate file ...
294 string pem
= _config
->Find("Acquire::https::SslCert","");
295 knob
= "Acquire::https::"+remotehost
+"::SslCert";
296 pem
= _config
->Find(knob
.c_str(),pem
.c_str());
297 if(pem
.empty() == false)
298 curl_easy_setopt(curl
, CURLOPT_SSLCERT
, pem
.c_str());
300 // ... and associated key.
301 string key
= _config
->Find("Acquire::https::SslKey","");
302 knob
= "Acquire::https::"+remotehost
+"::SslKey";
303 key
= _config
->Find(knob
.c_str(),key
.c_str());
304 if(key
.empty() == false)
305 curl_easy_setopt(curl
, CURLOPT_SSLKEY
, key
.c_str());
307 // Allow forcing SSL version to SSLv3 or TLSv1 (SSLv2 is not
308 // supported by GnuTLS).
309 long final_version
= CURL_SSLVERSION_DEFAULT
;
310 string sslversion
= _config
->Find("Acquire::https::SslForceVersion","");
311 knob
= "Acquire::https::"+remotehost
+"::SslForceVersion";
312 sslversion
= _config
->Find(knob
.c_str(),sslversion
.c_str());
313 if(sslversion
== "TLSv1")
314 final_version
= CURL_SSLVERSION_TLSv1
;
315 else if(sslversion
== "SSLv3")
316 final_version
= CURL_SSLVERSION_SSLv3
;
317 curl_easy_setopt(curl
, CURLOPT_SSLVERSION
, final_version
);
320 string crlfile
= _config
->Find("Acquire::https::CrlFile","");
321 knob
= "Acquire::https::"+remotehost
+"::CrlFile";
322 crlfile
= _config
->Find(knob
.c_str(),crlfile
.c_str());
323 if(crlfile
.empty() == false)
324 curl_easy_setopt(curl
, CURLOPT_CRLFILE
, crlfile
.c_str());
327 if(_config
->FindB("Acquire::https::No-Cache",
328 _config
->FindB("Acquire::http::No-Cache",false)) == false)
331 if (_config
->FindB("Acquire::https::No-Store",
332 _config
->FindB("Acquire::http::No-Store",false)) == true)
333 headers
= curl_slist_append(headers
,"Cache-Control: no-store");
335 ioprintf(ss
, "Cache-Control: max-age=%u", _config
->FindI("Acquire::https::Max-Age",
336 _config
->FindI("Acquire::http::Max-Age",0)));
337 headers
= curl_slist_append(headers
, ss
.str().c_str());
339 // cache disabled by user
340 headers
= curl_slist_append(headers
, "Cache-Control: no-cache");
341 headers
= curl_slist_append(headers
, "Pragma: no-cache");
343 curl_easy_setopt(curl
, CURLOPT_HTTPHEADER
, headers
);
346 int const dlLimit
= _config
->FindI("Acquire::https::Dl-Limit",
347 _config
->FindI("Acquire::http::Dl-Limit",0))*1024;
349 curl_easy_setopt(curl
, CURLOPT_MAX_RECV_SPEED_LARGE
, dlLimit
);
352 curl_easy_setopt(curl
, CURLOPT_USERAGENT
,
353 _config
->Find("Acquire::https::User-Agent",
354 _config
->Find("Acquire::http::User-Agent",
355 "Debian APT-CURL/1.0 (" PACKAGE_VERSION
")").c_str()).c_str());
358 int const timeout
= _config
->FindI("Acquire::https::Timeout",
359 _config
->FindI("Acquire::http::Timeout",120));
360 curl_easy_setopt(curl
, CURLOPT_CONNECTTIMEOUT
, timeout
);
361 //set really low lowspeed timeout (see #497983)
362 curl_easy_setopt(curl
, CURLOPT_LOW_SPEED_LIMIT
, DL_MIN_SPEED
);
363 curl_easy_setopt(curl
, CURLOPT_LOW_SPEED_TIME
, timeout
);
365 // set redirect options and default to 10 redirects
366 curl_easy_setopt(curl
, CURLOPT_FOLLOWLOCATION
, AllowRedirect
);
367 curl_easy_setopt(curl
, CURLOPT_MAXREDIRS
, 10);
371 curl_easy_setopt(curl
, CURLOPT_VERBOSE
, true);
374 curl_errorstr
[0] = '\0';
375 curl_easy_setopt(curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
377 // If we ask for uncompressed files servers might respond with content-
378 // negotiation which lets us end up with compressed files we do not support,
379 // see 657029, 657560 and co, so if we have no extension on the request
380 // ask for text only. As a sidenote: If there is nothing to negotate servers
381 // seem to be nice and ignore it.
382 if (_config
->FindB("Acquire::https::SendAccept", _config
->FindB("Acquire::http::SendAccept", true)) == true)
384 size_t const filepos
= Itm
->Uri
.find_last_of('/');
385 string
const file
= Itm
->Uri
.substr(filepos
+ 1);
386 if (flExtension(file
) == file
)
387 headers
= curl_slist_append(headers
, "Accept: text/*");
390 // if we have the file send an if-range query with a range header
391 if (stat(Itm
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
394 strprintf(Buf
, "Range: bytes=%lli-", (long long) SBuf
.st_size
);
395 headers
= curl_slist_append(headers
, Buf
.c_str());
396 strprintf(Buf
, "If-Range: %s", TimeRFC1123(SBuf
.st_mtime
).c_str());
397 headers
= curl_slist_append(headers
, Buf
.c_str());
399 else if(Itm
->LastModified
> 0)
401 curl_easy_setopt(curl
, CURLOPT_TIMECONDITION
, CURL_TIMECOND_IFMODSINCE
);
402 curl_easy_setopt(curl
, CURLOPT_TIMEVALUE
, Itm
->LastModified
);
405 // go for it - if the file exists, append on it
406 File
= new FileFd(Itm
->DestFile
, FileFd::WriteAny
);
407 Server
= CreateServerState(Itm
->Uri
);
408 if (Server
->InitHashes(Itm
->ExpectedHashes
) == false)
412 Res
.Filename
= Itm
->DestFile
;
415 CURLcode success
= curl_easy_perform(curl
);
417 // If the server returns 200 OK but the If-Modified-Since condition is not
418 // met, CURLINFO_CONDITION_UNMET will be set to 1
419 long curl_condition_unmet
= 0;
420 curl_easy_getinfo(curl
, CURLINFO_CONDITION_UNMET
, &curl_condition_unmet
);
423 curl_slist_free_all(headers
);
426 if (success
!= CURLE_OK
)
428 #pragma GCC diagnostic push
429 #pragma GCC diagnostic ignored "-Wswitch"
432 case CURLE_COULDNT_RESOLVE_PROXY
:
433 case CURLE_COULDNT_RESOLVE_HOST
:
434 SetFailReason("ResolveFailure");
436 case CURLE_COULDNT_CONNECT
:
437 SetFailReason("ConnectionRefused");
439 case CURLE_OPERATION_TIMEDOUT
:
440 SetFailReason("Timeout");
443 #pragma GCC diagnostic pop
444 // only take curls technical errors if we haven't our own
445 // (e.g. for the maximum size limit we have and curls can be confusing)
446 if (_error
->PendingError() == false)
447 _error
->Error("%s", curl_errorstr
);
449 _error
->Warning("curl: %s", curl_errorstr
);
453 // server says file not modified
454 if (Server
->Result
== 304 || curl_condition_unmet
== 1)
456 RemoveFile("https", File
->Name());
458 Res
.LastModified
= Itm
->LastModified
;
465 if (Server
->Result
!= 200 && // OK
466 Server
->Result
!= 206 && // Partial
467 Server
->Result
!= 416) // invalid Range
470 snprintf(err
, sizeof(err
) - 1, "HttpError%i", Server
->Result
);
472 _error
->Error("%i %s", Server
->Result
, Server
->Code
);
473 // unlink, no need keep 401/404 page content in partial/
474 RemoveFile("https", File
->Name());
478 // invalid range-request
479 if (Server
->Result
== 416)
481 RemoveFile("https", File
->Name());
487 struct stat resultStat
;
488 if (unlikely(stat(File
->Name().c_str(), &resultStat
) != 0))
490 _error
->Errno("stat", "Unable to access file %s", File
->Name().c_str());
493 Res
.Size
= resultStat
.st_size
;
496 curl_easy_getinfo(curl
, CURLINFO_FILETIME
, &Res
.LastModified
);
497 if (Res
.LastModified
!= -1)
499 struct timeval times
[2];
500 times
[0].tv_sec
= Res
.LastModified
;
501 times
[1].tv_sec
= Res
.LastModified
;
502 times
[0].tv_usec
= times
[1].tv_usec
= 0;
503 utimes(File
->Name().c_str(), times
);
506 Res
.LastModified
= resultStat
.st_mtime
;
509 Res
.TakeHashes(*(Server
->GetHashes()));
520 // HttpsMethod::Configuration - Handle a configuration message /*{{{*/
521 bool HttpsMethod::Configuration(string Message
)
523 if (ServerMethod::Configuration(Message
) == false)
526 AllowRedirect
= _config
->FindB("Acquire::https::AllowRedirect",
527 _config
->FindB("Acquire::http::AllowRedirect", true));
528 Debug
= _config
->FindB("Debug::Acquire::https",false);
533 std::unique_ptr
<ServerState
> HttpsMethod::CreateServerState(URI
const &uri
)/*{{{*/
535 return std::unique_ptr
<ServerState
>(new HttpsServerState(uri
, this));
541 setlocale(LC_ALL
, "");
544 curl_global_init(CURL_GLOBAL_SSL
) ;