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