]> git.saurik.com Git - apt.git/blob - methods/https.cc
a5a8a7cd1ef183f7a4e00e04725d2f3519f042bf
[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/error.h>
17 #include <apt-pkg/hashes.h>
18 #include <apt-pkg/netrc.h>
19 #include <apt-pkg/configuration.h>
20 #include <apt-pkg/macros.h>
21 #include <apt-pkg/strutl.h>
22 #include <apt-pkg/proxy.h>
23
24 #include <sys/stat.h>
25 #include <sys/time.h>
26 #include <unistd.h>
27 #include <stdio.h>
28 #include <iostream>
29 #include <sstream>
30 #include <ctype.h>
31 #include <stdlib.h>
32
33 #include "https.h"
34
35 #include <apti18n.h>
36 /*}}}*/
37 using namespace std;
38
39 struct APT_HIDDEN CURLUserPointer {
40 HttpsMethod * const https;
41 HttpsMethod::FetchResult * const Res;
42 HttpsMethod::FetchItem const * const Itm;
43 CURLUserPointer(HttpsMethod * const https, HttpsMethod::FetchResult * const Res,
44 HttpsMethod::FetchItem const * const Itm) : https(https), Res(Res), Itm(Itm) {}
45 };
46
47 size_t
48 HttpsMethod::parse_header(void *buffer, size_t size, size_t nmemb, void *userp)
49 {
50 size_t len = size * nmemb;
51 CURLUserPointer *me = static_cast<CURLUserPointer *>(userp);
52 std::string line((char*) buffer, len);
53 for (--len; len > 0; --len)
54 if (isspace_ascii(line[len]) == 0)
55 {
56 ++len;
57 break;
58 }
59 line.erase(len);
60
61 if (line.empty() == true)
62 {
63 me->https->Server->JunkSize = 0;
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->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 else
109 me->https->Server->JunkSize = std::numeric_limits<decltype(me->https->Server->JunkSize)>::max();
110 }
111 else if (me->https->Server->HeaderLine(line) == false)
112 return 0;
113
114 return size*nmemb;
115 }
116
117 size_t
118 HttpsMethod::write_data(void *buffer, size_t size, size_t nmemb, void *userp)
119 {
120 HttpsMethod *me = static_cast<HttpsMethod *>(userp);
121 size_t buffer_size = size * nmemb;
122 // we don't need to count the junk here, just drop anything we get as
123 // we don't always know how long it would be, e.g. in chunked encoding.
124 if (me->Server->JunkSize != 0)
125 return buffer_size;
126
127 if(me->File->Write(buffer, buffer_size) != true)
128 return 0;
129
130 if(me->Queue->MaximumSize > 0)
131 {
132 unsigned long long const TotalWritten = me->File->Tell();
133 if (TotalWritten > me->Queue->MaximumSize)
134 {
135 me->SetFailReason("MaximumSizeExceeded");
136 _error->Error("Writing more data than expected (%llu > %llu)",
137 TotalWritten, me->Queue->MaximumSize);
138 return 0;
139 }
140 }
141
142 if (me->Server->GetHashes()->Add((unsigned char const * const)buffer, buffer_size) == false)
143 return 0;
144
145 return buffer_size;
146 }
147
148 // HttpsServerState::HttpsServerState - Constructor /*{{{*/
149 HttpsServerState::HttpsServerState(URI Srv,HttpsMethod * Owner) : ServerState(Srv, Owner), Hash(NULL)
150 {
151 TimeOut = _config->FindI("Acquire::https::Timeout",TimeOut);
152 Reset();
153 }
154 /*}}}*/
155 bool HttpsServerState::InitHashes(HashStringList const &ExpectedHashes) /*{{{*/
156 {
157 delete Hash;
158 Hash = new Hashes(ExpectedHashes);
159 return true;
160 }
161 /*}}}*/
162 APT_PURE Hashes * HttpsServerState::GetHashes() /*{{{*/
163 {
164 return Hash;
165 }
166 /*}}}*/
167
168 bool HttpsMethod::SetupProxy() /*{{{*/
169 {
170 URI ServerName = Queue->Uri;
171
172 // Determine the proxy setting
173 AutoDetectProxy(ServerName);
174
175 // Curl should never read proxy settings from the environment, as
176 // we determine which proxy to use. Do this for consistency among
177 // methods and prevent an environment variable overriding a
178 // no-proxy ("DIRECT") setting in apt.conf.
179 curl_easy_setopt(curl, CURLOPT_PROXY, "");
180
181 // Determine the proxy setting - try https first, fallback to http and use env at last
182 string UseProxy = _config->Find("Acquire::https::Proxy::" + ServerName.Host,
183 _config->Find("Acquire::http::Proxy::" + ServerName.Host).c_str());
184
185 if (UseProxy.empty() == true)
186 UseProxy = _config->Find("Acquire::https::Proxy", _config->Find("Acquire::http::Proxy").c_str());
187
188 // User want to use NO proxy, so nothing to setup
189 if (UseProxy == "DIRECT")
190 return true;
191
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)
195 return true;
196
197 if (UseProxy.empty() == true)
198 {
199 const char* result = getenv("https_proxy");
200 // FIXME: Fall back to http_proxy is to remain compatible with
201 // existing setups and behaviour of apt.conf. This should be
202 // deprecated in the future (including apt.conf). Most other
203 // programs do not fall back to http proxy settings and neither
204 // should Apt.
205 if (result == NULL)
206 result = getenv("http_proxy");
207 UseProxy = result == NULL ? "" : result;
208 }
209
210 // Determine what host and port to use based on the proxy settings
211 if (UseProxy.empty() == false)
212 {
213 Proxy = UseProxy;
214 if (Proxy.Access == "socks5h")
215 curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
216 else if (Proxy.Access == "socks5")
217 curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
218 else if (Proxy.Access == "socks4a")
219 curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
220 else if (Proxy.Access == "socks")
221 curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
222 else if (Proxy.Access == "http" || Proxy.Access == "https")
223 curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
224 else
225 return false;
226
227 if (Proxy.Port != 1)
228 curl_easy_setopt(curl, CURLOPT_PROXYPORT, Proxy.Port);
229 curl_easy_setopt(curl, CURLOPT_PROXY, Proxy.Host.c_str());
230 if (Proxy.User.empty() == false || Proxy.Password.empty() == false)
231 {
232 curl_easy_setopt(curl, CURLOPT_PROXYUSERNAME, Proxy.User.c_str());
233 curl_easy_setopt(curl, CURLOPT_PROXYPASSWORD, Proxy.Password.c_str());
234 }
235 }
236 return true;
237 } /*}}}*/
238 // HttpsMethod::Fetch - Fetch an item /*{{{*/
239 // ---------------------------------------------------------------------
240 /* This adds an item to the pipeline. We keep the pipeline at a fixed
241 depth. */
242 bool HttpsMethod::Fetch(FetchItem *Itm)
243 {
244 struct stat SBuf;
245 struct curl_slist *headers=NULL;
246 char curl_errorstr[CURL_ERROR_SIZE];
247 URI Uri = Itm->Uri;
248 string remotehost = Uri.Host;
249
250 // TODO:
251 // - http::Pipeline-Depth
252 // - error checking/reporting
253 // - more debug options? (CURLOPT_DEBUGFUNCTION?)
254
255 curl_easy_reset(curl);
256 if (SetupProxy() == false)
257 return _error->Error("Unsupported proxy configured: %s", URI::SiteOnly(Proxy).c_str());
258
259 maybe_add_auth (Uri, _config->FindFile("Dir::Etc::netrc"));
260
261 FetchResult Res;
262 CURLUserPointer userp(this, &Res, Itm);
263 // callbacks
264 curl_easy_setopt(curl, CURLOPT_URL, static_cast<string>(Uri).c_str());
265 curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, parse_header);
266 curl_easy_setopt(curl, CURLOPT_WRITEHEADER, &userp);
267 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
268 curl_easy_setopt(curl, CURLOPT_WRITEDATA, this);
269 // options
270 curl_easy_setopt(curl, CURLOPT_NOPROGRESS, true);
271 curl_easy_setopt(curl, CURLOPT_FILETIME, true);
272 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 0);
273 // only allow curl to handle https, not the other stuff it supports
274 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
275 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS);
276
277 // SSL parameters are set by default to the common (non mirror-specific) value
278 // if available (or a default one) and gets overload by mirror-specific ones.
279
280 // File containing the list of trusted CA.
281 string cainfo = _config->Find("Acquire::https::CaInfo","");
282 string knob = "Acquire::https::"+remotehost+"::CaInfo";
283 cainfo = _config->Find(knob.c_str(),cainfo.c_str());
284 if(cainfo.empty() == false)
285 curl_easy_setopt(curl, CURLOPT_CAINFO,cainfo.c_str());
286
287 // Check server certificate against previous CA list ...
288 bool peer_verify = _config->FindB("Acquire::https::Verify-Peer",true);
289 knob = "Acquire::https::" + remotehost + "::Verify-Peer";
290 peer_verify = _config->FindB(knob.c_str(), peer_verify);
291 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, peer_verify);
292
293 // ... and hostname against cert CN or subjectAltName
294 bool verify = _config->FindB("Acquire::https::Verify-Host",true);
295 knob = "Acquire::https::"+remotehost+"::Verify-Host";
296 verify = _config->FindB(knob.c_str(),verify);
297 int const default_verify = (verify == true) ? 2 : 0;
298 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, default_verify);
299
300 // Also enforce issuer of server certificate using its cert
301 string issuercert = _config->Find("Acquire::https::IssuerCert","");
302 knob = "Acquire::https::"+remotehost+"::IssuerCert";
303 issuercert = _config->Find(knob.c_str(),issuercert.c_str());
304 if(issuercert.empty() == false)
305 curl_easy_setopt(curl, CURLOPT_ISSUERCERT,issuercert.c_str());
306
307 // For client authentication, certificate file ...
308 string pem = _config->Find("Acquire::https::SslCert","");
309 knob = "Acquire::https::"+remotehost+"::SslCert";
310 pem = _config->Find(knob.c_str(),pem.c_str());
311 if(pem.empty() == false)
312 curl_easy_setopt(curl, CURLOPT_SSLCERT, pem.c_str());
313
314 // ... and associated key.
315 string key = _config->Find("Acquire::https::SslKey","");
316 knob = "Acquire::https::"+remotehost+"::SslKey";
317 key = _config->Find(knob.c_str(),key.c_str());
318 if(key.empty() == false)
319 curl_easy_setopt(curl, CURLOPT_SSLKEY, key.c_str());
320
321 // Allow forcing SSL version to SSLv3 or TLSv1 (SSLv2 is not
322 // supported by GnuTLS).
323 long final_version = CURL_SSLVERSION_DEFAULT;
324 string sslversion = _config->Find("Acquire::https::SslForceVersion","");
325 knob = "Acquire::https::"+remotehost+"::SslForceVersion";
326 sslversion = _config->Find(knob.c_str(),sslversion.c_str());
327 if(sslversion == "TLSv1")
328 final_version = CURL_SSLVERSION_TLSv1;
329 else if(sslversion == "SSLv3")
330 final_version = CURL_SSLVERSION_SSLv3;
331 curl_easy_setopt(curl, CURLOPT_SSLVERSION, final_version);
332
333 // CRL file
334 string crlfile = _config->Find("Acquire::https::CrlFile","");
335 knob = "Acquire::https::"+remotehost+"::CrlFile";
336 crlfile = _config->Find(knob.c_str(),crlfile.c_str());
337 if(crlfile.empty() == false)
338 curl_easy_setopt(curl, CURLOPT_CRLFILE, crlfile.c_str());
339
340 // cache-control
341 if(_config->FindB("Acquire::https::No-Cache",
342 _config->FindB("Acquire::http::No-Cache",false)) == false)
343 {
344 // cache enabled
345 if (_config->FindB("Acquire::https::No-Store",
346 _config->FindB("Acquire::http::No-Store",false)) == true)
347 headers = curl_slist_append(headers,"Cache-Control: no-store");
348 stringstream ss;
349 ioprintf(ss, "Cache-Control: max-age=%u", _config->FindI("Acquire::https::Max-Age",
350 _config->FindI("Acquire::http::Max-Age",0)));
351 headers = curl_slist_append(headers, ss.str().c_str());
352 } else {
353 // cache disabled by user
354 headers = curl_slist_append(headers, "Cache-Control: no-cache");
355 headers = curl_slist_append(headers, "Pragma: no-cache");
356 }
357 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
358
359 // speed limit
360 int const dlLimit = _config->FindI("Acquire::https::Dl-Limit",
361 _config->FindI("Acquire::http::Dl-Limit",0))*1024;
362 if (dlLimit > 0)
363 curl_easy_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE, dlLimit);
364
365 // set header
366 curl_easy_setopt(curl, CURLOPT_USERAGENT,
367 _config->Find("Acquire::https::User-Agent",
368 _config->Find("Acquire::http::User-Agent",
369 "Debian APT-CURL/1.0 (" PACKAGE_VERSION ")").c_str()).c_str());
370
371 // set timeout
372 int const timeout = _config->FindI("Acquire::https::Timeout",
373 _config->FindI("Acquire::http::Timeout",120));
374 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, timeout);
375 //set really low lowspeed timeout (see #497983)
376 curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, DL_MIN_SPEED);
377 curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, timeout);
378
379 // debug
380 if (Debug == true)
381 curl_easy_setopt(curl, CURLOPT_VERBOSE, true);
382
383 // error handling
384 curl_errorstr[0] = '\0';
385 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_errorstr);
386
387 // If we ask for uncompressed files servers might respond with content-
388 // negotiation which lets us end up with compressed files we do not support,
389 // see 657029, 657560 and co, so if we have no extension on the request
390 // ask for text only. As a sidenote: If there is nothing to negotate servers
391 // seem to be nice and ignore it.
392 if (_config->FindB("Acquire::https::SendAccept", _config->FindB("Acquire::http::SendAccept", true)) == true)
393 {
394 size_t const filepos = Itm->Uri.find_last_of('/');
395 string const file = Itm->Uri.substr(filepos + 1);
396 if (flExtension(file) == file)
397 headers = curl_slist_append(headers, "Accept: text/*");
398 }
399
400 // if we have the file send an if-range query with a range header
401 if (stat(Itm->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
402 {
403 std::string Buf;
404 strprintf(Buf, "Range: bytes=%lli-", (long long) SBuf.st_size);
405 headers = curl_slist_append(headers, Buf.c_str());
406 strprintf(Buf, "If-Range: %s", TimeRFC1123(SBuf.st_mtime, false).c_str());
407 headers = curl_slist_append(headers, Buf.c_str());
408 }
409 else if(Itm->LastModified > 0)
410 {
411 curl_easy_setopt(curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
412 curl_easy_setopt(curl, CURLOPT_TIMEVALUE, Itm->LastModified);
413 }
414
415 // go for it - if the file exists, append on it
416 File = new FileFd(Itm->DestFile, FileFd::WriteAny);
417 Server = CreateServerState(Itm->Uri);
418 if (Server->InitHashes(Itm->ExpectedHashes) == false)
419 return false;
420
421 // keep apt updated
422 Res.Filename = Itm->DestFile;
423
424 // get it!
425 CURLcode success = curl_easy_perform(curl);
426
427 // If the server returns 200 OK but the If-Modified-Since condition is not
428 // met, CURLINFO_CONDITION_UNMET will be set to 1
429 long curl_condition_unmet = 0;
430 curl_easy_getinfo(curl, CURLINFO_CONDITION_UNMET, &curl_condition_unmet);
431 if (curl_condition_unmet == 1)
432 Server->Result = 304;
433
434 File->Close();
435 curl_slist_free_all(headers);
436
437 // cleanup
438 if (success != CURLE_OK)
439 {
440 #pragma GCC diagnostic push
441 #pragma GCC diagnostic ignored "-Wswitch"
442 switch (success)
443 {
444 case CURLE_COULDNT_RESOLVE_PROXY:
445 case CURLE_COULDNT_RESOLVE_HOST:
446 SetFailReason("ResolveFailure");
447 break;
448 case CURLE_COULDNT_CONNECT:
449 SetFailReason("ConnectionRefused");
450 break;
451 case CURLE_OPERATION_TIMEDOUT:
452 SetFailReason("Timeout");
453 break;
454 }
455 #pragma GCC diagnostic pop
456 // only take curls technical errors if we haven't our own
457 // (e.g. for the maximum size limit we have and curls can be confusing)
458 if (_error->PendingError() == false)
459 _error->Error("%s", curl_errorstr);
460 else
461 _error->Warning("curl: %s", curl_errorstr);
462 return false;
463 }
464
465 switch (DealWithHeaders(Res))
466 {
467 case ServerMethod::IMS_HIT:
468 URIDone(Res);
469 break;
470
471 case ServerMethod::ERROR_WITH_CONTENT_PAGE:
472 // unlink, no need keep 401/404 page content in partial/
473 RemoveFile(Binary.c_str(), File->Name());
474 case ServerMethod::ERROR_UNRECOVERABLE:
475 case ServerMethod::ERROR_NOT_FROM_SERVER:
476 return false;
477
478 case ServerMethod::TRY_AGAIN_OR_REDIRECT:
479 Redirect(NextURI);
480 break;
481
482 case ServerMethod::FILE_IS_OPEN:
483 struct stat resultStat;
484 if (unlikely(stat(File->Name().c_str(), &resultStat) != 0))
485 {
486 _error->Errno("stat", "Unable to access file %s", File->Name().c_str());
487 return false;
488 }
489 Res.Size = resultStat.st_size;
490
491 // Timestamp
492 curl_easy_getinfo(curl, CURLINFO_FILETIME, &Res.LastModified);
493 if (Res.LastModified != -1)
494 {
495 struct timeval times[2];
496 times[0].tv_sec = Res.LastModified;
497 times[1].tv_sec = Res.LastModified;
498 times[0].tv_usec = times[1].tv_usec = 0;
499 utimes(File->Name().c_str(), times);
500 }
501 else
502 Res.LastModified = resultStat.st_mtime;
503
504 // take hashes
505 Res.TakeHashes(*(Server->GetHashes()));
506
507 // keep apt updated
508 URIDone(Res);
509 break;
510 }
511
512 delete File;
513 return true;
514 }
515 /*}}}*/
516 // HttpsMethod::Configuration - Handle a configuration message /*{{{*/
517 bool HttpsMethod::Configuration(string Message)
518 {
519 if (ServerMethod::Configuration(Message) == false)
520 return false;
521
522 AllowRedirect = _config->FindB("Acquire::https::AllowRedirect",
523 _config->FindB("Acquire::http::AllowRedirect", true));
524 Debug = _config->FindB("Debug::Acquire::https",false);
525
526 return true;
527 }
528 /*}}}*/
529 std::unique_ptr<ServerState> HttpsMethod::CreateServerState(URI const &uri)/*{{{*/
530 {
531 return std::unique_ptr<ServerState>(new HttpsServerState(uri, this));
532 }
533 /*}}}*/
534
535 int main()
536 {
537 return HttpsMethod().Run();
538 }
539