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