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