UpdateSite.java 22.2 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 28 29 30 31
/*
 * 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 hudson.PluginWrapper;
import hudson.PluginManager;
import hudson.model.UpdateCenter.UpdateCenterJob;
import hudson.lifecycle.Lifecycle;
32
import hudson.util.IOUtils;
33 34 35 36
import hudson.util.TextFile;
import hudson.util.VersionNumber;
import static hudson.util.TimeUnit2.DAYS;
import net.sf.json.JSONObject;
37
import org.kohsuke.stapler.QueryParameter;
38
import org.kohsuke.stapler.DataBoundConstructor;
39
import org.kohsuke.stapler.StaplerRequest;
40 41 42 43 44 45 46 47 48 49 50 51
import org.kohsuke.stapler.StaplerResponse;
import org.jvnet.hudson.crypto.CertificateUtil;
import org.jvnet.hudson.crypto.SignatureOutputStream;
import org.apache.commons.io.output.NullOutputStream;
import org.apache.commons.io.output.TeeOutputStream;

import java.io.File;
import java.io.IOException;
import java.io.ByteArrayInputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
K
bug fix  
Kohsuke Kawaguchi 已提交
52
import java.util.HashSet;
53 54 55
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
56
import java.util.HashMap;
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
import java.util.Set;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.DigestOutputStream;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.TrustAnchor;

import com.trilead.ssh2.crypto.Base64;

import javax.servlet.ServletContext;


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

    /**
     * When was the last time we asked a browser to check the data for us?
     *
     * <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 browseres
     * all at once.
     */
    private transient volatile long lastAttempt = -1;

    /**
     * ID string for this update source.
     */
    private final String id;

    /**
K
Kohsuke Kawaguchi 已提交
107
     * Path to <tt>update-center.json</tt>, like <tt>http://jenkins-ci.org/update-center.json</tt>.
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
     */
    private final String url;

    public UpdateSite(String id, String url) {
        this.id = id;
        this.url = url;
    }

    /**
     * When read back from XML, initialize them back to -1.
     */
    private Object readResolve() {
        dataTimestamp = lastAttempt = -1;
        return this;
    }

    /**
     * Get ID string.
     */
    public String getId() {
        return id;
    }

    public long getDataTimestamp() {
        return dataTimestamp;
    }

    /**
     * This is the endpoint that receives the update center data file from the browser.
     */
138
    public void doPostBack(StaplerRequest req, StaplerResponse rsp) throws IOException, GeneralSecurityException {
139
        dataTimestamp = System.currentTimeMillis();
140
        String json = IOUtils.toString(req.getInputStream(),"UTF-8");
141 142 143 144 145 146 147 148 149 150 151
        JSONObject o = JSONObject.fromObject(json);

        int v = o.getInt("updateCenterVersion");
        if(v !=1) {
            LOGGER.warning("Unrecognized update center version: "+v);
            return;
        }

        if (signatureCheck)
            verifySignature(o);

K
bug fix  
Kohsuke Kawaguchi 已提交
152
        LOGGER.info("Obtained the latest update center data file for UpdateSource " + id);
153
        getDataFile().write(json);
154
        rsp.setContentType("text/plain");  // So browser won't try to parse response
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    }

    /**
     * Verifies the signature in the update center data file.
     */
    private boolean verifySignature(JSONObject o) throws GeneralSecurityException, IOException {
        JSONObject signature = o.getJSONObject("signature");
        if (signature.isNullObject()) {
            LOGGER.severe("No signature block found");
            return false;
        }
        o.remove("signature");

        List<X509Certificate> certs = new ArrayList<X509Certificate>();
        {// load and verify certificates
            CertificateFactory cf = CertificateFactory.getInstance("X509");
K
bug fix  
Kohsuke Kawaguchi 已提交
171
            for (Object cert : signature.getJSONArray("certificates")) {
172 173 174 175 176
                X509Certificate c = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray())));
                c.checkValidity();
                certs.add(c);
            }

A
alanharder 已提交
177
            // all default root CAs in JVM are trusted, plus certs bundled in Jenkins
K
bug fix  
Kohsuke Kawaguchi 已提交
178
            Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); // CertificateUtil.getDefaultRootCAs();
179 180 181 182 183
            ServletContext context = Hudson.getInstance().servletContext;
            for (String cert : (Set<String>) context.getResourcePaths("/WEB-INF/update-center-rootCAs")) {
                if (cert.endsWith(".txt"))  continue;       // skip text files that are meant to be documentation
                anchors.add(new TrustAnchor((X509Certificate)cf.generateCertificate(context.getResourceAsStream(cert)),null));
            }
K
bug fix  
Kohsuke Kawaguchi 已提交
184
            CertificateUtil.validatePath(certs,anchors);
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
        }

        // this is for computing a digest to check sanity
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(),sha1);

        // this is for computing a signature
        Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initVerify(certs.get(0));
        SignatureOutputStream sos = new SignatureOutputStream(sig);

        o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(dos,sos),"UTF-8"));

        // did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n
        // (which is more likely than someone tampering with update center), we can tell
        String computedDigest = new String(Base64.encode(sha1.digest()));
        String providedDigest = signature.getString("digest");
        if (!computedDigest.equalsIgnoreCase(providedDigest)) {
            LOGGER.severe("Digest mismatch: "+computedDigest+" vs "+providedDigest);
            return false;
        }

        if (!sig.verify(Base64.decode(signature.getString("signature").toCharArray()))) {
            LOGGER.severe("Signature in the update center doesn't match with the certificate");
            return false;
        }

        return true;
    }

    /**
     * Returns true if it's time for us to check for new version.
     */
    public boolean isDue() {
        if(neverUpdate)     return false;
        if(dataTimestamp==-1)
            dataTimestamp = getDataFile().file.lastModified();
        long now = System.currentTimeMillis();
        boolean due = now - dataTimestamp > DAY && now - lastAttempt > 15000;
        if(due)     lastAttempt = now;
        return due;
    }

    /**
     * Loads the update center data, if any.
     *
     * @return  null if no data is available.
     */
    public Data getData() {
        TextFile df = getDataFile();
        if(df.exists()) {
            try {
                return new Data(JSONObject.fromObject(df.read()));
            } 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;
        }
    }
    
    /**
     * Returns a list of plugins that should be shown in the "available" tab.
     * These are "all plugins - installed plugins".
     */
    public List<Plugin> getAvailables() {
        List<Plugin> r = new ArrayList<Plugin>();
        Data data = getData();
255
        if(data==null)     return Collections.emptyList();
256 257 258 259 260 261
        for (Plugin p : data.plugins.values()) {
            if(p.getInstalled()==null)
                r.add(p);
        }
        return r;
    }
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
    /**
     * 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);
    }

    /**
     * Returns an "always up" server for Internet connectivity testing, or null if we are going to skip the test.
     */
    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(Hudson.getInstance().getRootDir(),
                                     "updates/" + getId()+".json"));
    }
    
    /**
     * Returns the list of plugins that are updates to currently installed ones.
     *
     * @return
     *      can be empty but never null.
     */
    public List<Plugin> getUpdates() {
        Data data = getData();
        if(data==null)      return Collections.emptyList(); // fail to determine
        
        List<Plugin> r = new ArrayList<Plugin>();
        for (PluginWrapper pw : Hudson.getInstance().getPluginManager().getPlugins()) {
            Plugin p = pw.getUpdateInfo();
            if(p!=null) r.add(p);
        }
        
        return r;
    }
    
    /**
     * Does any of the plugin has updates?
     */
    public boolean hasUpdates() {
        Data data = getData();
        if(data==null)      return false;
        
        for (PluginWrapper pw : Hudson.getInstance().getPluginManager().getPlugins()) {
            if(!pw.isBundled() && pw.getUpdateInfo()!=null)
                // do not advertize updates to bundled plugins, since we generally want users to get them
A
alanharder 已提交
324
                // as a part of jenkins.war updates. This also avoids unnecessary pinning of plugins. 
325 326 327 328 329 330 331 332 333 334 335 336 337 338
                return true;
        }
        return false;
    }
    
    
    /**
     * Exposed to get rid of hardcoding of the URL that serves up update-center.json
     * in Javascript.
     */
    public String getUrl() {
        return url;
    }

K
kohsuke 已提交
339 340 341 342
    /**
     * Is this the legacy default update center site?
     */
    public boolean isLegacyDefault() {
K
Kohsuke Kawaguchi 已提交
343
        return id.equals("default") && url.startsWith("http://hudson-ci.org/") || url.startsWith("http://updates.hudson-labs.org/");
K
kohsuke 已提交
344 345
    }

346 347 348 349 350 351 352 353 354 355
    /**
     * In-memory representation of the update center data.
     */
    public final class Data {
        /**
         * The {@link UpdateSite} ID.
         */
        public final String sourceId;

        /**
A
alanharder 已提交
356
         * The latest jenkins.war.
357 358 359 360 361 362 363 364
         */
        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);

        /**
A
alanharder 已提交
365
         * If this is non-null, Jenkins is going to check the connectivity to this URL to make sure
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
         * the network connection is up. Null to skip the check.
         */
        public final String connectionCheckUrl;

        Data(JSONObject o) {
            this.sourceId = (String)o.get("id");
            if (sourceId.equals("default")) {
                core = new Entry(sourceId, o.getJSONObject("core"));
            }
            else {
                core = null;
            }
            for(Map.Entry<String,JSONObject> e : (Set<Map.Entry<String,JSONObject>>)o.getJSONObject("plugins").entrySet()) {
                plugins.put(e.getKey(),new Plugin(sourceId, e.getValue()));
            }

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

        /**
         * Is there a new version of the core?
         */
        public boolean hasCoreUpdates() {
            return core != null && core.isNewerThan(Hudson.VERSION);
        }

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

    public static class Entry {
        /**
         * {@link UpdateSite} ID.
         */
        public final String sourceId;

        /**
         * Artifact ID.
         */
        public final String name;
        /**
         * The version.
         */
        public final String version;
        /**
         * Download URL.
         */
        public final String url;

        public Entry(String sourceId, JSONObject o) {
            this.sourceId = sourceId;
            this.name = o.getString("name");
            this.version = o.getString("version");
            this.url = o.getString("url");
        }

        /**
         * 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 {
437
                return new VersionNumber(currentVersion).compareTo(new VersionNumber(version)) < 0;
438 439 440 441 442
            } catch (IllegalArgumentException e) {
                // couldn't parse as the version number.
                return false;
            }
        }
443

444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
    }

    public final class Plugin extends Entry {
        /**
         * Optional URL to the Wiki page that discusses this plugin.
         */
        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
         */
        public final String title;
        /**
         * Optional excerpt string.
         */
        public final String excerpt;
        /**
         * Optional version # from which this plugin release is configuration-compatible.
         */
        public final String compatibleSinceVersion;
467
        /**
A
alanharder 已提交
468
         * Version of Jenkins core this plugin was compiled against.
469 470
         */
        public final String requiredCore;
471 472 473 474 475
        /**
         * Categories for grouping plugins, taken from labels assigned to wiki page.
         * Can be null.
         */
        public final String[] categories;
476

477 478 479 480 481
        /**
         * Dependencies of this plugin.
         */
        public final Map<String,String> dependencies = new HashMap<String,String>();
        
482 483 484 485 486 487 488
        @DataBoundConstructor
        public Plugin(String sourceId, JSONObject o) {
            super(sourceId, o);
            this.wiki = get(o,"wiki");
            this.title = get(o,"title");
            this.excerpt = get(o,"excerpt");
            this.compatibleSinceVersion = get(o,"compatibleSinceVersion");
489
            this.requiredCore = get(o,"requiredCore");
490
            this.categories = o.has("labels") ? (String[])o.getJSONArray("labels").toArray(new String[0]) : null;
491 492 493 494 495 496 497 498 499 500 501 502
            for(Object jo : o.getJSONArray("dependencies")) {
                JSONObject depObj = (JSONObject) jo;
                // Make sure there's a name attribute, that that name isn't maven-plugin - we ignore that one -
                // and that the optional value isn't true.
                if (get(depObj,"name")!=null
                    && !get(depObj,"name").equals("maven-plugin")
                    && get(depObj,"optional").equals("false")) {
                    dependencies.put(get(depObj,"name"), get(depObj,"version"));
                }
                
            }

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
        }

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

        public String getDisplayName() {
            if(title!=null) return title;
            return name;
        }

        /**
         * If some version of this plugin is currently installed, return {@link PluginWrapper}.
         * Otherwise null.
         */
        public PluginWrapper getInstalled() {
            PluginManager pm = Hudson.getInstance().getPluginManager();
            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.
         */
        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;
        }

546 547 548 549 550 551
        /**
         * Returns a list of dependent plugins which need to be installed or upgraded for this plugin to work.
         */
        public List<Plugin> getNeededDependencies() {
            List<Plugin> deps = new ArrayList<Plugin>();

552
            for(Map.Entry<String,String> e : dependencies.entrySet()) {
553
                Plugin depPlugin = Hudson.getInstance().getUpdateCenter().getPlugin(e.getKey());
554
                VersionNumber requiredVersion = new VersionNumber(e.getValue());
555 556
                
                // Is the plugin installed already? If not, add it.
557 558 559
                PluginWrapper current = depPlugin.getInstalled();

                if (current ==null) {
560 561 562 563
                    deps.add(depPlugin);
                }
                // If the dependency plugin is installed, is the version we depend on newer than
                // what's installed? If so, upgrade.
564
                else if (current.isOlderThan(requiredVersion)) {
565 566 567 568 569 570 571
                    deps.add(depPlugin);
                }
            }

            return deps;
        }
        
572
        public boolean isForNewerHudson() {
573 574
            try {
                return requiredCore!=null && new VersionNumber(requiredCore).isNewerThan(
575
                  new VersionNumber(Hudson.VERSION.replaceFirst("SHOT *\\(private.*\\)", "SHOT")));
576 577 578
            } catch (NumberFormatException nfe) {
                return true;  // If unable to parse version
            }
579 580
        }

581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
        /**
         * @deprecated as of 1.326
         *      Use {@link #deploy()}.
         */
        public void install() {
            deploy();
        }

        /**
         * 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.
         */
        public Future<UpdateCenterJob> deploy() {
            Hudson.getInstance().checkPermission(Hudson.ADMINISTER);
            UpdateCenter uc = Hudson.getInstance().getUpdateCenter();
599 600 601 602
            for (Plugin dep : getNeededDependencies()) {
                LOGGER.log(Level.WARNING, "Adding dependent install of " + dep.name + " for plugin " + name);
                dep.deploy();
            }
603 604 605
            return uc.addJob(uc.new InstallationJob(this, UpdateSite.this, Hudson.getAuthentication()));
        }

606 607 608 609 610 611 612 613
        /**
         * Schedules the downgrade of this plugin.
         */
        public Future<UpdateCenterJob> deployBackup() {
            Hudson.getInstance().checkPermission(Hudson.ADMINISTER);
            UpdateCenter uc = Hudson.getInstance().getUpdateCenter();
            return uc.addJob(uc.new PluginDowngradeJob(this, UpdateSite.this, Hudson.getAuthentication()));
        }
614 615 616 617 618 619 620
        /**
         * Making the installation web bound.
         */
        public void doInstall(StaplerResponse rsp) throws IOException {
            deploy();
            rsp.sendRedirect2("../..");
        }
621 622 623 624 625 626

        /**
         * Performs the downgrade of the plugin.
         */
        public void doDowngrade(StaplerResponse rsp) throws IOException {
            deployBackup();
627
            rsp.sendRedirect2("../..");
628
        }
629 630 631 632 633 634
    }

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

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

635
    // The name uses UpdateCenter for compatibility reason.
636
    public static boolean neverUpdate = Boolean.getBoolean(UpdateCenter.class.getName()+".never");
637 638 639 640 641 642

    /**
     * Off by default until we know this is reasonably working.
     */
    public static boolean signatureCheck = Boolean.getBoolean(UpdateCenter.class.getName()+".signatureCheck");
}