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