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