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