1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
|
//-*- mode: cpp; mode: fold -*-
// Description /*{{{*/
// $Id: http.cc,v 1.59 2004/05/08 19:42:35 mdz Exp $
/* ######################################################################
HTTPS Acquire Method - This is the HTTPS acquire method for APT.
It uses libcurl
##################################################################### */
/*}}}*/
// Include Files /*{{{*/
#include <config.h>
#include <apt-pkg/fileutl.h>
#include <apt-pkg/error.h>
#include <apt-pkg/hashes.h>
#include <apt-pkg/netrc.h>
#include <apt-pkg/configuration.h>
#include <apt-pkg/macros.h>
#include <apt-pkg/strutl.h>
#include <apt-pkg/proxy.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <array>
#include <iostream>
#include <sstream>
#include "https.h"
#include <apti18n.h>
/*}}}*/
using namespace std;
struct APT_HIDDEN CURLUserPointer {
HttpsMethod * const https;
HttpsMethod::FetchResult * const Res;
HttpsMethod::FetchItem const * const Itm;
CURLUserPointer(HttpsMethod * const https, HttpsMethod::FetchResult * const Res,
HttpsMethod::FetchItem const * const Itm) : https(https), Res(Res), Itm(Itm) {}
};
size_t
HttpsMethod::parse_header(void *buffer, size_t size, size_t nmemb, void *userp)
{
size_t len = size * nmemb;
CURLUserPointer *me = static_cast<CURLUserPointer *>(userp);
std::string line((char*) buffer, len);
for (--len; len > 0; --len)
if (isspace_ascii(line[len]) == 0)
{
++len;
break;
}
line.erase(len);
if (line.empty() == true)
{
me->https->Server->JunkSize = 0;
if (me->https->Server->Result != 416 && me->https->Server->StartPos != 0)
;
else if (me->https->Server->Result == 416)
{
bool partialHit = false;
if (me->Itm->ExpectedHashes.usable() == true)
{
Hashes resultHashes(me->Itm->ExpectedHashes);
FileFd file(me->Itm->DestFile, FileFd::ReadOnly);
me->https->Server->TotalFileSize = file.FileSize();
me->https->Server->Date = file.ModificationTime();
resultHashes.AddFD(file);
HashStringList const hashList = resultHashes.GetHashStringList();
partialHit = (me->Itm->ExpectedHashes == hashList);
}
else if (me->https->Server->Result == 416 && me->https->Server->TotalFileSize == me->https->File->FileSize())
partialHit = true;
if (partialHit == true)
{
me->https->Server->Result = 200;
me->https->Server->StartPos = me->https->Server->TotalFileSize;
// the actual size is not important for https as curl will deal with it
// by itself and e.g. doesn't bother us with transport-encoding…
me->https->Server->JunkSize = std::numeric_limits<unsigned long long>::max();
}
else
me->https->Server->StartPos = 0;
}
else
me->https->Server->StartPos = 0;
me->Res->LastModified = me->https->Server->Date;
me->Res->Size = me->https->Server->TotalFileSize;
me->Res->ResumePoint = me->https->Server->StartPos;
// we expect valid data, so tell our caller we get the file now
if (me->https->Server->Result >= 200 && me->https->Server->Result < 300)
{
if (me->Res->Size != 0 && me->Res->Size > me->Res->ResumePoint)
me->https->URIStart(*me->Res);
if (me->https->Server->AddPartialFileToHashes(*(me->https->File)) == false)
return 0;
}
else
me->https->Server->JunkSize = std::numeric_limits<decltype(me->https->Server->JunkSize)>::max();
}
else if (me->https->Server->HeaderLine(line) == false)
return 0;
return size*nmemb;
}
size_t
HttpsMethod::write_data(void *buffer, size_t size, size_t nmemb, void *userp)
{
HttpsMethod *me = static_cast<HttpsMethod *>(userp);
size_t buffer_size = size * nmemb;
// we don't need to count the junk here, just drop anything we get as
// we don't always know how long it would be, e.g. in chunked encoding.
if (me->Server->JunkSize != 0)
return buffer_size;
if(me->File->Write(buffer, buffer_size) != true)
return 0;
if(me->Queue->MaximumSize > 0)
{
unsigned long long const TotalWritten = me->File->Tell();
if (TotalWritten > me->Queue->MaximumSize)
{
me->SetFailReason("MaximumSizeExceeded");
_error->Error("Writing more data than expected (%llu > %llu)",
TotalWritten, me->Queue->MaximumSize);
return 0;
}
}
if (me->Server->GetHashes()->Add((unsigned char const * const)buffer, buffer_size) == false)
return 0;
return buffer_size;
}
// HttpsServerState::HttpsServerState - Constructor /*{{{*/
HttpsServerState::HttpsServerState(URI Srv,HttpsMethod * Owner) : ServerState(Srv, Owner), Hash(NULL)
{
TimeOut = Owner->ConfigFindI("Timeout", TimeOut);
Reset();
}
/*}}}*/
bool HttpsServerState::InitHashes(HashStringList const &ExpectedHashes) /*{{{*/
{
delete Hash;
Hash = new Hashes(ExpectedHashes);
return true;
}
/*}}}*/
APT_PURE Hashes * HttpsServerState::GetHashes() /*{{{*/
{
return Hash;
}
/*}}}*/
bool HttpsMethod::SetupProxy() /*{{{*/
{
URI ServerName = Queue->Uri;
// Determine the proxy setting
AutoDetectProxy(ServerName);
// Curl should never read proxy settings from the environment, as
// we determine which proxy to use. Do this for consistency among
// methods and prevent an environment variable overriding a
// no-proxy ("DIRECT") setting in apt.conf.
curl_easy_setopt(curl, CURLOPT_PROXY, "");
// Determine the proxy setting - try https first, fallback to http and use env at last
string UseProxy = ConfigFind("Proxy::" + ServerName.Host, "");
if (UseProxy.empty() == true)
UseProxy = ConfigFind("Proxy", "");
// User wants to use NO proxy, so nothing to setup
if (UseProxy == "DIRECT")
return true;
// Parse no_proxy, a comma (,) separated list of domains we don't want to use
// a proxy for so we stop right here if it is in the list
if (getenv("no_proxy") != 0 && CheckDomainList(ServerName.Host,getenv("no_proxy")) == true)
return true;
if (UseProxy.empty() == true)
{
const char* result = nullptr;
if (std::find(methodNames.begin(), methodNames.end(), "https") != methodNames.end())
result = getenv("https_proxy");
// FIXME: Fall back to http_proxy is to remain compatible with
// existing setups and behaviour of apt.conf. This should be
// deprecated in the future (including apt.conf). Most other
// programs do not fall back to http proxy settings and neither
// should Apt.
if (result == nullptr && std::find(methodNames.begin(), methodNames.end(), "http") != methodNames.end())
result = getenv("http_proxy");
UseProxy = result == nullptr ? "" : result;
}
// Determine what host and port to use based on the proxy settings
if (UseProxy.empty() == false)
{
Proxy = UseProxy;
AddProxyAuth(Proxy, ServerName);
if (Proxy.Access == "socks5h")
curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
else if (Proxy.Access == "socks5")
curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
else if (Proxy.Access == "socks4a")
curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
else if (Proxy.Access == "socks")
curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
else if (Proxy.Access == "http" || Proxy.Access == "https")
curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
else
return false;
if (Proxy.Port != 1)
curl_easy_setopt(curl, CURLOPT_PROXYPORT, Proxy.Port);
curl_easy_setopt(curl, CURLOPT_PROXY, Proxy.Host.c_str());
if (Proxy.User.empty() == false || Proxy.Password.empty() == false)
{
curl_easy_setopt(curl, CURLOPT_PROXYUSERNAME, Proxy.User.c_str());
curl_easy_setopt(curl, CURLOPT_PROXYPASSWORD, Proxy.Password.c_str());
}
}
return true;
} /*}}}*/
// HttpsMethod::Fetch - Fetch an item /*{{{*/
// ---------------------------------------------------------------------
/* This adds an item to the pipeline. We keep the pipeline at a fixed
depth. */
bool HttpsMethod::Fetch(FetchItem *Itm)
{
struct stat SBuf;
struct curl_slist *headers=NULL;
char curl_errorstr[CURL_ERROR_SIZE];
URI Uri = Itm->Uri;
setPostfixForMethodNames(Uri.Host.c_str());
AllowRedirect = ConfigFindB("AllowRedirect", true);
Debug = DebugEnabled();
// TODO:
// - http::Pipeline-Depth
// - error checking/reporting
// - more debug options? (CURLOPT_DEBUGFUNCTION?)
{
auto const plus = Binary.find('+');
if (plus != std::string::npos)
Uri.Access = Binary.substr(plus + 1);
}
curl_easy_reset(curl);
if (SetupProxy() == false)
return _error->Error("Unsupported proxy configured: %s", URI::SiteOnly(Proxy).c_str());
maybe_add_auth (Uri, _config->FindFile("Dir::Etc::netrc"));
// The "+" is encoded as a workaround for a amazon S3 bug
// see LP bugs #1003633 and #1086997. (taken from http method)
Uri.Path = QuoteString(Uri.Path, "+~ ");
FetchResult Res;
CURLUserPointer userp(this, &Res, Itm);
// callbacks
curl_easy_setopt(curl, CURLOPT_URL, static_cast<string>(Uri).c_str());
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, parse_header);
curl_easy_setopt(curl, CURLOPT_WRITEHEADER, &userp);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, this);
// options
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, true);
curl_easy_setopt(curl, CURLOPT_FILETIME, true);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 0);
if (std::find(methodNames.begin(), methodNames.end(), "https") != methodNames.end())
{
curl_easy_setopt(curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS);
// File containing the list of trusted CA.
std::string const cainfo = ConfigFind("CaInfo", "");
if(cainfo.empty() == false)
curl_easy_setopt(curl, CURLOPT_CAINFO, cainfo.c_str());
// Check server certificate against previous CA list ...
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, ConfigFindB("Verify-Peer", true) ? 1 : 0);
// ... and hostname against cert CN or subjectAltName
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, ConfigFindB("Verify-Host", true) ? 2 : 0);
// Also enforce issuer of server certificate using its cert
std::string const issuercert = ConfigFind("IssuerCert", "");
if(issuercert.empty() == false)
curl_easy_setopt(curl, CURLOPT_ISSUERCERT, issuercert.c_str());
// For client authentication, certificate file ...
std::string const pem = ConfigFind("SslCert", "");
if(pem.empty() == false)
curl_easy_setopt(curl, CURLOPT_SSLCERT, pem.c_str());
// ... and associated key.
std::string const key = ConfigFind("SslKey", "");
if(key.empty() == false)
curl_easy_setopt(curl, CURLOPT_SSLKEY, key.c_str());
// Allow forcing SSL version to SSLv3 or TLSv1
long final_version = CURL_SSLVERSION_DEFAULT;
std::string const sslversion = ConfigFind("SslForceVersion", "");
if(sslversion == "TLSv1")
final_version = CURL_SSLVERSION_TLSv1;
else if(sslversion == "TLSv1.0")
final_version = CURL_SSLVERSION_TLSv1_0;
else if(sslversion == "TLSv1.1")
final_version = CURL_SSLVERSION_TLSv1_1;
else if(sslversion == "TLSv1.2")
final_version = CURL_SSLVERSION_TLSv1_2;
else if(sslversion == "SSLv3")
final_version = CURL_SSLVERSION_SSLv3;
curl_easy_setopt(curl, CURLOPT_SSLVERSION, final_version);
// CRL file
std::string const crlfile = ConfigFind("CrlFile", "");
if(crlfile.empty() == false)
curl_easy_setopt(curl, CURLOPT_CRLFILE, crlfile.c_str());
}
else
{
curl_easy_setopt(curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTP);
curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP);
}
// cache-control
if(ConfigFindB("No-Cache", false) == false)
{
// cache enabled
if (ConfigFindB("No-Store", false) == true)
headers = curl_slist_append(headers,"Cache-Control: no-store");
std::string ss;
strprintf(ss, "Cache-Control: max-age=%u", ConfigFindI("Max-Age", 0));
headers = curl_slist_append(headers, ss.c_str());
} else {
// cache disabled by user
headers = curl_slist_append(headers, "Cache-Control: no-cache");
headers = curl_slist_append(headers, "Pragma: no-cache");
}
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
// speed limit
int const dlLimit = ConfigFindI("Dl-Limit", 0) * 1024;
if (dlLimit > 0)
curl_easy_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE, dlLimit);
// set header
curl_easy_setopt(curl, CURLOPT_USERAGENT, ConfigFind("User-Agent", "Debian APT-CURL/1.0 (" PACKAGE_VERSION ")").c_str());
// set timeout
int const timeout = ConfigFindI("Timeout", 120);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, timeout);
//set really low lowspeed timeout (see #497983)
curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, DL_MIN_SPEED);
curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, timeout);
if(_config->FindB("Acquire::ForceIPv4", false) == true)
curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
else if(_config->FindB("Acquire::ForceIPv6", false) == true)
curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
// debug
if (Debug == true)
curl_easy_setopt(curl, CURLOPT_VERBOSE, true);
// error handling
curl_errorstr[0] = '\0';
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_errorstr);
// If we ask for uncompressed files servers might respond with content-
// negotiation which lets us end up with compressed files we do not support,
// see 657029, 657560 and co, so if we have no extension on the request
// ask for text only. As a sidenote: If there is nothing to negotate servers
// seem to be nice and ignore it.
if (ConfigFindB("SendAccept", true))
{
size_t const filepos = Itm->Uri.find_last_of('/');
string const file = Itm->Uri.substr(filepos + 1);
if (flExtension(file) == file)
headers = curl_slist_append(headers, "Accept: text/*");
}
// go for it - if the file exists, append on it
File = new FileFd(Itm->DestFile, FileFd::WriteAny);
if (Server == nullptr || Server->Comp(Itm->Uri) == false)
Server = CreateServerState(Itm->Uri);
else
Server->Reset(false);
// if we have the file send an if-range query with a range header
if (Server->RangesAllowed && stat(Itm->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
{
std::string Buf;
strprintf(Buf, "Range: bytes=%lli-", (long long) SBuf.st_size);
headers = curl_slist_append(headers, Buf.c_str());
strprintf(Buf, "If-Range: %s", TimeRFC1123(SBuf.st_mtime, false).c_str());
headers = curl_slist_append(headers, Buf.c_str());
}
else if(Itm->LastModified > 0)
{
curl_easy_setopt(curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
curl_easy_setopt(curl, CURLOPT_TIMEVALUE, Itm->LastModified);
}
if (Server->InitHashes(Itm->ExpectedHashes) == false)
return false;
// keep apt updated
Res.Filename = Itm->DestFile;
// get it!
CURLcode success = curl_easy_perform(curl);
// If the server returns 200 OK but the If-Modified-Since condition is not
// met, CURLINFO_CONDITION_UNMET will be set to 1
long curl_condition_unmet = 0;
curl_easy_getinfo(curl, CURLINFO_CONDITION_UNMET, &curl_condition_unmet);
if (curl_condition_unmet == 1)
Server->Result = 304;
File->Close();
curl_slist_free_all(headers);
// cleanup
if (success != CURLE_OK)
{
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wswitch"
switch (success)
{
case CURLE_COULDNT_RESOLVE_PROXY:
case CURLE_COULDNT_RESOLVE_HOST:
SetFailReason("ResolveFailure");
break;
case CURLE_COULDNT_CONNECT:
SetFailReason("ConnectionRefused");
break;
case CURLE_OPERATION_TIMEDOUT:
SetFailReason("Timeout");
break;
}
#pragma GCC diagnostic pop
// only take curls technical errors if we haven't our own
// (e.g. for the maximum size limit we have and curls can be confusing)
if (_error->PendingError() == false)
_error->Error("%s", curl_errorstr);
else
_error->Warning("curl: %s", curl_errorstr);
return false;
}
switch (DealWithHeaders(Res))
{
case ServerMethod::IMS_HIT:
URIDone(Res);
break;
case ServerMethod::ERROR_WITH_CONTENT_PAGE:
// unlink, no need keep 401/404 page content in partial/
RemoveFile(Binary.c_str(), File->Name());
case ServerMethod::ERROR_UNRECOVERABLE:
case ServerMethod::ERROR_NOT_FROM_SERVER:
return false;
case ServerMethod::TRY_AGAIN_OR_REDIRECT:
Redirect(NextURI);
break;
case ServerMethod::FILE_IS_OPEN:
struct stat resultStat;
if (unlikely(stat(File->Name().c_str(), &resultStat) != 0))
{
_error->Errno("stat", "Unable to access file %s", File->Name().c_str());
return false;
}
Res.Size = resultStat.st_size;
// Timestamp
curl_easy_getinfo(curl, CURLINFO_FILETIME, &Res.LastModified);
if (Res.LastModified != -1)
{
struct timeval times[2];
times[0].tv_sec = Res.LastModified;
times[1].tv_sec = Res.LastModified;
times[0].tv_usec = times[1].tv_usec = 0;
utimes(File->Name().c_str(), times);
}
else
Res.LastModified = resultStat.st_mtime;
// take hashes
Res.TakeHashes(*(Server->GetHashes()));
// keep apt updated
URIDone(Res);
break;
}
delete File;
return true;
}
/*}}}*/
std::unique_ptr<ServerState> HttpsMethod::CreateServerState(URI const &uri)/*{{{*/
{
return std::unique_ptr<ServerState>(new HttpsServerState(uri, this));
}
/*}}}*/
HttpsMethod::HttpsMethod(std::string &&pProg) : ServerMethod(std::move(pProg),"1.2",Pipeline | SendConfig)/*{{{*/
{
auto addName = std::inserter(methodNames, methodNames.begin());
addName = "http";
auto const plus = Binary.find('+');
if (plus != std::string::npos)
{
addName = Binary.substr(plus + 1);
auto base = Binary.substr(0, plus);
if (base != "https")
addName = base;
}
if (std::find(methodNames.begin(), methodNames.end(), "https") != methodNames.end())
curl_global_init(CURL_GLOBAL_SSL);
else
curl_global_init(CURL_GLOBAL_NOTHING);
curl = curl_easy_init();
}
/*}}}*/
HttpsMethod::~HttpsMethod() /*{{{*/
{
curl_easy_cleanup(curl);
}
/*}}}*/
int main(int, const char *argv[]) /*{{{*/
{
std::string Binary = flNotDir(argv[0]);
if (Binary.find('+') == std::string::npos && Binary != "https")
Binary.append("+https");
return HttpsMethod(std::move(Binary)).Run();
}
/*}}}*/
|