forked from jenkinsci/jenkins
/
UpdateSite.java
1701 lines (1525 loc) · 61.1 KB
/
UpdateSite.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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Yahoo! Inc., Seiji Sogabe,
* Andrew Bayer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static jenkins.util.MemoryReductionUtil.getPresizedMutableMap;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.ExtensionList;
import hudson.PluginManager;
import hudson.PluginWrapper;
import hudson.Util;
import hudson.lifecycle.Lifecycle;
import hudson.model.UpdateCenter.UpdateCenterJob;
import hudson.util.FormValidation;
import hudson.util.HttpResponses;
import hudson.util.TextFile;
import hudson.util.VersionNumber;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Stream;
import jenkins.model.Jenkins;
import jenkins.plugins.DetachedPluginsUtil;
import jenkins.security.UpdateSiteWarningsConfiguration;
import jenkins.security.UpdateSiteWarningsMonitor;
import jenkins.util.JSONSignatureValidator;
import jenkins.util.PluginLabelUtil;
import jenkins.util.SystemProperties;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.interceptor.RequirePOST;
/**
* Source of the update center information, like "http://jenkins-ci.org/update-center.json"
*
* <p>
* Jenkins can have multiple {@link UpdateSite}s registered in the system, so that it can pick up plugins
* from different locations.
*
* @author Andrew Bayer
* @author Kohsuke Kawaguchi
* @since 1.333
*/
@ExportedBean
public class UpdateSite {
/**
* What's the time stamp of data file?
* 0 means never.
*/
private transient volatile long dataTimestamp;
/**
* When was the last time we asked a browser to check the data for us?
* 0 means never.
*
* <p>
* There's normally some delay between when we send HTML that includes the check code,
* until we get the data back, so this variable is used to avoid asking too many browsers
* all at once.
*/
private transient volatile long lastAttempt;
/**
* If the attempt to fetch data fails, we progressively use longer time out before retrying,
* to avoid overloading the server.
*/
private transient volatile long retryWindow;
/**
* Latest data as read from the data file.
*/
private transient Data data;
/**
* ID string for this update source.
*/
private final String id;
/**
* Path to {@code update-center.json}, like {@code http://jenkins-ci.org/update-center.json}.
*/
private final String url;
/**
* the prefix for the signature validator name
*/
private static final String signatureValidatorPrefix = "update site";
private static final Set<String> warnedMissing = Collections.synchronizedSet(new HashSet<>());
public UpdateSite(String id, String url) {
this.id = id;
this.url = url;
}
/**
* Get ID string.
*/
@Exported
public String getId() {
return id;
}
@Exported
public long getDataTimestamp() {
assert dataTimestamp >= 0;
return dataTimestamp;
}
/**
* Update the data file from the given URL if the file
* does not exist, or is otherwise due for update.
* Accepted formats are JSONP or HTML with {@code postMessage}, not raw JSON.
* @return null if no updates are necessary, or the future result
* @since 2.222
*/
public @CheckForNull Future<FormValidation> updateDirectly() {
return updateDirectly(DownloadService.signatureCheck);
}
/**
* Update the data file from the given URL if the file
* does not exist, or is otherwise due for update.
* Accepted formats are JSONP or HTML with {@code postMessage}, not raw JSON.
* @param signatureCheck whether to enforce the signature (may be off only for testing!)
* @return null if no updates are necessary, or the future result
* @since 1.502
* @deprecated use {@linkplain #updateDirectly()}
*/
@Deprecated
public @CheckForNull Future<FormValidation> updateDirectly(final boolean signatureCheck) {
if (! getDataFile().exists() || isDue()) {
return Jenkins.get().getUpdateCenter().updateService.submit(new Callable<FormValidation>() {
@Override public FormValidation call() throws Exception {
return updateDirectlyNow(signatureCheck);
}
});
} else {
return null;
}
}
/**
* Forces an update of the data file from the configured URL, irrespective of the last time the data was retrieved.
* @return A {@code FormValidation} indicating the if the update metadata was successfully downloaded from the configured update site
* @since 2.222
* @throws IOException if there was an error downloading or saving the file.
*/
public @NonNull FormValidation updateDirectlyNow() throws IOException {
return updateDirectlyNow(DownloadService.signatureCheck);
}
@Restricted(NoExternalUse.class)
public @NonNull FormValidation updateDirectlyNow(boolean signatureCheck) throws IOException {
return updateData(DownloadService.loadJSON(new URL(getUrl() + "?id=" + URLEncoder.encode(getId(), StandardCharsets.UTF_8) + "&version=" + URLEncoder.encode(Jenkins.VERSION, StandardCharsets.UTF_8))), signatureCheck);
}
private FormValidation updateData(String json, boolean signatureCheck)
throws IOException {
dataTimestamp = System.currentTimeMillis();
JSONObject o = JSONObject.fromObject(json);
try {
int v = o.getInt("updateCenterVersion");
if (v != 1) {
throw new IllegalArgumentException("Unrecognized update center version: " + v);
}
} catch (JSONException x) {
throw new IllegalArgumentException("Could not find (numeric) updateCenterVersion in " + json, x);
}
if (signatureCheck) {
FormValidation e = verifySignatureInternal(o);
if (e.kind != FormValidation.Kind.OK) {
LOGGER.severe(e.toString());
return e;
}
}
LOGGER.fine(() -> "Obtained the latest update center data file for UpdateSource " + id);
retryWindow = 0;
getDataFile().write(json);
data = new Data(o);
return FormValidation.ok();
}
public FormValidation doVerifySignature() throws IOException {
return verifySignatureInternal(getJSONObject());
}
/**
* Extension point to allow implementations of {@link UpdateSite} to create a custom
* {@link UpdateCenter.InstallationJob}.
*
* @param plugin the plugin to create the {@link UpdateCenter.InstallationJob} for.
* @param uc the {@link UpdateCenter}.
* @param dynamicLoad {@code true} if the plugin should be attempted to be dynamically loaded.
* @return the {@link UpdateCenter.InstallationJob}.
* @since 2.9
*/
protected UpdateCenter.InstallationJob createInstallationJob(Plugin plugin, UpdateCenter uc, boolean dynamicLoad) {
return uc.new InstallationJob(plugin, this, Jenkins.getAuthentication2(), dynamicLoad);
}
/**
* Verifies the signature in the update center data file.
*/
@Restricted(NoExternalUse.class)
public final FormValidation verifySignatureInternal(JSONObject o) throws IOException {
return getJsonSignatureValidator().verifySignature(o);
}
/**
* Let sub-classes of UpdateSite provide their own signature validator.
* @return the signature validator.
* @deprecated use {@link #getJsonSignatureValidator(String)} instead.
*/
@Deprecated
@NonNull
protected JSONSignatureValidator getJsonSignatureValidator() {
return getJsonSignatureValidator(null);
}
/**
* Let sub-classes of UpdateSite provide their own signature validator.
* @param name the name for the JSON signature Validator object.
* if name is null, then the default name will be used,
* which is "update site" followed by the update site id
* @return the signature validator.
* @since 2.21
*/
@NonNull
protected JSONSignatureValidator getJsonSignatureValidator(@CheckForNull String name) {
if (name == null) {
name = signatureValidatorPrefix + " '" + id + "'";
}
return new JSONSignatureValidator(name);
}
/**
* Returns true if it's time for us to check for new version.
*/
public synchronized boolean isDue() {
if (neverUpdate) return false;
if (dataTimestamp == 0)
dataTimestamp = getDataFile().file.lastModified();
long now = System.currentTimeMillis();
retryWindow = Math.max(retryWindow, SECONDS.toMillis(15));
boolean due = now - dataTimestamp > DAY && now - lastAttempt > retryWindow;
if (due) {
lastAttempt = now;
retryWindow = Math.min(retryWindow * 2, HOURS.toMillis(1)); // exponential back off but at most 1 hour
}
return due;
}
/**
* Invalidates the cached data and force retrieval.
*
* @since 1.432
*/
@RequirePOST
public HttpResponse doInvalidateData() {
Jenkins.get().checkPermission(Jenkins.ADMINISTER);
dataTimestamp = 0;
data = null;
return HttpResponses.ok();
}
/**
* Loads the update center data, if any.
*
* @return null if no data is available.
*/
@CheckForNull
public Data getData() {
if (data == null) {
JSONObject o = getJSONObject();
if (o != null) {
data = new Data(o);
}
}
return data;
}
/**
* Whether {@link #getData} might be blocking.
*/
// Internal use only
boolean hasUnparsedData() {
return data == null && getDataFile().exists();
}
/**
* Gets the raw update center JSON data.
*/
public JSONObject getJSONObject() {
TextFile df = getDataFile();
if (df.exists()) {
long start = System.nanoTime();
try {
JSONObject o = JSONObject.fromObject(df.read());
LOGGER.fine(() -> String.format("Loaded and parsed %s in %.01fs", df, (System.nanoTime() - start) / 1_000_000_000.0));
return o;
} catch (JSONException | IOException e) {
LOGGER.log(Level.SEVERE, "Failed to parse " + df, e);
try {
df.delete(); // if we keep this file, it will cause repeated failures
} catch (IOException e2) {
LOGGER.log(Level.SEVERE, "Failed to delete " + df, e2);
}
return null;
}
} else {
return null;
}
}
/**
* Returns a list of plugins that should be shown in the "available" tab.
* These are "all plugins - installed plugins".
*/
@Exported
public List<Plugin> getAvailables() {
List<Plugin> r = new ArrayList<>();
Data data = getData();
if (data == null) return Collections.emptyList();
for (Plugin p : data.plugins.values()) {
if (p.getInstalled() == null)
r.add(p);
}
r.sort((plugin, t1) -> {
final int pop = t1.popularity.compareTo(plugin.popularity);
if (pop != 0) {
return pop; // highest popularity first
}
return plugin.getDisplayName().compareTo(t1.getDisplayName());
});
return r;
}
/**
* Gets the information about a specific plugin.
*
* @param artifactId
* The short name of the plugin. Corresponds to {@link PluginWrapper#getShortName()}.
*
* @return
* {@code null} if no such information is found.
*/
@CheckForNull
public Plugin getPlugin(String artifactId) {
Data dt = getData();
if (dt == null) return null;
return dt.plugins.get(artifactId);
}
public Api getApi() {
return new Api(this);
}
/**
* Gets a URL for the Internet connection check.
* @return an "always up" server for Internet connectivity testing, or {@code null} if we are going to skip the test.
*/
@Exported
@CheckForNull
public String getConnectionCheckUrl() {
Data dt = getData();
if (dt == null) return "http://www.google.com/";
return dt.connectionCheckUrl;
}
/**
* This is where we store the update center data.
*/
private TextFile getDataFile() {
return new TextFile(new File(Jenkins.get().getRootDir(),
"updates/" + getId() + ".json"));
}
/**
* Returns the list of plugins that are updates to currently installed ones.
*
* @return
* can be empty but never null.
*/
@Exported
public List<Plugin> getUpdates() {
Data data = getData();
if (data == null) return Collections.emptyList(); // fail to determine
List<Plugin> r = new ArrayList<>();
for (PluginWrapper pw : Jenkins.get().getPluginManager().getPlugins()) {
Plugin p = pw.getUpdateInfo();
if (p != null) r.add(p);
}
return r;
}
/**
* Does any of the plugin has updates?
*/
@Exported
public boolean hasUpdates() {
Data data = getData();
if (data == null) return false;
for (PluginWrapper pw : Jenkins.get().getPluginManager().getPlugins()) {
if (!pw.isBundled() && pw.getUpdateInfo() != null)
// do not advertize updates to bundled plugins, since we generally want users to get them
// as a part of jenkins.war updates. This also avoids unnecessary pinning of plugins.
return true;
}
return false;
}
/**
* Exposed to get rid of hardcoding of the URL that serves up update-center.json
* in JavaScript.
*/
@Exported
public String getUrl() {
return url;
}
/**
*
* @return the URL used by {@link jenkins.install.SetupWizard} for suggested plugins to install at setup time
* @since 2.446
*/
@Exported
public String getSuggestedPluginsUrl() {
String updateCenterJsonUrl = getUrl();
return updateCenterJsonUrl.replace("/update-center.json", "/platform-plugins.json");
}
/**
* URL which exposes the metadata location in a specific update site.
* @param downloadable the downloadable id of a specific metatadata json (e.g. hudson.tasks.Maven.MavenInstaller.json)
* @return the location
* @since 2.20
*/
@CheckForNull
@Restricted(NoExternalUse.class)
public String getMetadataUrlForDownloadable(String downloadable) {
String siteUrl = getUrl();
String updateSiteMetadataUrl = null;
int baseUrlEnd = siteUrl.indexOf("update-center.json");
if (baseUrlEnd != -1) {
String siteBaseUrl = siteUrl.substring(0, baseUrlEnd);
updateSiteMetadataUrl = siteBaseUrl + "updates/" + downloadable;
} else {
LOGGER.log(Level.WARNING, "Url {0} does not look like an update center:", siteUrl);
}
return updateSiteMetadataUrl;
}
/**
* Where to actually download the update center?
*
* @deprecated
* Exposed only for UI.
*/
@Deprecated
public String getDownloadUrl() {
return url;
}
/**
* Is this the legacy default update center site?
* @deprecated
* Will be removed, currently returns always false.
* @since 2.343
*/
@Deprecated
@Restricted(NoExternalUse.class)
public boolean isLegacyDefault() {
return false;
}
/**
* In-memory representation of the update center data.
*/
public final class Data {
/**
* The {@link UpdateSite} ID.
*/
public final String sourceId;
/**
* The latest jenkins.war.
*/
public final Entry core;
/**
* Plugins in the repository, keyed by their artifact IDs.
*/
public final Map<String, Plugin> plugins = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
/**
* List of warnings (mostly security) published with the update site.
*
* @since 2.40
*/
private final Set<Warning> warnings = new HashSet<>();
/**
* Mapping of plugin IDs to deprecation notices
*
* @since 2.246
*/
private final Map<String, Deprecation> deprecations = new HashMap<>();
/**
* If this is non-null, Jenkins is going to check the connectivity to this URL to make sure
* the network connection is up. Null to skip the check.
*/
public final String connectionCheckUrl;
Data(JSONObject o) {
this.sourceId = Util.intern((String) o.get("id"));
JSONObject c = o.optJSONObject("core");
if (c != null) {
core = new Entry(sourceId, c, url);
} else {
core = null;
}
JSONArray w = o.optJSONArray("warnings");
if (w != null) {
for (int i = 0; i < w.size(); i++) {
try {
warnings.add(new Warning(w.getJSONObject(i)));
} catch (JSONException ex) {
LOGGER.log(Level.WARNING, "Failed to parse JSON for warning", ex);
}
}
}
JSONObject deprecations = o.optJSONObject("deprecations");
if (deprecations != null) {
for (Iterator it = deprecations.keys(); it.hasNext(); ) {
try {
String pluginId = it.next().toString();
JSONObject entry = deprecations.getJSONObject(pluginId); // additional level of indirection to support future extensibility
if (entry != null) {
String referenceUrl = entry.getString("url");
if (referenceUrl != null) {
this.deprecations.put(pluginId, new Deprecation(referenceUrl));
}
}
} catch (RuntimeException ex) {
LOGGER.log(Level.WARNING, "Failed to parse JSON for deprecation", ex);
}
}
}
for (Map.Entry<String, JSONObject> e : (Set<Map.Entry<String, JSONObject>>) o.getJSONObject("plugins").entrySet()) {
Plugin p = new Plugin(sourceId, e.getValue());
// JENKINS-33308 - include implied dependencies for older plugins that may need them
List<PluginWrapper.Dependency> implicitDeps = DetachedPluginsUtil.getImpliedDependencies(p.name, p.requiredCore);
if (!implicitDeps.isEmpty()) {
for (PluginWrapper.Dependency dep : implicitDeps) {
if (!p.dependencies.containsKey(dep.shortName)) {
p.dependencies.put(dep.shortName, dep.version);
}
}
}
plugins.put(Util.intern(e.getKey()), p);
// compatibility with update sites that have no separate 'deprecated' top-level entry.
// Also do this even if there are deprecations to potentially allow limiting the top-level entry to overridden URLs.
if (p.hasCategory("deprecated")) {
if (!this.deprecations.containsKey(p.name)) {
this.deprecations.put(p.name, new Deprecation(p.wiki));
}
}
}
connectionCheckUrl = (String) o.get("connectionCheckUrl");
}
/**
* Returns the set of warnings
* @return the set of warnings
* @since 2.40
*/
@Restricted(NoExternalUse.class)
public Set<Warning> getWarnings() {
return this.warnings;
}
/**
* Returns the deprecations provided by the update site
* @return the deprecations provided by the update site
* @since 2.246
*/
@Restricted(NoExternalUse.class)
public Map<String, Deprecation> getDeprecations() {
return this.deprecations;
}
/**
* Is there a new version of the core?
*/
public boolean hasCoreUpdates() {
return core != null && core.isNewerThan(Jenkins.VERSION);
}
/**
* Do we support upgrade?
*/
public boolean canUpgrade() {
return Lifecycle.get().canRewriteHudsonWar();
}
}
@ExportedBean
public static class Entry {
/**
* {@link UpdateSite} ID.
*/
@Exported
public final String sourceId;
/**
* Artifact ID.
*/
@Exported
public final String name;
/**
* The version.
*/
@Exported
public final String version;
/**
* Download URL.
*/
@Exported
public final String url;
/**
* Size of the file in bytes, or {@code null} if unknown.
*/
private final Long size;
// non-private, non-final for test
@Restricted(NoExternalUse.class)
/* final */ String sha1;
@Restricted(NoExternalUse.class)
/* final */ String sha256;
@Restricted(NoExternalUse.class)
/* final */ String sha512;
public Entry(String sourceId, JSONObject o) {
this(sourceId, o, null);
}
Entry(String sourceId, JSONObject o, String baseURL) {
this.sourceId = sourceId;
this.name = Util.intern(o.getString("name"));
this.version = Util.intern(o.getString("version"));
// Trim this to prevent issues when the other end used Base64.encodeBase64String that added newlines
// to the end in old commons-codec. Not the case on updates.jenkins-ci.org, but let's be safe.
this.sha1 = Util.fixEmptyAndTrim(o.optString("sha1"));
this.sha256 = Util.fixEmptyAndTrim(o.optString("sha256"));
this.sha512 = Util.fixEmptyAndTrim(o.optString("sha512"));
Long fileSize = null;
if (o.has("size")) {
fileSize = o.getLong("size");
}
this.size = fileSize;
String url = o.getString("url");
if (!URI.create(url).isAbsolute()) {
if (baseURL == null) {
throw new IllegalArgumentException("Cannot resolve " + url + " without a base URL");
}
url = URI.create(baseURL).resolve(url).toString();
}
this.url = url;
}
/**
* The base64 encoded binary SHA-1 checksum of the file.
* Can be null if not provided by the update site.
* @since 1.641 (and 1.625.3 LTS)
*/
// TODO @Exported assuming we want this in the API
public String getSha1() {
return sha1;
}
/**
* The base64 encoded SHA-256 checksum of the file.
* Can be null if not provided by the update site.
* @since 2.130
*/
public String getSha256() {
return sha256;
}
/**
* The base64 encoded SHA-512 checksum of the file.
* Can be null if not provided by the update site.
* @since 2.130
*/
public String getSha512() {
return sha512;
}
/**
* Checks if the specified "current version" is older than the version of this entry.
*
* @param currentVersion
* The string that represents the version number to be compared.
* @return
* true if the version listed in this entry is newer.
* false otherwise, including the situation where the strings couldn't be parsed as version numbers.
*/
public boolean isNewerThan(String currentVersion) {
try {
return new VersionNumber(currentVersion).compareTo(new VersionNumber(version)) < 0;
} catch (IllegalArgumentException e) {
// couldn't parse as the version number.
return false;
}
}
public Api getApi() {
return new Api(this);
}
/**
* Size of the file being advertised in bytes, or {@code null} if unspecified/unknown.
* @return size of the file if known, {@code null} otherwise.
*
* @since 2.325
*/
// @Exported -- TODO unsure
@Restricted(NoExternalUse.class)
public Long getFileSize() {
return size;
}
}
/**
* A version range for {@code Warning}s indicates which versions of a given plugin are affected
* by it.
*
* {@link #name}, {@link #firstVersion} and {@link #lastVersion} fields are only used for administrator notices.
*
* The {@link #pattern} is used to determine whether a given warning applies to the current installation.
*
* @since 2.40
*/
@Restricted(NoExternalUse.class)
public static final class WarningVersionRange {
/**
* Human-readable English name for this version range, e.g. 'regular', 'LTS', '2.6 line'.
*/
@Nullable
public final String name;
/**
* First version in this version range to be subject to the warning.
*/
@Nullable
public final String firstVersion;
/**
* Last version in this version range to be subject to the warning.
*/
@Nullable
public final String lastVersion;
/**
* Regular expression pattern for this version range that matches all included version numbers.
*/
@NonNull
private final Pattern pattern;
public WarningVersionRange(JSONObject o) {
this.name = Util.fixEmpty(o.optString("name"));
this.firstVersion = Util.intern(Util.fixEmpty(o.optString("firstVersion")));
this.lastVersion = Util.intern(Util.fixEmpty(o.optString("lastVersion")));
Pattern p;
try {
p = Pattern.compile(o.getString("pattern"));
} catch (PatternSyntaxException ex) {
LOGGER.log(Level.WARNING, "Failed to compile pattern '" + o.getString("pattern") + "', using '.*' instead", ex);
p = Pattern.compile(".*");
}
this.pattern = p;
}
public boolean includes(VersionNumber number) {
return pattern.matcher(number.toString()).matches();
}
}
/**
* Represents a deprecation of a certain component. Jenkins project policy determines exactly what it means.
*
* @since 2.246
*/
@Restricted(NoExternalUse.class)
public static final class Deprecation {
/**
* URL for this deprecation.
*
* Jenkins will show a link to this URL when displaying the deprecation message.
*/
public final String url;
public Deprecation(String url) {
this.url = url;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Deprecation that = (Deprecation) o;
return Objects.equals(url, that.url);
}
@Override
public int hashCode() {
return Objects.hash(url);
}
}
@Restricted(NoExternalUse.class)
public enum WarningType {
CORE,
PLUGIN,
UNKNOWN
}
/**
* Represents a warning about a certain component, mostly related to known security issues.
*
* @see UpdateSiteWarningsConfiguration
* @see jenkins.security.UpdateSiteWarningsMonitor
*
* @since 2.40
*/
@Restricted(NoExternalUse.class)
public final class Warning {
/**
* The type classifier for this warning.
*/
@NonNull
public /* final */ WarningType type;
/**
* The globally unique ID of this warning.
*
* <p>This is typically the CVE identifier or SECURITY issue (Jenkins project);
* possibly with a unique suffix (e.g. artifactId) if either applies to multiple components.</p>
*/
@Exported
@NonNull
public final String id;
/**
* The name of the affected component.
* <ul>
* <li>If type is 'core', this is 'core' by convention.
* <li>If type is 'plugin', this is the artifactId of the affected plugin
* </ul>
*/
@Exported
@NonNull
public final String component;
/**
* A short, English language explanation for this warning.
*/
@Exported
@NonNull
public final String message;
/**
* A URL with more information about this, typically a security advisory. For use in administrator notices
* only, so
*/
@Exported
@NonNull
public final String url;
/**
* A list of named version ranges specifying which versions of the named component this warning applies to.
*
* If this list is empty, all versions of the component are considered to be affected by this warning.
*/
@Exported
@NonNull
public final List<WarningVersionRange> versionRanges;
/**
*
* @param o the {@link JSONObject} representing the warning
* @throws JSONException if the argument does not match the expected format
*/
@Restricted(NoExternalUse.class)
public Warning(JSONObject o) {
try {
this.type = WarningType.valueOf(o.getString("type").toUpperCase(Locale.US));
} catch (IllegalArgumentException ex) {
this.type = WarningType.UNKNOWN;
}
this.id = o.getString("id");
this.component = Util.intern(o.getString("name"));
this.message = o.getString("message");
this.url = o.getString("url");
if (o.has("versions")) {
JSONArray versions = o.getJSONArray("versions");
List<WarningVersionRange> ranges = new ArrayList<>(versions.size());
for (int i = 0; i < versions.size(); i++) {
WarningVersionRange range = new WarningVersionRange(versions.getJSONObject(i));
ranges.add(range);
}
this.versionRanges = Collections.unmodifiableList(ranges);