UpdateSite.java 44.5 KB
Newer Older
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
/*
 * 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;

28
import hudson.ClassicPluginStrategy;
29
import hudson.ExtensionList;
30
import hudson.PluginManager;
31
import hudson.PluginWrapper;
32
import hudson.Util;
33
import hudson.lifecycle.Lifecycle;
34 35 36
import hudson.model.UpdateCenter.UpdateCenterJob;
import hudson.util.FormValidation;
import hudson.util.FormValidation.Kind;
37
import hudson.util.HttpResponses;
38
import hudson.util.TextFile;
B
Baptiste Mathus 已提交
39
import static java.util.concurrent.TimeUnit.*;
40 41 42
import hudson.util.VersionNumber;
import java.io.File;
import java.io.IOException;
43
import java.net.URI;
44
import java.net.URL;
45
import java.net.URLEncoder;
46
import java.security.GeneralSecurityException;
47 48
import java.util.ArrayList;
import java.util.Collections;
49
import java.util.HashMap;
50
import java.util.HashSet;
51
import java.util.List;
52
import java.util.Locale;
53 54
import java.util.Map;
import java.util.Set;
55
import java.util.TreeMap;
56
import java.util.UUID;
57
import java.util.concurrent.Callable;
58 59 60
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
61 62
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
63 64
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
65 66
import javax.annotation.Nullable;

67
import jenkins.model.Jenkins;
68
import jenkins.model.DownloadSettings;
69
import jenkins.security.UpdateSiteWarningsConfiguration;
70
import jenkins.util.JSONSignatureValidator;
71
import jenkins.util.SystemProperties;
72
import net.sf.json.JSONArray;
73 74
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
75
import org.apache.commons.io.IOUtils;
76 77
import org.apache.commons.lang.StringUtils;
import org.kohsuke.accmod.Restricted;
78
import org.kohsuke.accmod.restrictions.DoNotUse;
79 80 81 82 83 84 85
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.interceptor.RequirePOST;
86 87

/**
K
Kohsuke Kawaguchi 已提交
88
 * Source of the update center information, like "http://jenkins-ci.org/update-center.json"
89 90
 *
 * <p>
A
alanharder 已提交
91
 * Jenkins can have multiple {@link UpdateSite}s registered in the system, so that it can pick up plugins
92 93 94 95
 * from different locations.
 *
 * @author Andrew Bayer
 * @author Kohsuke Kawaguchi
96
 * @since 1.333
97
 */
98
@ExportedBean
99 100 101
public class UpdateSite {
    /**
     * What's the time stamp of data file?
102
     * 0 means never.
103
     */
104
    private transient volatile long dataTimestamp;
105 106 107

    /**
     * When was the last time we asked a browser to check the data for us?
108
     * 0 means never.
109 110 111
     *
     * <p>
     * There's normally some delay between when we send HTML that includes the check code,
112
     * until we get the data back, so this variable is used to avoid asking too many browsers
113 114
     * all at once.
     */
115
    private transient volatile long lastAttempt;
116

117 118 119 120 121 122
    /**
     * 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;

123 124 125 126 127 128 129 130
    /**
     * lastModified time of the data file when it was last read.
     */
    private transient long dataLastReadFromFile;

    /**
     * Latest data as read from the data file.
     */
131
    private transient Data data;
132

133 134 135 136 137 138
    /**
     * ID string for this update source.
     */
    private final String id;

    /**
K
Kohsuke Kawaguchi 已提交
139
     * Path to <tt>update-center.json</tt>, like <tt>http://jenkins-ci.org/update-center.json</tt>.
140 141 142
     */
    private final String url;

143 144 145 146
    /**
     * the prefix for the signature validator name
     */
    private static final String signatureValidatorPrefix = "update site";
147 148


149 150 151 152 153 154 155 156
    public UpdateSite(String id, String url) {
        this.id = id;
        this.url = url;
    }

    /**
     * Get ID string.
     */
157
    @Exported
158 159 160 161
    public String getId() {
        return id;
    }

162
    @Exported
163
    public long getDataTimestamp() {
164
        assert dataTimestamp >= 0;
165 166 167
        return dataTimestamp;
    }

168
    /**
169
     * Update the data file from the given URL if the file
170
     * does not exist, or is otherwise due for update.
171 172
     * 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!)
173
     * @return null if no updates are necessary, or the future result
174
     * @since 1.502
175
     */
176
    public @CheckForNull Future<FormValidation> updateDirectly(final boolean signatureCheck) {
177 178
        if (! getDataFile().exists() || isDue()) {
            return Jenkins.getInstance().getUpdateCenter().updateService.submit(new Callable<FormValidation>() {
179 180
                @Override public FormValidation call() throws Exception {
                    return updateDirectlyNow(signatureCheck);
181 182
                }
            });
183
        } else {
184
            return null;
185 186 187 188 189 190
        }
    }

    @Restricted(NoExternalUse.class)
    public @Nonnull FormValidation updateDirectlyNow(boolean signatureCheck) throws IOException {
        return updateData(DownloadService.loadJSON(new URL(getUrl() + "?id=" + URLEncoder.encode(getId(), "UTF-8") + "&version=" + URLEncoder.encode(Jenkins.VERSION, "UTF-8"))), signatureCheck);
191 192
    }
    
193 194 195
    /**
     * This is the endpoint that receives the update center data file from the browser.
     */
196
    @RequirePOST
197
    public FormValidation doPostBack(StaplerRequest req) throws IOException, GeneralSecurityException {
198
        DownloadSettings.checkPostBackAccess();
199
        return updateData(IOUtils.toString(req.getInputStream(),"UTF-8"), true);
200 201
    }

202
    private FormValidation updateData(String json, boolean signatureCheck)
203 204 205 206
            throws IOException {

        dataTimestamp = System.currentTimeMillis();

207 208
        JSONObject o = JSONObject.fromObject(json);

209 210 211 212 213 214 215 216
        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);
        }
217 218 219

        if (signatureCheck) {
            FormValidation e = verifySignature(o);
220
            if (e.kind!=Kind.OK) {
221
                LOGGER.severe(e.toString());
222 223
                return e;
            }
224 225
        }

K
bug fix  
Kohsuke Kawaguchi 已提交
226
        LOGGER.info("Obtained the latest update center data file for UpdateSource " + id);
227
        retryWindow = 0;
228
        getDataFile().write(json);
229 230 231 232 233
        return FormValidation.ok();
    }

    public FormValidation doVerifySignature() throws IOException {
        return verifySignature(getJSONObject());
234 235
    }

236 237 238 239 240 241 242 243 244 245 246 247 248 249
    /**
     * 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.getAuthentication(), dynamicLoad);
    }

250 251 252
    /**
     * Verifies the signature in the update center data file.
     */
253
    private FormValidation verifySignature(JSONObject o) throws IOException {
254 255 256 257 258 259
        return getJsonSignatureValidator().verifySignature(o);
    }

    /**
     * Let sub-classes of UpdateSite provide their own signature validator.
     * @return the signature validator.
260
     * @deprecated use {@link #getJsonSignatureValidator(@CheckForNull String)} instead.
261
     */
262
    @Deprecated
263 264
    @Nonnull
    protected JSONSignatureValidator getJsonSignatureValidator() {
265 266 267 268 269 270 271 272 273
        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.
274
     * @since 2.21
275 276 277 278 279 280 281
     */
    @Nonnull
    protected JSONSignatureValidator getJsonSignatureValidator(@CheckForNull String name) {
        if (name == null) {
            name = signatureValidatorPrefix + " '" + id + "'";
        }
        return new JSONSignatureValidator(name);
282 283 284 285 286 287 288
    }

    /**
     * Returns true if it's time for us to check for new version.
     */
    public boolean isDue() {
        if(neverUpdate)     return false;
289
        if(dataTimestamp == 0)
290 291
            dataTimestamp = getDataFile().file.lastModified();
        long now = System.currentTimeMillis();
292 293 294 295 296 297 298 299
        
        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
        }
300 301 302
        return due;
    }

303 304 305 306 307
    /**
     * Invalidates the cached data and force retrieval.
     *
     * @since 1.432
     */
308
    @RequirePOST
309 310 311 312 313 314
    public HttpResponse doInvalidateData() {
        Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
        dataTimestamp = 0;
        return HttpResponses.ok();
    }

315
    /**
316
     * Loads the update center data, if any and if modified since last read.
317 318 319 320
     *
     * @return  null if no data is available.
     */
    public Data getData() {
321 322 323 324 325 326 327 328 329 330 331
        TextFile df = getDataFile();
        if (df.exists() && dataLastReadFromFile != df.file.lastModified()) {
            JSONObject o = getJSONObject();
            if (o!=null) {
                data = new Data(o);
                dataLastReadFromFile = df.file.lastModified();
            } else {
                data = null;
            }
        }
        return data;
332 333 334 335 336 337
    }

    /**
     * Gets the raw update center JSON data.
     */
    public JSONObject getJSONObject() {
338 339 340
        TextFile df = getDataFile();
        if(df.exists()) {
            try {
341
                return JSONObject.fromObject(df.read());
342 343 344 345
            } catch (JSONException e) {
                LOGGER.log(Level.SEVERE,"Failed to parse "+df,e);
                df.delete(); // if we keep this file, it will cause repeated failures
                return null;
346 347 348 349 350 351 352 353 354
            } catch (IOException e) {
                LOGGER.log(Level.SEVERE,"Failed to parse "+df,e);
                df.delete(); // if we keep this file, it will cause repeated failures
                return null;
            }
        } else {
            return null;
        }
    }
355

356 357 358 359
    /**
     * Returns a list of plugins that should be shown in the "available" tab.
     * These are "all plugins - installed plugins".
     */
360
    @Exported
361 362 363
    public List<Plugin> getAvailables() {
        List<Plugin> r = new ArrayList<Plugin>();
        Data data = getData();
364
        if(data==null)     return Collections.emptyList();
365 366 367 368 369 370
        for (Plugin p : data.plugins.values()) {
            if(p.getInstalled()==null)
                r.add(p);
        }
        return r;
    }
371

372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
    /**
     * Gets the information about a specific plugin.
     *
     * @param artifactId
     *      The short name of the plugin. Corresponds to {@link PluginWrapper#getShortName()}.
     *
     * @return
     *      null if no such information is found.
     */
    public Plugin getPlugin(String artifactId) {
        Data dt = getData();
        if(dt==null)    return null;
        return dt.plugins.get(artifactId);
    }

387 388 389 390
    public Api getApi() {
        return new Api(this);
    }

391
    /**
392 393
     * 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.
394
     */
395
    @Exported
396
    @CheckForNull
397 398 399 400 401 402 403 404 405 406
    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() {
407
        return new TextFile(new File(Jenkins.getInstance().getRootDir(),
408 409 410 411 412 413 414 415 416
                                     "updates/" + getId()+".json"));
    }
    
    /**
     * Returns the list of plugins that are updates to currently installed ones.
     *
     * @return
     *      can be empty but never null.
     */
417
    @Exported
418 419 420 421 422
    public List<Plugin> getUpdates() {
        Data data = getData();
        if(data==null)      return Collections.emptyList(); // fail to determine
        
        List<Plugin> r = new ArrayList<Plugin>();
423
        for (PluginWrapper pw : Jenkins.getInstance().getPluginManager().getPlugins()) {
424 425 426 427 428 429 430 431 432 433
            Plugin p = pw.getUpdateInfo();
            if(p!=null) r.add(p);
        }
        
        return r;
    }
    
    /**
     * Does any of the plugin has updates?
     */
434
    @Exported
435 436 437 438
    public boolean hasUpdates() {
        Data data = getData();
        if(data==null)      return false;
        
439
        for (PluginWrapper pw : Jenkins.getInstance().getPluginManager().getPlugins()) {
440 441
            if(!pw.isBundled() && pw.getUpdateInfo()!=null)
                // do not advertize updates to bundled plugins, since we generally want users to get them
A
alanharder 已提交
442
                // as a part of jenkins.war updates. This also avoids unnecessary pinning of plugins. 
443 444 445 446 447 448 449 450 451 452
                return true;
        }
        return false;
    }
    
    
    /**
     * Exposed to get rid of hardcoding of the URL that serves up update-center.json
     * in Javascript.
     */
453
    @Exported
454 455 456 457
    public String getUrl() {
        return url;
    }

458 459 460 461 462

    /**
     * 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
463
     * @since 2.20
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
     */
    @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;
    }

480 481 482 483 484 485
    /**
     * Where to actually download the update center?
     *
     * @deprecated
     *      Exposed only for UI.
     */
486
    @Deprecated
487 488 489 490
    public String getDownloadUrl() {
        return url;
    }

K
kohsuke 已提交
491 492 493 494
    /**
     * Is this the legacy default update center site?
     */
    public boolean isLegacyDefault() {
495
        return id.equals(UpdateCenter.PREDEFINED_UPDATE_SITE_ID) && url.startsWith("http://hudson-ci.org/") || url.startsWith("http://updates.hudson-labs.org/");
K
kohsuke 已提交
496 497
    }

498 499 500 501 502 503 504 505 506 507
    /**
     * In-memory representation of the update center data.
     */
    public final class Data {
        /**
         * The {@link UpdateSite} ID.
         */
        public final String sourceId;

        /**
A
alanharder 已提交
508
         * The latest jenkins.war.
509 510 511 512 513 514
         */
        public final Entry core;
        /**
         * Plugins in the repository, keyed by their artifact IDs.
         */
        public final Map<String,Plugin> plugins = new TreeMap<String,Plugin>(String.CASE_INSENSITIVE_ORDER);
515 516 517
        /**
         * List of warnings (mostly security) published with the update site.
         *
518
         * @since 2.40
519 520
         */
        private final Set<Warning> warnings = new HashSet<Warning>();
521 522

        /**
A
alanharder 已提交
523
         * If this is non-null, Jenkins is going to check the connectivity to this URL to make sure
524 525 526 527 528 529
         * the network connection is up. Null to skip the check.
         */
        public final String connectionCheckUrl;

        Data(JSONObject o) {
            this.sourceId = (String)o.get("id");
530 531 532 533
            JSONObject c = o.optJSONObject("core");
            if (c!=null) {
                core = new Entry(sourceId, c, url);
            } else {
534 535
                core = null;
            }
536 537 538 539 540 541 542 543 544 545 546 547

            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);
                    }
                }
            }

548
            for(Map.Entry<String,JSONObject> e : (Set<Map.Entry<String,JSONObject>>)o.getJSONObject("plugins").entrySet()) {
549 550 551 552 553 554 555 556 557 558 559
                Plugin p = new Plugin(sourceId, e.getValue());
                // JENKINS-33308 - include implied dependencies for older plugins that may need them
                List<PluginWrapper.Dependency> implicitDeps = ClassicPluginStrategy.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(e.getKey(), p);
560 561 562 563 564
            }

            connectionCheckUrl = (String)o.get("connectionCheckUrl");
        }

565 566 567
        /**
         * Returns the set of warnings
         * @return the set of warnings
568
         * @since 2.40
569 570 571 572 573 574
         */
        @Restricted(NoExternalUse.class)
        public Set<Warning> getWarnings() {
            return this.warnings;
        }

575 576 577 578
        /**
         * Is there a new version of the core?
         */
        public boolean hasCoreUpdates() {
579
            return core != null && core.isNewerThan(Jenkins.VERSION);
580 581 582 583 584 585 586 587 588 589
        }

        /**
         * Do we support upgrade?
         */
        public boolean canUpgrade() {
            return Lifecycle.get().canRewriteHudsonWar();
        }
    }

590
    @ExportedBean
591 592 593 594
    public static class Entry {
        /**
         * {@link UpdateSite} ID.
         */
595
        @Exported
596 597 598 599 600
        public final String sourceId;

        /**
         * Artifact ID.
         */
601
        @Exported
602 603 604 605
        public final String name;
        /**
         * The version.
         */
606
        @Exported
607 608 609 610
        public final String version;
        /**
         * Download URL.
         */
611
        @Exported
612 613
        public final String url;

614 615 616 617

        // non-private, non-final for test
        @Restricted(NoExternalUse.class)
        /* final */ String sha1;
618

619 620 621 622 623 624
        @Restricted(NoExternalUse.class)
        /* final */ String sha256;

        @Restricted(NoExternalUse.class)
        /* final */ String sha512;

625
        public Entry(String sourceId, JSONObject o) {
626 627 628 629
            this(sourceId, o, null);
        }

        Entry(String sourceId, JSONObject o, String baseURL) {
630 631 632
            this.sourceId = sourceId;
            this.name = o.getString("name");
            this.version = o.getString("version");
633 634 635

            // 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.
636
            this.sha1 = Util.fixEmptyAndTrim(o.optString("sha1"));
637 638
            this.sha256 = Util.fixEmptyAndTrim(o.optString("sha256"));
            this.sha512 = Util.fixEmptyAndTrim(o.optString("sha512"));
639

640 641 642 643 644 645 646 647
            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;
648 649
        }

650 651 652
        /**
         * The base64 encoded binary SHA-1 checksum of the file.
         * Can be null if not provided by the update site.
D
Daniel Beck 已提交
653
         * @since 1.641 (and 1.625.3 LTS)
654 655 656 657 658 659
         */
        // TODO @Exported assuming we want this in the API
        public String getSha1() {
            return sha1;
        }

660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
        /**
         * The hex string encoded SHA-256 checksum of the file.
         * Can be null if not provided by the update site.
         * @since TODO
         */
        public String getSha256() {
            return sha256;
        }

        /**
         * The hex string encoded SHA-512 checksum of the file.
         * Can be null if not provided by the update site.
         * @since TODO
         */
        public String getSha512() {
            return sha512;
        }

678 679 680 681 682 683 684 685 686 687 688
        /**
         * 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 {
689
                return new VersionNumber(currentVersion).compareTo(new VersionNumber(version)) < 0;
690 691 692 693 694
            } catch (IllegalArgumentException e) {
                // couldn't parse as the version number.
                return false;
            }
        }
695

696 697 698 699
        public Api getApi() {
            return new Api(this);
        }

700 701
    }

702 703 704 705 706 707 708 709
    /**
     * 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.
     *
710
     * @since 2.40
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
     */
    @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.fixEmpty(o.optString("firstVersion"));
            this.lastVersion = 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 warning about a certain component, mostly related to known security issues.
     *
     * @see UpdateSiteWarningsConfiguration
     * @see jenkins.security.UpdateSiteWarningsMonitor
     *
763
     * @since 2.40
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
     */
    @Restricted(NoExternalUse.class)
    public static final class Warning {

        public enum Type {
            CORE,
            PLUGIN,
            UNKNOWN
        }

        /**
         * The type classifier for this warning.
         */
        @Nonnull
        public /* final */ Type 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 = Type.valueOf(o.getString("type").toUpperCase(Locale.US));
            } catch (IllegalArgumentException ex) {
                this.type = Type.UNKNOWN;
            }
            this.id = o.getString("id");
            this.component = o.getString("name");
            this.message = o.getString("message");
            this.url = o.getString("url");

            if (o.has("versions")) {
                List<WarningVersionRange> ranges = new ArrayList<>();
                JSONArray versions = o.getJSONArray("versions");
                for (int i = 0; i < versions.size(); i++) {
                    WarningVersionRange range = new WarningVersionRange(versions.getJSONObject(i));
                    ranges.add(range);
                }
                this.versionRanges = Collections.unmodifiableList(ranges);
            } else {
                this.versionRanges = Collections.emptyList();
            }
        }

        /**
         * Two objects are considered equal if they are the same type and have the same ID.
         *
         * @param o the other object
         * @return true iff this object and the argument are considered equal
         */
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof Warning)) return false;

            Warning warning = (Warning) o;

            return id.equals(warning.id);
        }

        @Override
        public int hashCode() {
            return id.hashCode();
        }

        public boolean isPluginWarning(@Nonnull String pluginName) {
            return type == Type.PLUGIN && pluginName.equals(this.component);
        }

        /**
         * Returns true if this warning is relevant to the current configuration
         * @return true if this warning is relevant to the current configuration
         */
        public boolean isRelevant() {
            switch (this.type) {
                case CORE:
                    VersionNumber current = Jenkins.getVersion();

                    if (!isRelevantToVersion(current)) {
                        return false;
                    }
                    return true;
                case PLUGIN:

                    // check whether plugin is installed
                    PluginWrapper plugin = Jenkins.getInstance().getPluginManager().getPlugin(this.component);
                    if (plugin == null) {
                        return false;
                    }

                    // check whether warning is relevant to installed version
                    VersionNumber currentCore = plugin.getVersionNumber();
                    if (!isRelevantToVersion(currentCore)) {
                        return false;
                    }
                    return true;
                case UNKNOWN:
                default:
                    return false;
            }
        }

        public boolean isRelevantToVersion(@Nonnull VersionNumber version) {
            if (this.versionRanges.isEmpty()) {
                // no version ranges specified, so all versions are affected
                return true;
            }

            for (UpdateSite.WarningVersionRange range : this.versionRanges) {
                if (range.includes(version)) {
                    return true;
                }
            }
            return false;
        }
    }

928 929 930 931
    public final class Plugin extends Entry {
        /**
         * Optional URL to the Wiki page that discusses this plugin.
         */
932
        @Exported
933 934 935 936 937 938 939 940
        public final String wiki;
        /**
         * Human readable title of the plugin, taken from Wiki page.
         * Can be null.
         *
         * <p>
         * beware of XSS vulnerability since this data comes from Wiki
         */
941
        @Exported
942 943 944 945
        public final String title;
        /**
         * Optional excerpt string.
         */
946
        @Exported
947 948 949 950
        public final String excerpt;
        /**
         * Optional version # from which this plugin release is configuration-compatible.
         */
951
        @Exported
952
        public final String compatibleSinceVersion;
953
        /**
A
alanharder 已提交
954
         * Version of Jenkins core this plugin was compiled against.
955
         */
956
        @Exported
957
        public final String requiredCore;
958 959 960 961
        /**
         * Categories for grouping plugins, taken from labels assigned to wiki page.
         * Can be null.
         */
962
        @Exported
963
        public final String[] categories;
964

965
        /**
966
         * Dependencies of this plugin, a name -&gt; version mapping.
967
         */
968
        @Exported
969 970
        public final Map<String,String> dependencies = new HashMap<String,String>();
        
971 972 973 974 975 976
        /**
         * Optional dependencies of this plugin.
         */
        @Exported
        public final Map<String,String> optionalDependencies = new HashMap<String,String>();

977 978
        @DataBoundConstructor
        public Plugin(String sourceId, JSONObject o) {
979
            super(sourceId, o, UpdateSite.this.url);
980 981 982 983
            this.wiki = get(o,"wiki");
            this.title = get(o,"title");
            this.excerpt = get(o,"excerpt");
            this.compatibleSinceVersion = get(o,"compatibleSinceVersion");
984
            this.requiredCore = get(o,"requiredCore");
985
            this.categories = o.has("labels") ? (String[])o.getJSONArray("labels").toArray(new String[0]) : null;
986 987
            for(Object jo : o.getJSONArray("dependencies")) {
                JSONObject depObj = (JSONObject) jo;
988 989
                // Make sure there's a name attribute and that the optional value isn't true.
                if (get(depObj,"name")!=null) {
990 991 992 993 994
                    if (get(depObj, "optional").equals("false")) {
                        dependencies.put(get(depObj, "name"), get(depObj, "version"));
                    } else {
                        optionalDependencies.put(get(depObj, "name"), get(depObj, "version"));
                    }
995 996 997 998
                }
                
            }

999 1000 1001 1002 1003 1004 1005 1006 1007 1008
        }

        private String get(JSONObject o, String prop) {
            if(o.has(prop))
                return o.getString(prop);
            else
                return null;
        }

        public String getDisplayName() {
1009 1010 1011 1012 1013 1014
            String displayName;
            if(title!=null)
                displayName = title;
            else
                displayName = name;
            return StringUtils.removeStart(displayName, "Jenkins ");
1015 1016 1017 1018 1019 1020
        }

        /**
         * If some version of this plugin is currently installed, return {@link PluginWrapper}.
         * Otherwise null.
         */
1021
        @Exported
1022
        public PluginWrapper getInstalled() {
1023
            PluginManager pm = Jenkins.getInstance().getPluginManager();
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
            return pm.getPlugin(name);
        }

        /**
         * If the plugin is already installed, and the new version of the plugin has a "compatibleSinceVersion"
         * value (i.e., it's only directly compatible with that version or later), this will check to
         * see if the installed version is older than the compatible-since version. If it is older, it'll return false.
         * If it's not older, or it's not installed, or it's installed but there's no compatibleSinceVersion
         * specified, it'll return true.
         */
1034
        @Exported
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
        public boolean isCompatibleWithInstalledVersion() {
            PluginWrapper installedVersion = getInstalled();
            if (installedVersion != null) {
                if (compatibleSinceVersion != null) {
                    if (new VersionNumber(installedVersion.getVersion())
                            .isOlderThan(new VersionNumber(compatibleSinceVersion))) {
                        return false;
                    }
                }
            }
            return true;
        }

1048 1049 1050
        /**
         * Returns a list of dependent plugins which need to be installed or upgraded for this plugin to work.
         */
1051
        @Exported
1052 1053 1054
        public List<Plugin> getNeededDependencies() {
            List<Plugin> deps = new ArrayList<Plugin>();

1055
            for(Map.Entry<String,String> e : dependencies.entrySet()) {
1056
                Plugin depPlugin = Jenkins.getInstance().getUpdateCenter().getPlugin(e.getKey());
1057 1058 1059 1060
                if (depPlugin == null) {
                    LOGGER.log(Level.WARNING, "Could not find dependency {0} of {1}", new Object[] {e.getKey(), name});
                    continue;
                }
1061
                VersionNumber requiredVersion = new VersionNumber(e.getValue());
1062 1063
                
                // Is the plugin installed already? If not, add it.
1064 1065 1066
                PluginWrapper current = depPlugin.getInstalled();

                if (current ==null) {
1067 1068 1069 1070
                    deps.add(depPlugin);
                }
                // If the dependency plugin is installed, is the version we depend on newer than
                // what's installed? If so, upgrade.
1071
                else if (current.isOlderThan(requiredVersion)) {
1072 1073
                    deps.add(depPlugin);
                }
1074 1075 1076 1077
                // JENKINS-34494 - or if the plugin is disabled, this will allow us to enable it
                else if (!current.isEnabled()) {
                    deps.add(depPlugin);
                }
1078 1079
            }

1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
            for(Map.Entry<String,String> e : optionalDependencies.entrySet()) {
                Plugin depPlugin = Jenkins.getInstance().getUpdateCenter().getPlugin(e.getKey());
                if (depPlugin == null) {
                    continue;
                }
                VersionNumber requiredVersion = new VersionNumber(e.getValue());

                PluginWrapper current = depPlugin.getInstalled();

                // If the optional dependency plugin is installed, is the version we depend on newer than
                // what's installed? If so, upgrade.
                if (current != null && current.isOlderThan(requiredVersion)) {
                    deps.add(depPlugin);
                }
            }

1096 1097 1098
            return deps;
        }
        
1099
        public boolean isForNewerHudson() {
1100 1101
            try {
                return requiredCore!=null && new VersionNumber(requiredCore).isNewerThan(
1102
                  new VersionNumber(Jenkins.VERSION.replaceFirst("SHOT *\\(private.*\\)", "SHOT")));
1103 1104 1105
            } catch (NumberFormatException nfe) {
                return true;  // If unable to parse version
            }
1106
        }
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143

        public VersionNumber getNeededDependenciesRequiredCore() {
            VersionNumber versionNumber = null;
            try {
                versionNumber = requiredCore == null ? null : new VersionNumber(requiredCore);
            } catch (NumberFormatException nfe) {
                // unable to parse version
            }
            for (Plugin p: getNeededDependencies()) {
                VersionNumber v = p.getNeededDependenciesRequiredCore();
                if (versionNumber == null || v.isNewerThan(versionNumber)) versionNumber = v;
            }
            return versionNumber;
        }

        public boolean isNeededDependenciesForNewerJenkins() {
            for (Plugin p: getNeededDependencies()) {
                if (p.isForNewerHudson() || p.isNeededDependenciesForNewerJenkins()) return true;
            }
            return false;
        }

        /**
         * If at least some of the plugin's needed dependencies are already installed, and the new version of the
         * needed dependencies plugin have a "compatibleSinceVersion"
         * value (i.e., it's only directly compatible with that version or later), this will check to
         * see if the installed version is older than the compatible-since version. If it is older, it'll return false.
         * If it's not older, or it's not installed, or it's installed but there's no compatibleSinceVersion
         * specified, it'll return true.
         */
        public boolean isNeededDependenciesCompatibleWithInstalledVersion() {
            for (Plugin p: getNeededDependencies()) {
                if (!p.isCompatibleWithInstalledVersion() || !p.isNeededDependenciesCompatibleWithInstalledVersion())
                    return false;
            }
            return true;
        }
1144

1145
        /**
1146
         * @since 2.40
1147 1148 1149 1150
         */
        @CheckForNull
        @Restricted(NoExternalUse.class)
        public Set<Warning> getWarnings() {
1151
            UpdateSiteWarningsConfiguration configuration = ExtensionList.lookupSingleton(UpdateSiteWarningsConfiguration.class);
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
            Set<Warning> warnings = new HashSet<>();

            for (Warning warning: configuration.getAllWarnings()) {
                if (configuration.isIgnored(warning)) {
                    // warning is currently being ignored
                    continue;
                }
                if (!warning.isPluginWarning(this.name)) {
                    // warning is not about this plugin
                    continue;
                }

                if (!warning.isRelevantToVersion(new VersionNumber(this.version))) {
                    // warning is not relevant to this version
                    continue;
                }
                warnings.add(warning);
            }

            return warnings;
        }

        /**
1175
         * @since 2.40
1176 1177 1178 1179 1180 1181
         */
        @Restricted(DoNotUse.class)
        public boolean hasWarnings() {
            return getWarnings().size() > 0;
        }

1182 1183 1184 1185
        /**
         * @deprecated as of 1.326
         *      Use {@link #deploy()}.
         */
1186
        @Deprecated
1187 1188 1189 1190
        public void install() {
            deploy();
        }

1191 1192 1193 1194
        public Future<UpdateCenterJob> deploy() {
            return deploy(false);
        }

1195 1196 1197 1198 1199 1200
        /**
         * Schedules the installation of this plugin.
         *
         * <p>
         * This is mainly intended to be called from the UI. The actual installation work happens
         * asynchronously in another thread.
1201 1202 1203 1204
         *
         * @param dynamicLoad
         *      If true, the plugin will be dynamically loaded into this Jenkins. If false,
         *      the plugin will only take effect after the reboot.
1205
         *      See {@link UpdateCenter#isRestartRequiredForCompletion()}
1206
         */
1207
        public Future<UpdateCenterJob> deploy(boolean dynamicLoad) {
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
            return deploy(dynamicLoad, null);
        }

        /**
         * Schedules the installation of this plugin.
         *
         * <p>
         * This is mainly intended to be called from the UI. The actual installation work happens
         * asynchronously in another thread.
         *
         * @param dynamicLoad
         *      If true, the plugin will be dynamically loaded into this Jenkins. If false,
         *      the plugin will only take effect after the reboot.
         *      See {@link UpdateCenter#isRestartRequiredForCompletion()}
         * @param correlationId A correlation ID to be set on the job.
         */
1224
        @Restricted(NoExternalUse.class)
1225
        public Future<UpdateCenterJob> deploy(boolean dynamicLoad, @CheckForNull UUID correlationId) {
1226 1227
            Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
            UpdateCenter uc = Jenkins.getInstance().getUpdateCenter();
1228
            for (Plugin dep : getNeededDependencies()) {
1229 1230
                UpdateCenter.InstallationJob job = uc.getJob(dep);
                if (job == null || job.status instanceof UpdateCenter.DownloadJob.Failure) {
1231
                    LOGGER.log(Level.INFO, "Adding dependent install of " + dep.name + " for plugin " + name);
1232 1233
                    dep.deploy(dynamicLoad);
                } else {
1234
                    LOGGER.log(Level.INFO, "Dependent install of " + dep.name + " for plugin " + name + " already added, skipping");
1235
                }
1236
            }
1237 1238 1239 1240
            PluginWrapper pw = getInstalled();
            if(pw != null) { // JENKINS-34494 - check for this plugin being disabled
                Future<UpdateCenterJob> enableJob = null;
                if(!pw.isEnabled()) {
1241
                    UpdateCenter.EnableJob job = uc.new EnableJob(UpdateSite.this, null, this, dynamicLoad);
1242 1243 1244 1245
                    job.setCorrelationId(correlationId);
                    enableJob = uc.addJob(job);
                }
                if(pw.getVersionNumber().equals(new VersionNumber(version))) {
1246
                    return enableJob != null ? enableJob : uc.addJob(uc.new NoOpJob(UpdateSite.this, null, this));
1247
                }
1248
            }
1249
            UpdateCenter.InstallationJob job = createInstallationJob(this, uc, dynamicLoad);
1250 1251
            job.setCorrelationId(correlationId);
            return uc.addJob(job);
1252 1253
        }

1254 1255 1256 1257
        /**
         * Schedules the downgrade of this plugin.
         */
        public Future<UpdateCenterJob> deployBackup() {
1258 1259 1260
            Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
            UpdateCenter uc = Jenkins.getInstance().getUpdateCenter();
            return uc.addJob(uc.new PluginDowngradeJob(this, UpdateSite.this, Jenkins.getAuthentication()));
1261
        }
1262 1263 1264
        /**
         * Making the installation web bound.
         */
1265
        @RequirePOST
1266 1267 1268 1269 1270
        public HttpResponse doInstall() throws IOException {
            deploy(false);
            return HttpResponses.redirectTo("../..");
        }

1271
        @RequirePOST
1272 1273 1274
        public HttpResponse doInstallNow() throws IOException {
            deploy(true);
            return HttpResponses.redirectTo("../..");
1275
        }
1276 1277 1278 1279

        /**
         * Performs the downgrade of the plugin.
         */
1280
        @RequirePOST
1281
        public HttpResponse doDowngrade() throws IOException {
1282
            deployBackup();
1283
            return HttpResponses.redirectTo("../..");
1284
        }
1285 1286 1287 1288 1289 1290
    }

    private static final long DAY = DAYS.toMillis(1);

    private static final Logger LOGGER = Logger.getLogger(UpdateSite.class.getName());

1291
    // The name uses UpdateCenter for compatibility reason.
1292
    public static boolean neverUpdate = SystemProperties.getBoolean(UpdateCenter.class.getName()+".never");
1293 1294

}