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 CURLUserPointer(HttpsMethod
* const https
, HttpsMethod::FetchResult
* const Res
) : https(https
), Res(Res
) {}
47 HttpsMethod::parse_header(void *buffer
, size_t size
, size_t nmemb
, void *userp
)
49 size_t len
= size
* nmemb
;
50 CURLUserPointer
*me
= (CURLUserPointer
*)userp
;
51 std::string
line((char*) buffer
, len
);
52 for (--len
; len
> 0; --len
)
53 if (isspace(line
[len
]) == 0)
60 if (line
.empty() == true)
62 if (me
->https
->Server
->Result
!= 416 && me
->https
->Server
->StartPos
!= 0)
64 else if (me
->https
->Server
->Result
== 416 && me
->https
->Server
->Size
== me
->https
->File
->FileSize())
66 me
->https
->Server
->Result
= 200;
67 me
->https
->Server
->StartPos
= me
->https
->Server
->Size
;
68 // the actual size is not important for https as curl will deal with it
69 // by itself and e.g. doesn't bother us with transport-encoding…
70 me
->https
->Server
->JunkSize
= std::numeric_limits
<unsigned long long>::max();
73 me
->https
->Server
->StartPos
= 0;
75 me
->https
->File
->Truncate(me
->https
->Server
->StartPos
);
76 me
->https
->File
->Seek(me
->https
->Server
->StartPos
);
78 me
->Res
->LastModified
= me
->https
->Server
->Date
;
79 me
->Res
->Size
= me
->https
->Server
->Size
;
80 me
->Res
->ResumePoint
= me
->https
->Server
->StartPos
;
82 // we expect valid data, so tell our caller we get the file now
83 if (me
->https
->Server
->Result
>= 200 && me
->https
->Server
->Result
< 300 &&
84 me
->https
->Server
->JunkSize
== 0 &&
85 me
->Res
->Size
!= 0 && me
->Res
->Size
> me
->Res
->ResumePoint
)
86 me
->https
->URIStart(*me
->Res
);
88 else if (me
->https
->Server
->HeaderLine(line
) == false)
95 HttpsMethod::write_data(void *buffer
, size_t size
, size_t nmemb
, void *userp
)
97 HttpsMethod
*me
= (HttpsMethod
*)userp
;
98 size_t buffer_size
= size
* nmemb
;
99 // we don't need to count the junk here, just drop anything we get as
100 // we don't always know how long it would be, e.g. in chunked encoding.
101 if (me
->Server
->JunkSize
!= 0)
104 if(me
->File
->Write(buffer
, buffer_size
) != true)
107 if(me
->Queue
->MaximumSize
> 0)
109 unsigned long long const TotalWritten
= me
->File
->Tell();
110 if (TotalWritten
> me
->Queue
->MaximumSize
)
112 me
->SetFailReason("MaximumSizeExceeded");
113 _error
->Error("Writing more data than expected (%llu > %llu)",
114 TotalWritten
, me
->Queue
->MaximumSize
);
122 // HttpsServerState::HttpsServerState - Constructor /*{{{*/
123 HttpsServerState::HttpsServerState(URI Srv
,HttpsMethod
* Owner
) : ServerState(Srv
, Owner
)
125 TimeOut
= _config
->FindI("Acquire::https::Timeout",TimeOut
);
130 void HttpsMethod::SetupProxy() /*{{{*/
132 URI ServerName
= Queue
->Uri
;
134 // Determine the proxy setting
135 AutoDetectProxy(ServerName
);
137 // Curl should never read proxy settings from the environment, as
138 // we determine which proxy to use. Do this for consistency among
139 // methods and prevent an environment variable overriding a
140 // no-proxy ("DIRECT") setting in apt.conf.
141 curl_easy_setopt(curl
, CURLOPT_PROXY
, "");
143 // Determine the proxy setting - try https first, fallback to http and use env at last
144 string UseProxy
= _config
->Find("Acquire::https::Proxy::" + ServerName
.Host
,
145 _config
->Find("Acquire::http::Proxy::" + ServerName
.Host
).c_str());
147 if (UseProxy
.empty() == true)
148 UseProxy
= _config
->Find("Acquire::https::Proxy", _config
->Find("Acquire::http::Proxy").c_str());
150 // User want to use NO proxy, so nothing to setup
151 if (UseProxy
== "DIRECT")
154 if (UseProxy
.empty() == false)
156 // Parse no_proxy, a comma (,) separated list of domains we don't want to use
157 // a proxy for so we stop right here if it is in the list
158 if (getenv("no_proxy") != 0 && CheckDomainList(ServerName
.Host
,getenv("no_proxy")) == true)
161 const char* result
= getenv("https_proxy");
162 // FIXME: Fall back to http_proxy is to remain compatible with
163 // existing setups and behaviour of apt.conf. This should be
164 // deprecated in the future (including apt.conf). Most other
165 // programs do not fall back to http proxy settings and neither
168 result
= getenv("http_proxy");
169 UseProxy
= result
== NULL
? "" : result
;
172 // Determine what host and port to use based on the proxy settings
173 if (UseProxy
.empty() == false)
177 curl_easy_setopt(curl
, CURLOPT_PROXYPORT
, Proxy
.Port
);
178 curl_easy_setopt(curl
, CURLOPT_PROXY
, Proxy
.Host
.c_str());
179 if (Proxy
.User
.empty() == false || Proxy
.Password
.empty() == false)
181 curl_easy_setopt(curl
, CURLOPT_PROXYUSERNAME
, Proxy
.User
.c_str());
182 curl_easy_setopt(curl
, CURLOPT_PROXYPASSWORD
, Proxy
.Password
.c_str());
186 // HttpsMethod::Fetch - Fetch an item /*{{{*/
187 // ---------------------------------------------------------------------
188 /* This adds an item to the pipeline. We keep the pipeline at a fixed
190 bool HttpsMethod::Fetch(FetchItem
*Itm
)
193 struct curl_slist
*headers
=NULL
;
194 char curl_errorstr
[CURL_ERROR_SIZE
];
196 string remotehost
= Uri
.Host
;
199 // - http::Pipeline-Depth
200 // - error checking/reporting
201 // - more debug options? (CURLOPT_DEBUGFUNCTION?)
203 curl_easy_reset(curl
);
206 maybe_add_auth (Uri
, _config
->FindFile("Dir::Etc::netrc"));
209 CURLUserPointer
userp(this, &Res
);
211 curl_easy_setopt(curl
, CURLOPT_URL
, static_cast<string
>(Uri
).c_str());
212 curl_easy_setopt(curl
, CURLOPT_HEADERFUNCTION
, parse_header
);
213 curl_easy_setopt(curl
, CURLOPT_WRITEHEADER
, &userp
);
214 curl_easy_setopt(curl
, CURLOPT_WRITEFUNCTION
, write_data
);
215 curl_easy_setopt(curl
, CURLOPT_WRITEDATA
, this);
217 curl_easy_setopt(curl
, CURLOPT_NOPROGRESS
, true);
218 curl_easy_setopt(curl
, CURLOPT_FILETIME
, true);
219 // only allow curl to handle https, not the other stuff it supports
220 curl_easy_setopt(curl
, CURLOPT_PROTOCOLS
, CURLPROTO_HTTPS
);
221 curl_easy_setopt(curl
, CURLOPT_REDIR_PROTOCOLS
, CURLPROTO_HTTPS
);
223 // SSL parameters are set by default to the common (non mirror-specific) value
224 // if available (or a default one) and gets overload by mirror-specific ones.
226 // File containing the list of trusted CA.
227 string cainfo
= _config
->Find("Acquire::https::CaInfo","");
228 string knob
= "Acquire::https::"+remotehost
+"::CaInfo";
229 cainfo
= _config
->Find(knob
.c_str(),cainfo
.c_str());
230 if(cainfo
.empty() == false)
231 curl_easy_setopt(curl
, CURLOPT_CAINFO
,cainfo
.c_str());
233 // Check server certificate against previous CA list ...
234 bool peer_verify
= _config
->FindB("Acquire::https::Verify-Peer",true);
235 knob
= "Acquire::https::" + remotehost
+ "::Verify-Peer";
236 peer_verify
= _config
->FindB(knob
.c_str(), peer_verify
);
237 curl_easy_setopt(curl
, CURLOPT_SSL_VERIFYPEER
, peer_verify
);
239 // ... and hostname against cert CN or subjectAltName
240 bool verify
= _config
->FindB("Acquire::https::Verify-Host",true);
241 knob
= "Acquire::https::"+remotehost
+"::Verify-Host";
242 verify
= _config
->FindB(knob
.c_str(),verify
);
243 int const default_verify
= (verify
== true) ? 2 : 0;
244 curl_easy_setopt(curl
, CURLOPT_SSL_VERIFYHOST
, default_verify
);
246 // Also enforce issuer of server certificate using its cert
247 string issuercert
= _config
->Find("Acquire::https::IssuerCert","");
248 knob
= "Acquire::https::"+remotehost
+"::IssuerCert";
249 issuercert
= _config
->Find(knob
.c_str(),issuercert
.c_str());
250 if(issuercert
.empty() == false)
251 curl_easy_setopt(curl
, CURLOPT_ISSUERCERT
,issuercert
.c_str());
253 // For client authentication, certificate file ...
254 string pem
= _config
->Find("Acquire::https::SslCert","");
255 knob
= "Acquire::https::"+remotehost
+"::SslCert";
256 pem
= _config
->Find(knob
.c_str(),pem
.c_str());
257 if(pem
.empty() == false)
258 curl_easy_setopt(curl
, CURLOPT_SSLCERT
, pem
.c_str());
260 // ... and associated key.
261 string key
= _config
->Find("Acquire::https::SslKey","");
262 knob
= "Acquire::https::"+remotehost
+"::SslKey";
263 key
= _config
->Find(knob
.c_str(),key
.c_str());
264 if(key
.empty() == false)
265 curl_easy_setopt(curl
, CURLOPT_SSLKEY
, key
.c_str());
267 // Allow forcing SSL version to SSLv3 or TLSv1 (SSLv2 is not
268 // supported by GnuTLS).
269 long final_version
= CURL_SSLVERSION_DEFAULT
;
270 string sslversion
= _config
->Find("Acquire::https::SslForceVersion","");
271 knob
= "Acquire::https::"+remotehost
+"::SslForceVersion";
272 sslversion
= _config
->Find(knob
.c_str(),sslversion
.c_str());
273 if(sslversion
== "TLSv1")
274 final_version
= CURL_SSLVERSION_TLSv1
;
275 else if(sslversion
== "SSLv3")
276 final_version
= CURL_SSLVERSION_SSLv3
;
277 curl_easy_setopt(curl
, CURLOPT_SSLVERSION
, final_version
);
280 string crlfile
= _config
->Find("Acquire::https::CrlFile","");
281 knob
= "Acquire::https::"+remotehost
+"::CrlFile";
282 crlfile
= _config
->Find(knob
.c_str(),crlfile
.c_str());
283 if(crlfile
.empty() == false)
284 curl_easy_setopt(curl
, CURLOPT_CRLFILE
, crlfile
.c_str());
287 if(_config
->FindB("Acquire::https::No-Cache",
288 _config
->FindB("Acquire::http::No-Cache",false)) == false)
291 if (_config
->FindB("Acquire::https::No-Store",
292 _config
->FindB("Acquire::http::No-Store",false)) == true)
293 headers
= curl_slist_append(headers
,"Cache-Control: no-store");
295 ioprintf(ss
, "Cache-Control: max-age=%u", _config
->FindI("Acquire::https::Max-Age",
296 _config
->FindI("Acquire::http::Max-Age",0)));
297 headers
= curl_slist_append(headers
, ss
.str().c_str());
299 // cache disabled by user
300 headers
= curl_slist_append(headers
, "Cache-Control: no-cache");
301 headers
= curl_slist_append(headers
, "Pragma: no-cache");
303 curl_easy_setopt(curl
, CURLOPT_HTTPHEADER
, headers
);
306 int const dlLimit
= _config
->FindI("Acquire::https::Dl-Limit",
307 _config
->FindI("Acquire::http::Dl-Limit",0))*1024;
309 curl_easy_setopt(curl
, CURLOPT_MAX_RECV_SPEED_LARGE
, dlLimit
);
312 curl_easy_setopt(curl
, CURLOPT_USERAGENT
,
313 _config
->Find("Acquire::https::User-Agent",
314 _config
->Find("Acquire::http::User-Agent",
315 "Debian APT-CURL/1.0 (" PACKAGE_VERSION
")").c_str()).c_str());
318 int const timeout
= _config
->FindI("Acquire::https::Timeout",
319 _config
->FindI("Acquire::http::Timeout",120));
320 curl_easy_setopt(curl
, CURLOPT_CONNECTTIMEOUT
, timeout
);
321 //set really low lowspeed timeout (see #497983)
322 curl_easy_setopt(curl
, CURLOPT_LOW_SPEED_LIMIT
, DL_MIN_SPEED
);
323 curl_easy_setopt(curl
, CURLOPT_LOW_SPEED_TIME
, timeout
);
325 // set redirect options and default to 10 redirects
326 curl_easy_setopt(curl
, CURLOPT_FOLLOWLOCATION
, AllowRedirect
);
327 curl_easy_setopt(curl
, CURLOPT_MAXREDIRS
, 10);
331 curl_easy_setopt(curl
, CURLOPT_VERBOSE
, true);
334 curl_errorstr
[0] = '\0';
335 curl_easy_setopt(curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
337 // If we ask for uncompressed files servers might respond with content-
338 // negotiation which lets us end up with compressed files we do not support,
339 // see 657029, 657560 and co, so if we have no extension on the request
340 // ask for text only. As a sidenote: If there is nothing to negotate servers
341 // seem to be nice and ignore it.
342 if (_config
->FindB("Acquire::https::SendAccept", _config
->FindB("Acquire::http::SendAccept", true)) == true)
344 size_t const filepos
= Itm
->Uri
.find_last_of('/');
345 string
const file
= Itm
->Uri
.substr(filepos
+ 1);
346 if (flExtension(file
) == file
)
347 headers
= curl_slist_append(headers
, "Accept: text/*");
350 // if we have the file send an if-range query with a range header
351 if (stat(Itm
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
354 strprintf(Buf
, "Range: bytes=%lli-", (long long) SBuf
.st_size
);
355 headers
= curl_slist_append(headers
, Buf
.c_str());
356 strprintf(Buf
, "If-Range: %s", TimeRFC1123(SBuf
.st_mtime
).c_str());
357 headers
= curl_slist_append(headers
, Buf
.c_str());
359 else if(Itm
->LastModified
> 0)
361 curl_easy_setopt(curl
, CURLOPT_TIMECONDITION
, CURL_TIMECOND_IFMODSINCE
);
362 curl_easy_setopt(curl
, CURLOPT_TIMEVALUE
, Itm
->LastModified
);
365 // go for it - if the file exists, append on it
366 File
= new FileFd(Itm
->DestFile
, FileFd::WriteAny
);
367 Server
= CreateServerState(Itm
->Uri
);
370 Res
.Filename
= Itm
->DestFile
;
373 CURLcode success
= curl_easy_perform(curl
);
375 // If the server returns 200 OK but the If-Modified-Since condition is not
376 // met, CURLINFO_CONDITION_UNMET will be set to 1
377 long curl_condition_unmet
= 0;
378 curl_easy_getinfo(curl
, CURLINFO_CONDITION_UNMET
, &curl_condition_unmet
);
381 curl_slist_free_all(headers
);
386 _error
->Error("%s", curl_errorstr
);
390 // server says file not modified
391 if (Server
->Result
== 304 || curl_condition_unmet
== 1)
393 unlink(File
->Name().c_str());
395 Res
.LastModified
= Itm
->LastModified
;
402 if (Server
->Result
!= 200 && // OK
403 Server
->Result
!= 206 && // Partial
404 Server
->Result
!= 416) // invalid Range
407 snprintf(err
, sizeof(err
) - 1, "HttpError%i", Server
->Result
);
409 _error
->Error("%s", err
);
410 // unlink, no need keep 401/404 page content in partial/
411 unlink(File
->Name().c_str());
415 // invalid range-request
416 if (Server
->Result
== 416)
418 unlink(File
->Name().c_str());
424 struct stat resultStat
;
425 if (unlikely(stat(File
->Name().c_str(), &resultStat
) != 0))
427 _error
->Errno("stat", "Unable to access file %s", File
->Name().c_str());
430 Res
.Size
= resultStat
.st_size
;
433 curl_easy_getinfo(curl
, CURLINFO_FILETIME
, &Res
.LastModified
);
434 if (Res
.LastModified
!= -1)
436 struct timeval times
[2];
437 times
[0].tv_sec
= Res
.LastModified
;
438 times
[1].tv_sec
= Res
.LastModified
;
439 times
[0].tv_usec
= times
[1].tv_usec
= 0;
440 utimes(File
->Name().c_str(), times
);
443 Res
.LastModified
= resultStat
.st_mtime
;
447 FileFd
Fd(Res
.Filename
, FileFd::ReadOnly
);
449 Res
.TakeHashes(Hash
);
460 // HttpsMethod::Configuration - Handle a configuration message /*{{{*/
461 bool HttpsMethod::Configuration(string Message
)
463 if (ServerMethod::Configuration(Message
) == false)
466 AllowRedirect
= _config
->FindB("Acquire::https::AllowRedirect",
467 _config
->FindB("Acquire::http::AllowRedirect", true));
468 Debug
= _config
->FindB("Debug::Acquire::https",false);
473 ServerState
* HttpsMethod::CreateServerState(URI uri
) /*{{{*/
475 return new HttpsServerState(uri
, this);
481 setlocale(LC_ALL
, "");
484 curl_global_init(CURL_GLOBAL_SSL
) ;