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