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