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