]> git.saurik.com Git - apt.git/blob - methods/https.cc
implement Fallback-Of for IndexTargets
[apt.git] / methods / https.cc
1 //-*- mode: cpp; mode: fold -*-
2 // Description /*{{{*/
3 // $Id: http.cc,v 1.59 2004/05/08 19:42:35 mdz Exp $
4 /* ######################################################################
5
6 HTTPS Acquire Method - This is the HTTPS acquire method for APT.
7
8 It uses libcurl
9
10 ##################################################################### */
11 /*}}}*/
12 // Include Files /*{{{*/
13 #include <config.h>
14
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>
24
25 #include <sys/stat.h>
26 #include <sys/time.h>
27 #include <unistd.h>
28 #include <stdio.h>
29 #include <iostream>
30 #include <sstream>
31 #include <ctype.h>
32 #include <stdlib.h>
33
34 #include "https.h"
35
36 #include <apti18n.h>
37 /*}}}*/
38 using namespace std;
39
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) {}
46 };
47
48 size_t
49 HttpsMethod::parse_header(void *buffer, size_t size, size_t nmemb, void *userp)
50 {
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)
56 {
57 ++len;
58 break;
59 }
60 line.erase(len);
61
62 if (line.empty() == true)
63 {
64 if (me->https->Server->Result != 416 && me->https->Server->StartPos != 0)
65 ;
66 else if (me->https->Server->Result == 416)
67 {
68 bool partialHit = false;
69 if (me->Itm->ExpectedHashes.usable() == true)
70 {
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);
78 }
79 else if (me->https->Server->Result == 416 && me->https->Server->TotalFileSize == me->https->File->FileSize())
80 partialHit = true;
81
82 if (partialHit == true)
83 {
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();
89 }
90 else
91 me->https->Server->StartPos = 0;
92 }
93 else
94 me->https->Server->StartPos = 0;
95
96 me->Res->LastModified = me->https->Server->Date;
97 me->Res->Size = me->https->Server->TotalFileSize;
98 me->Res->ResumePoint = me->https->Server->StartPos;
99
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)
102 {
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)
106 return 0;
107 }
108 }
109 else if (me->https->Server->HeaderLine(line) == false)
110 return 0;
111
112 return size*nmemb;
113 }
114
115 size_t
116 HttpsMethod::write_data(void *buffer, size_t size, size_t nmemb, void *userp)
117 {
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)
123 return buffer_size;
124
125 if(me->File->Write(buffer, buffer_size) != true)
126 return 0;
127
128 if(me->Queue->MaximumSize > 0)
129 {
130 unsigned long long const TotalWritten = me->File->Tell();
131 if (TotalWritten > me->Queue->MaximumSize)
132 {
133 me->SetFailReason("MaximumSizeExceeded");
134 _error->Error("Writing more data than expected (%llu > %llu)",
135 TotalWritten, me->Queue->MaximumSize);
136 return 0;
137 }
138 }
139
140 if (me->Server->GetHashes()->Add((unsigned char const * const)buffer, buffer_size) == false)
141 return 0;
142
143 return buffer_size;
144 }
145
146 // HttpsServerState::HttpsServerState - Constructor /*{{{*/
147 HttpsServerState::HttpsServerState(URI Srv,HttpsMethod * Owner) : ServerState(Srv, Owner), Hash(NULL)
148 {
149 TimeOut = _config->FindI("Acquire::https::Timeout",TimeOut);
150 Reset();
151 }
152 /*}}}*/
153 bool HttpsServerState::InitHashes(HashStringList const &ExpectedHashes) /*{{{*/
154 {
155 delete Hash;
156 Hash = new Hashes(ExpectedHashes);
157 return true;
158 }
159 /*}}}*/
160 APT_PURE Hashes * HttpsServerState::GetHashes() /*{{{*/
161 {
162 return Hash;
163 }
164 /*}}}*/
165
166 void HttpsMethod::SetupProxy() /*{{{*/
167 {
168 URI ServerName = Queue->Uri;
169
170 // Determine the proxy setting
171 AutoDetectProxy(ServerName);
172
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, "");
178
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());
182
183 if (UseProxy.empty() == true)
184 UseProxy = _config->Find("Acquire::https::Proxy", _config->Find("Acquire::http::Proxy").c_str());
185
186 // User want to use NO proxy, so nothing to setup
187 if (UseProxy == "DIRECT")
188 return;
189
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)
193 return;
194
195 if (UseProxy.empty() == true)
196 {
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
202 // should Apt.
203 if (result == NULL)
204 result = getenv("http_proxy");
205 UseProxy = result == NULL ? "" : result;
206 }
207
208 // Determine what host and port to use based on the proxy settings
209 if (UseProxy.empty() == false)
210 {
211 Proxy = UseProxy;
212 if (Proxy.Port != 1)
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)
216 {
217 curl_easy_setopt(curl, CURLOPT_PROXYUSERNAME, Proxy.User.c_str());
218 curl_easy_setopt(curl, CURLOPT_PROXYPASSWORD, Proxy.Password.c_str());
219 }
220 }
221 } /*}}}*/
222 // HttpsMethod::Fetch - Fetch an item /*{{{*/
223 // ---------------------------------------------------------------------
224 /* This adds an item to the pipeline. We keep the pipeline at a fixed
225 depth. */
226 bool HttpsMethod::Fetch(FetchItem *Itm)
227 {
228 struct stat SBuf;
229 struct curl_slist *headers=NULL;
230 char curl_errorstr[CURL_ERROR_SIZE];
231 URI Uri = Itm->Uri;
232 string remotehost = Uri.Host;
233
234 // TODO:
235 // - http::Pipeline-Depth
236 // - error checking/reporting
237 // - more debug options? (CURLOPT_DEBUGFUNCTION?)
238
239 curl_easy_reset(curl);
240 SetupProxy();
241
242 maybe_add_auth (Uri, _config->FindFile("Dir::Etc::netrc"));
243
244 FetchResult Res;
245 CURLUserPointer userp(this, &Res, Itm);
246 // callbacks
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);
252 // options
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);
258
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.
261
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());
268
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);
274
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);
281
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());
288
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());
295
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());
302
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);
314
315 // CRL file
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());
321
322 // cache-control
323 if(_config->FindB("Acquire::https::No-Cache",
324 _config->FindB("Acquire::http::No-Cache",false)) == false)
325 {
326 // cache enabled
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");
330 stringstream ss;
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());
334 } else {
335 // cache disabled by user
336 headers = curl_slist_append(headers, "Cache-Control: no-cache");
337 headers = curl_slist_append(headers, "Pragma: no-cache");
338 }
339 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
340
341 // speed limit
342 int const dlLimit = _config->FindI("Acquire::https::Dl-Limit",
343 _config->FindI("Acquire::http::Dl-Limit",0))*1024;
344 if (dlLimit > 0)
345 curl_easy_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE, dlLimit);
346
347 // set header
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());
352
353 // set timeout
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);
360
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);
364
365 // debug
366 if (Debug == true)
367 curl_easy_setopt(curl, CURLOPT_VERBOSE, true);
368
369 // error handling
370 curl_errorstr[0] = '\0';
371 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_errorstr);
372
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)
379 {
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/*");
384 }
385
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)
388 {
389 std::string Buf;
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());
394 }
395 else if(Itm->LastModified > 0)
396 {
397 curl_easy_setopt(curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
398 curl_easy_setopt(curl, CURLOPT_TIMEVALUE, Itm->LastModified);
399 }
400
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)
405 return false;
406
407 // keep apt updated
408 Res.Filename = Itm->DestFile;
409
410 // get it!
411 CURLcode success = curl_easy_perform(curl);
412
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);
417
418 File->Close();
419 curl_slist_free_all(headers);
420
421 // cleanup
422 if (success != CURLE_OK)
423 {
424 #pragma GCC diagnostic push
425 #pragma GCC diagnostic ignored "-Wswitch"
426 switch (success)
427 {
428 case CURLE_COULDNT_RESOLVE_PROXY:
429 case CURLE_COULDNT_RESOLVE_HOST:
430 SetFailReason("ResolveFailure");
431 break;
432 case CURLE_COULDNT_CONNECT:
433 SetFailReason("ConnectionRefused");
434 break;
435 case CURLE_OPERATION_TIMEDOUT:
436 SetFailReason("Timeout");
437 break;
438 }
439 #pragma GCC diagnostic pop
440 return _error->Error("%s", curl_errorstr);
441 }
442
443 // server says file not modified
444 if (Server->Result == 304 || curl_condition_unmet == 1)
445 {
446 RemoveFile("https", File->Name());
447 Res.IMSHit = true;
448 Res.LastModified = Itm->LastModified;
449 Res.Size = 0;
450 URIDone(Res);
451 return true;
452 }
453 Res.IMSHit = false;
454
455 if (Server->Result != 200 && // OK
456 Server->Result != 206 && // Partial
457 Server->Result != 416) // invalid Range
458 {
459 char err[255];
460 snprintf(err, sizeof(err) - 1, "HttpError%i", Server->Result);
461 SetFailReason(err);
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());
465 return false;
466 }
467
468 // invalid range-request
469 if (Server->Result == 416)
470 {
471 RemoveFile("https", File->Name());
472 delete File;
473 Redirect(Itm->Uri);
474 return true;
475 }
476
477 struct stat resultStat;
478 if (unlikely(stat(File->Name().c_str(), &resultStat) != 0))
479 {
480 _error->Errno("stat", "Unable to access file %s", File->Name().c_str());
481 return false;
482 }
483 Res.Size = resultStat.st_size;
484
485 // Timestamp
486 curl_easy_getinfo(curl, CURLINFO_FILETIME, &Res.LastModified);
487 if (Res.LastModified != -1)
488 {
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);
494 }
495 else
496 Res.LastModified = resultStat.st_mtime;
497
498 // take hashes
499 Res.TakeHashes(*(Server->GetHashes()));
500
501 // keep apt updated
502 URIDone(Res);
503
504 // cleanup
505 delete File;
506
507 return true;
508 }
509 /*}}}*/
510 // HttpsMethod::Configuration - Handle a configuration message /*{{{*/
511 bool HttpsMethod::Configuration(string Message)
512 {
513 if (ServerMethod::Configuration(Message) == false)
514 return false;
515
516 AllowRedirect = _config->FindB("Acquire::https::AllowRedirect",
517 _config->FindB("Acquire::http::AllowRedirect", true));
518 Debug = _config->FindB("Debug::Acquire::https",false);
519
520 return true;
521 }
522 /*}}}*/
523 std::unique_ptr<ServerState> HttpsMethod::CreateServerState(URI const &uri)/*{{{*/
524 {
525 return std::unique_ptr<ServerState>(new HttpsServerState(uri, this));
526 }
527 /*}}}*/
528
529 int main()
530 {
531 setlocale(LC_ALL, "");
532
533 HttpsMethod Mth;
534 curl_global_init(CURL_GLOBAL_SSL) ;
535
536 return Mth.Run();
537 }
538