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