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