-
-
Notifications
You must be signed in to change notification settings - Fork 302
/
ConnectionSettings.java
662 lines (569 loc) · 18.5 KB
/
ConnectionSettings.java
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
package aQute.bnd.connection.settings;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import java.io.File;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXParseException;
import aQute.bnd.exceptions.Exceptions;
import aQute.bnd.header.Attrs;
import aQute.bnd.header.Parameters;
import aQute.bnd.http.HttpClient;
import aQute.bnd.osgi.Constants;
import aQute.bnd.osgi.Processor;
import aQute.bnd.osgi.Processor.FileLine;
import aQute.bnd.service.url.ProxyHandler;
import aQute.bnd.service.url.URLConnectionHandler;
import aQute.bnd.url.BasicAuthentication;
import aQute.bnd.url.BearerAuthentication;
import aQute.bnd.url.HttpsVerification;
import aQute.bnd.util.home.Home;
import aQute.lib.collections.Iterables;
import aQute.lib.concurrentinit.ConcurrentInitialize;
import aQute.lib.converter.Converter;
import aQute.lib.hex.Hex;
import aQute.lib.io.IO;
import aQute.lib.mavenpasswordobfuscator.MavenPasswordObfuscator;
import aQute.lib.strings.Strings;
import aQute.lib.xpath.XPathParser;
import aQute.libg.glob.Glob;
import aQute.libg.uri.URIUtil;
import aQute.service.reporter.Reporter.SetLocation;
public class ConnectionSettings {
final static Logger logger = LoggerFactory
.getLogger(ConnectionSettings.class);
public static final String M2_SETTINGS_SECURITY_XML = "~/.m2/settings-security.xml";
public static final String M2_SETTINGS_SECURITY_PROPERTY = "settings.security";
private static final String M2_SETTINGS_XML = "~/.m2/settings.xml";
private static final String BND_CONNECTION_SETTINGS_XML = Home.getUserHomeBnd()
+ "/connection-settings.xml";
private static final String CONNECTION_SETTINGS = "-connection-settings";
private final Processor processor;
private final HttpClient client;
private final List<ServerDTO> servers = new ArrayList<>();
private final ConcurrentInitialize<String> mavenMasterPassphrase;
private final List<String> parsed = new ArrayList<>();
public ConnectionSettings(Processor processor, HttpClient client) throws Exception {
this.processor = Objects.requireNonNull(processor);
this.client = client;
String logfile = processor.getProperty(Constants.CONNECTION_LOG);
if (Strings.nonNullOrEmpty(logfile)) {
File file = IO.getFile(logfile);
file.getParentFile()
.mkdirs();
this.client.setLog(file);
}
mavenMasterPassphrase = new MasterPassphrase(processor);
}
private static final class MasterPassphrase extends ConcurrentInitialize<String> {
private final Processor processor;
MasterPassphrase(Processor processor) {
this.processor = processor;
}
@Override
public String create() throws Exception {
String path = System.getProperty(M2_SETTINGS_SECURITY_PROPERTY, M2_SETTINGS_SECURITY_XML);
File file = IO.getFile(path);
if (!file.isFile()) {
logger.info("No Maven security settings file {}", path);
return null;
}
XPathParser sp = new XPathParser(file);
String master = sp.parse("/settingsSecurity/master");
if (master == null || master.isEmpty()) {
processor.warning("Found Maven security settings file %s but not master password in it", path);
return null;
} else {
if (!MavenPasswordObfuscator.isObfuscatedPassword(master)) {
processor.warning("Master password in %s was not obfuscated, using actual value", path);
return master;
}
try {
return MavenPasswordObfuscator.decrypt(master, M2_SETTINGS_SECURITY_PROPERTY);
} catch (Exception e) {
processor.exception(e, "Could not decrypt the master password from %s with key %s", path,
M2_SETTINGS_SECURITY_PROPERTY);
return null;
}
}
}
}
public void readSettings() throws Exception {
Parameters connectionSettings = new Parameters(processor.mergeProperties(CONNECTION_SETTINGS), processor);
if (connectionSettings.isEmpty()) {
File file = IO.getFile(BND_CONNECTION_SETTINGS_XML);
if (!file.isFile()) {
file = IO.getFile(M2_SETTINGS_XML);
if (!file.isFile()) {
return;
}
}
parse(file);
return;
}
List<File> tmps = new ArrayList<>();
try {
for (Map.Entry<String, Attrs> entry : connectionSettings.entrySet()) {
String key = entry.getKey();
if ("false".equalsIgnoreCase(key)) {
continue;
}
boolean ignoreError = false;
if (key.startsWith("-")) {
ignoreError = true;
key = key.substring(1);
}
switch (key) {
case "maven" :
key = M2_SETTINGS_XML;
break;
case "bnd" :
key = BND_CONNECTION_SETTINGS_XML;
break;
case "env" :
Attrs attrs = entry.getValue();
String variable = attrs.get("var");
if (variable == null) {
processor.error(
"Specified -connection-settings: %s, with 'env' but the 'var' parameter was not found",
connectionSettings);
} else {
String value = System.getenv(variable);
if (value != null) {
File tmp = File.createTempFile(variable, ".xml");
IO.store(value, tmp);
key = IO.absolutePath(tmp);
tmps.add(tmp);
} else {
if (!ignoreError) {
processor.error(
"Specified -connection-settings: %s, but no such environment variable %s is found",
connectionSettings, variable);
}
}
}
break;
}
key = Processor.removeDuplicateMarker(key);
if ("server".equals(key)) {
parseServer(entry.getValue());
} else {
File file = processor.getFile(key);
if (!file.isFile()) {
if (!ignoreError) {
SetLocation error = processor
.error("Specified -connection-settings: %s, but no such file or is directory", file);
FileLine header = processor.getHeader(CONNECTION_SETTINGS, key);
if (header != null)
header.set(error);
}
} else {
parse(file);
}
}
}
} finally {
tmps.forEach(IO::delete);
}
}
/**
* Set the parameters from within, i.e. not via file
*
* @param value the values
* @throws Exception
*/
private void parseServer(Attrs value) throws Exception {
parsed.add("direct: " + value);
ServerDTO server = Converter.cnv(ServerDTO.class, value);
if (isBasicAuth(server) || isBearerAuth(server) || isPrivateKey(server) || isHttpsVerification(server)) {
if (server.id == null) {
server.id = "*";
} else {
String normalized = normalize(server.id);
if (server.id != normalized) { // normalized
server.id = normalized;
} else if ((server.match == null) && (server.id.indexOf('*') < 0)) {
server.match = "*" + server.id + "*";
}
}
add(server);
}
}
private static final Pattern URI_P = Pattern.compile("([^:/?#]+)://([^:/?#]+)(?::([^:/?#]+))?.*");
static String normalize(String id) {
Matcher m = URI_P.matcher(id);
if (!m.matches()) {
return id;
}
String scheme = m.group(1)
.toLowerCase(Locale.ROOT);
String host = m.group(2);
String port = m.group(3);
StringBuilder address = new StringBuilder();
address.append(scheme)
.append(':')
.append('/')
.append('/')
.append(host);
if (port != null) {
int defaultPort = URIUtil.getDefaultPort(scheme);
if ((defaultPort < 0) || !port.equals(Integer.toString(defaultPort))) {
address.append(':')
.append(port);
}
}
return address.toString();
}
private boolean isPrivateKey(ServerDTO server) {
if (isEmpty(server.privateKey) || isEmpty(server.passphrase))
return false;
else
return true;
}
private boolean isBasicAuth(ServerDTO server) {
if (isEmpty(server.username) || isEmpty(server.password))
return false;
else
return true;
}
private boolean isBearerAuth(ServerDTO server) {
if (isEmpty(server.username) && !isEmpty(server.password))
return true;
else
return false;
}
private boolean isHttpsVerification(ServerDTO server) {
if (isEmpty(server.trust))
return false;
else
return true;
}
private boolean isEmpty(String s) {
return s == null || s.trim()
.isEmpty();
}
public URLConnectionHandler createURLConnectionHandler(ServerDTO serverDTO) {
return new SettingsURLConnectionHandler(serverDTO, processor);
}
private static final class SettingsURLConnectionHandler implements URLConnectionHandler {
private final Glob match;
private final URLConnectionHandler handler;
private final URLConnectionHandler https;
private final int maxConcurrentConnections;
SettingsURLConnectionHandler(ServerDTO serverDTO, Processor processor) {
match = new Glob(serverDTO.match != null ? serverDTO.match : serverDTO.id);
maxConcurrentConnections = serverDTO.maxConcurrentConnections;
if (serverDTO.password == null) {
handler = null;
} else if (serverDTO.username != null) {
handler = new BasicAuthentication(serverDTO.username, serverDTO.password, processor);
} else {
handler = new BearerAuthentication(serverDTO.password, processor);
}
// verify=false, trust.isEmpty -> void default check
// verify=false, !trust.isEmpty -> ignore
// verify=true, trust.isEmpty -> use default check
// verify=true, !trust.isEmpty -> verify against given certs
boolean hasCerts = serverDTO.trust != null && !serverDTO.trust.isEmpty();
if (serverDTO.verify == false || hasCerts)
https = new HttpsVerification(serverDTO.trust, serverDTO.verify, processor);
else
https = null; // verify & no certs ==> default
}
@Override
public boolean matches(URL url) {
return match.matcher(normalize(url.toString()))
.matches();
}
@Override
public void handle(URLConnection connection) throws Exception {
if (handler != null) {
handler.handle(connection);
}
if ((https != null) && isHttps(connection)) {
https.handle(connection);
}
}
@Override
public int maxConcurrentConnections() {
return maxConcurrentConnections;
}
private boolean isHttps(URLConnection connection) {
return "https".equalsIgnoreCase(connection.getURL()
.getProtocol());
}
@Override
public String toString() {
return "Server [ match=" + match + ", handler=" + handler + ", maxConcurrentConnections="
+ maxConcurrentConnections + ", https=" + https + "]";
}
}
/**
* Create Proxy Handler from ProxyDTO
*/
public ProxyHandler createProxyHandler(ProxyDTO proxyDTO) {
return new SettingsProxyHandler(proxyDTO);
}
private static final class SettingsProxyHandler implements ProxyHandler {
private final ProxyDTO proxyDTO;
private List<Glob> globs;
private ProxySetup proxySetup;
SettingsProxyHandler(ProxyDTO proxyDTO) {
this.proxyDTO = proxyDTO;
}
@Override
public ProxySetup forURL(URL url) throws Exception {
Proxy.Type type;
switch (proxyDTO.protocol.toUpperCase(Locale.ROOT)) {
case "DIRECT" :
type = Type.DIRECT;
break;
case "HTTP" :
type = Type.HTTP;
if (url.getProtocol()
.equalsIgnoreCase("http")) {
// ok
} else
return null;
break;
case "HTTPS" :
type = Type.HTTP;
if (url.getProtocol()
.equalsIgnoreCase("https")) {
// ok
} else
return null;
break;
case "SOCKS" :
type = Type.SOCKS;
break;
default :
type = Type.HTTP;
break;
}
if (isNonProxyHost(url.getHost())) {
return null;
}
// not synchronized because conflicts only do some double work
if (proxySetup == null) {
final ProxySetup pendingProxySetup = new ProxySetup();
if (proxyDTO.username != null && proxyDTO.password != null)
pendingProxySetup.authentication = new PasswordAuthentication(proxyDTO.username,
proxyDTO.password.toCharArray());
SocketAddress socketAddress;
if (proxyDTO.host != null)
socketAddress = new InetSocketAddress(proxyDTO.host, proxyDTO.port);
else
socketAddress = new InetSocketAddress(proxyDTO.port);
pendingProxySetup.proxy = new Proxy(type, socketAddress);
proxySetup = pendingProxySetup;
}
return proxySetup;
}
private boolean isNonProxyHost(String host) {
if (host == null) {
return false;
}
return getNonProxyHosts().stream()
.anyMatch(g -> g.matcher(host)
.matches());
}
private List<Glob> getNonProxyHosts() {
// not synchronized because conflicts only do some double work
if (globs != null) {
return globs;
}
if (proxyDTO.nonProxyHosts == null) {
return globs = emptyList();
}
return globs = Processor.split(proxyDTO.nonProxyHosts, "\\s*\\|\\s*")
.stream()
.map(Glob::new)
.collect(toList());
}
}
private void parse(File file) throws Exception {
try {
assert file != null : "File must be set";
assert file.isFile() : "File must be a file and exist";
parsed.add(file.getAbsolutePath());
SettingsParser parser = new SettingsParser(file);
SettingsDTO settings = parser.getSettings();
for (ProxyDTO proxyDTO : settings.proxies) {
if (isActive(proxyDTO)) {
add(proxyDTO);
}
}
ServerDTO deflt = null;
for (ServerDTO serverDTO : settings.servers) {
String normalized = normalize(serverDTO.id);
if (serverDTO.id != normalized) { // normalized
serverDTO.id = normalized;
} else if ((serverDTO.match == null) && (serverDTO.id.indexOf('*') < 0)) {
serverDTO.match = "*" + serverDTO.id + "*";
}
serverDTO.trust = makeAbsolute(file.getParentFile(), serverDTO.trust);
if (MavenPasswordObfuscator.isObfuscatedPassword(serverDTO.password)) {
String masterPassphrase = mavenMasterPassphrase.get();
if (masterPassphrase != null) {
try {
serverDTO.password = MavenPasswordObfuscator.decrypt(serverDTO.password, masterPassphrase);
} catch (Exception e) {
processor.exception(e, "Could not decrypt the password for server %s", serverDTO.id);
}
}
}
if ("default".equals(serverDTO.id))
deflt = serverDTO;
else {
add(serverDTO);
}
}
if (deflt != null)
add(deflt);
} catch (SAXParseException e) {
processor.error("Invalid XML in connection settings for file : %s: %s", file, e.getMessage());
}
}
private boolean isActive(ProxyDTO proxy) throws SocketException {
if (!proxy.active)
return false;
String mask = proxy.mask;
if (mask == null)
return true;
String[] clauses = mask.split("\\s*,\\s*");
for (String clause : clauses)
try {
String parts[] = clause.split("\\s*:\\s*");
Glob g = new Glob(parts[0]);
byte[] address = null;
int maskLength = 0;
if (parts.length > 1) {
String pp[] = parts[1].split("/");
address = InetAddress.getByName(pp[0])
.getAddress();
maskLength = pp.length > 1 ? Integer.parseInt(pp[1]) : address.length * 8;
}
for (NetworkInterface ni : Iterables.iterable(NetworkInterface.getNetworkInterfaces())) {
if (ni == null)
continue;
if (!ni.isUp())
continue;
if (g.matcher(ni.getName())
.matches()) {
if (address == null)
return true;
for (InterfaceAddress ia : ni.getInterfaceAddresses()) {
byte[] iaa = ia.getAddress()
.getAddress();
if (address.length != iaa.length)
continue;
if (maskLength != 0 && ia.getNetworkPrefixLength() != maskLength)
continue;
if (Arrays.equals(address, iaa))
return true;
}
}
}
} catch (Exception e) {
processor.exception(e, "Failed to parse proxy 'mask' clause in settings: %s", clause);
}
return false;
}
public static String makeAbsolute(File cwd, String trust) {
if (trust == null || trust.trim()
.isEmpty())
return null;
return Processor.split(trust)
.stream()
.map(part -> resolve(cwd, part))
.collect(joining(","));
}
static String resolve(File dir, String part) {
return IO.getFile(dir, part)
.getPath();
}
public void add(ServerDTO server) {
servers.add(server);
if (client != null)
client.addURLConnectionHandler(createURLConnectionHandler(server));
}
public void add(ProxyDTO proxy) {
if (client != null)
client.addProxyHandler(createProxyHandler(proxy));
}
public List<ServerDTO> getServerDTOs() {
return servers;
}
public List<String> getParsedFiles() {
return parsed;
}
public void report(Formatter f) {
f.format("-connection-settings %s%n", processor.getProperty(CONNECTION_SETTINGS, "<>"));
f.format("Parsed files:%n");
getParsedFiles().forEach(file -> f.format(" %s%n", file));
getServerDTOs().forEach(server -> {
f.format("%n");
f.format("Id %s%n", server.id);
f.format("Username %s%n", server.username);
f.format("Password %s%n", server.password == null ? "<>" : "*******");
f.format("Private Key %s%n", server.privateKey == null ? "<>" : "*******");
f.format("Passphrase %s%n", server.passphrase == null ? "<>" : "*******");
if (server.trust != null && !server.trust.trim()
.isEmpty()) {
f.format("Trust%n");
List<String> paths = Strings.split(server.trust);
for (String path : paths)
try {
File file = new File(path);
if (file.isFile()) {
f.format(" %s%n", file);
List<X509Certificate> certificates = new ArrayList<>();
HttpsVerification.getCertificates(path, certificates);
for (X509Certificate certificate : certificates) {
f.format(" Subject %s%n", certificate.getSubjectDN());
byte[] bytes = certificate.getSerialNumber()
.toByteArray();
f.format(" Serial Nr %s%n", Hex.separated(bytes, ":"));
f.format(" Issuer %s%n", certificate.getIssuerDN());
f.format(" Type %s%n", certificate.getType());
try {
certificate.checkValidity();
f.format(" Valid yes%n");
} catch (Exception e) {
f.format(" Valid %s%n", e.getMessage());
}
}
} else {
f.format(" %s NO SUCH FILE%n", file);
}
} catch (Exception e) {
f.format(" Unexpected connection settings '%s'%n", Exceptions.causes(e));
}
f.format("Verify %s%n", server.verify);
}
});
}
}