LinkCheckerImpl.java 17.1 KB
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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.text.Text
 *  javax.jcr.RepositoryException
 *  javax.servlet.http.HttpServletRequest
 *  org.apache.felix.scr.annotations.Activate
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Deactivate
 *  org.apache.felix.scr.annotations.Properties
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.ReferenceCardinality
 *  org.apache.felix.scr.annotations.ReferencePolicy
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.sling.api.SlingException
 *  org.apache.sling.api.SlingHttpServletRequest
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceUtil
 *  org.osgi.framework.ServiceReference
 *  org.osgi.service.component.ComponentContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.rewriter.linkchecker.impl;

import com.day.cq.rewriter.linkchecker.Link;
import com.day.cq.rewriter.linkchecker.LinkChecker;
import com.day.cq.rewriter.linkchecker.LinkCheckerExtension;
import com.day.cq.rewriter.linkchecker.LinkCheckerSettings;
import com.day.cq.rewriter.linkchecker.LinkCheckerSettingsProvider;
import com.day.cq.rewriter.linkchecker.LinkInfo;
import com.day.cq.rewriter.linkchecker.LinkInfoStorage;
import com.day.cq.rewriter.linkchecker.LinkRewriteConfig;
import com.day.cq.rewriter.linkchecker.LinkValidity;
import com.day.cq.rewriter.linkchecker.impl.ExtensionList;
import com.day.cq.rewriter.linkchecker.impl.LinkImpl;
import com.day.text.Text;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.jcr.RepositoryException;
import javax.servlet.http.HttpServletRequest;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingException;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceUtil;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(label="%service.name", description="%service.description", metatype=1)
@Properties(value={@Property(name="service.description", value={"LinkChecker Service"}), @Property(name="scheduler.period", longValue={5}), @Property(name="scheduler.concurrent", boolValue={0})})
@Reference(name="extension", cardinality=ReferenceCardinality.OPTIONAL_MULTIPLE, policy=ReferencePolicy.DYNAMIC, referenceInterface=LinkCheckerExtension.class)
@Service(value={Runnable.class, LinkChecker.class})
public class LinkCheckerImpl
implements LinkChecker,
Runnable {
    private final Logger logger;
    @Property(intValue={48})
    private static final String BAD_LINK_TOLERANCE_INTERVAL = "service.bad_link_tolerance_interval";
    @Property(value={"^system/"}, cardinality=Integer.MAX_VALUE)
    private static final String CHECK_OVERRIDE_PATTERNS = "service.check_override_patterns";
    @Property(boolValue={0})
    private static final String CACHE_BROKEN_INTERNAL_LINKS = "service.cache_broken_internal_links";
    @Property(value={"javascript:", "mailto:", "#", "<!--", "${"}, cardinality=Integer.MAX_VALUE)
    private static final String SPECIAL_LINK_PREFIX = "service.special_link_prefix";
    @Property(cardinality=Integer.MAX_VALUE)
    private static final String SPECIAL_LINK_PATTERNS = "service.special_link_patterns";
    protected static final LinkRewriteConfig DEFAULT_CONFIG = new LinkRewriteConfig(true, "", "");
    @Reference
    protected LinkInfoStorage storage;
    @Reference(cardinality=ReferenceCardinality.OPTIONAL_UNARY, policy=ReferencePolicy.DYNAMIC)
    protected volatile LinkCheckerSettingsProvider settingsProvider;
    private int badLinkToleranceInterval;
    private List<Pattern> checkOverridePatterns;
    protected ExtensionList extensionList;
    private List<ServiceReference> delayedExtensionList;
    private final Set<String> brokenInternalLinkCache;
    private boolean cacheBrokenInternalLinks;
    private String[] specialLinkPrefix;
    private List<Pattern> specialLinkPatterns;

    public LinkCheckerImpl() {
        this.logger = LoggerFactory.getLogger(this.getClass());
        this.checkOverridePatterns = new LinkedList<Pattern>();
        this.delayedExtensionList = new LinkedList<ServiceReference>();
        this.brokenInternalLinkCache = Collections.synchronizedSet(new HashSet());
        this.cacheBrokenInternalLinks = false;
        this.specialLinkPrefix = new String[0];
        this.specialLinkPatterns = new LinkedList<Pattern>();
    }

    @Override
    public void run() {
        this.brokenInternalLinkCache.clear();
    }

    LinkImpl parseLink(String href, LinkCheckerSettings settings) {
        LinkImpl link = new LinkImpl(href, this.isSpecial(href));
        if (link.isSpecial()) {
            return link;
        }
        try {
            URI context;
            URI uri;
            int pos = href.indexOf(35);
            String fragment = null;
            if (pos > 0) {
                fragment = href.substring(pos + 1);
                href = href.substring(0, pos);
            }
            try {
                uri = new URI(href);
            }
            catch (URISyntaxException e) {
                if (href.startsWith("/")) {
                    this.logger.debug("auto escaping invalid uri: " + e.getMessage());
                    uri = new URI(Text.escape((String)href, (char)'%', (boolean)true));
                }
                throw e;
            }
            boolean isAbsolute = uri.isAbsolute();
            if (fragment != null) {
                uri = new URI(uri.getScheme(), uri.getSchemeSpecificPart(), fragment);
            }
            link.setUri(uri);
            URI base = settings.getBaseURI();
            if (base != null) {
                uri = base.resolve(uri);
            }
            if (!isAbsolute && (context = settings.getContextURI()) != null) {
                uri = context.relativize(uri);
            }
            link.setRelUri(uri);
        }
        catch (URISyntaxException e) {
            this.logger.warn("Ignoring malformed URI: {}", (Object)e.toString());
        }
        return link;
    }

    @Override
    public LinkValidity getLinkValidity(String url, LinkCheckerSettings settings) {
        return this.getLink(url, settings).getValidity();
    }

    @Override
    public Link getLink(String href, LinkCheckerSettings settings) {
        LinkImpl link = this.parseLink(href, settings);
        URI uri = link.getRelUri();
        if (link.isSpecial()) {
            return link.setValidity(LinkValidity.VALID);
        }
        if (uri == null) {
            return link.setValidity(LinkValidity.INVALID);
        }
        if (this.matchesCheckOverridePatterns(link.getUri())) {
            return link.setValidity(LinkValidity.VALID);
        }
        if (uri.isAbsolute()) {
            LinkValidity validity;
            if (settings.isIgnoreExternals()) {
                return link.setValidity(LinkValidity.VALID);
            }
            LinkInfo info = this.storage.getLinkInfo(uri.toString());
            if (info == null) {
                info = new LinkInfo(uri.toString());
                validity = LinkValidity.PENDING;
            } else if (info.getLastChecked() == null) {
                validity = LinkValidity.PENDING;
            } else if (info.isValid()) {
                validity = LinkValidity.VALID;
            } else if (info.getLastAvailable() == null) {
                validity = LinkValidity.INVALID;
            } else {
                Calendar threshold = Calendar.getInstance();
                threshold.add(10, - this.badLinkToleranceInterval);
                validity = info.getLastAvailable().after(threshold) ? LinkValidity.VALID : LinkValidity.INVALID;
            }
            if (!uri.getScheme().equals("http")) {
                validity = LinkValidity.VALID;
            }
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("External link {} -> {} is " + (Object)((Object)validity), (Object)settings.getRequestURI(), (Object)uri);
            }
            info.setLastAccessed(Calendar.getInstance());
            info.addReferrer(settings.getRequest().getPathInfo());
            this.storage.putLinkInfo(info);
            return link.setValidity(validity);
        }
        if (uri.getPath() == null) {
            return link.setValidity(LinkValidity.VALID);
        }
        if (uri.getPath().startsWith("/")) {
            return link.setValidity(LinkValidity.VALID);
        }
        link.setContextRelative(true);
        if (settings.isIgnoreInternals()) {
            return link.setValidity(LinkValidity.VALID);
        }
        String path = "/" + uri.getPath();
        try {
            ResourceResolver resolver = settings.getResourceResolver();
            String key = settings.getRequest().getRemoteUser() + path;
            if (this.cacheBrokenInternalLinks && this.brokenInternalLinkCache.contains(key)) {
                return link.setValidity(LinkValidity.INVALID);
            }
            Resource resource = resolver.resolve((HttpServletRequest)settings.getRequest(), path);
            if (resource == null || ResourceUtil.isNonExistingResource((Resource)resource)) {
                if (this.cacheBrokenInternalLinks) {
                    this.brokenInternalLinkCache.add(key);
                }
                return link.setValidity(LinkValidity.INVALID);
            }
            for (LinkCheckerExtension extension : this.extensionList.getExtensions()) {
                LinkValidity validity = extension.getLinkValidity(resource);
                if (validity == LinkValidity.VALID) continue;
                return link.setValidity(validity);
            }
            return link.setValidity(LinkValidity.VALID);
        }
        catch (SlingException e) {
            this.logger.warn("Error during link checking: " + path, (Throwable)e);
            return link.setValidity(LinkValidity.INVALID);
        }
    }

    private boolean matchesCheckOverridePatterns(URI uri) {
        String link = uri.toString();
        for (Pattern pattern : this.checkOverridePatterns) {
            if (!pattern.matcher(link).find()) continue;
            return true;
        }
        return false;
    }

    @Override
    public LinkCheckerSettings createSettings(SlingHttpServletRequest request) {
        LinkCheckerSettings settings = LinkCheckerSettings.fromRequest(request);
        if (settings.getRequest() != null) {
            return settings;
        }
        settings.init(request);
        LinkCheckerSettings config = null;
        LinkCheckerSettingsProvider provider = this.settingsProvider;
        if (provider != null) {
            config = provider.createSettings(request);
        }
        if (config == null) {
            config = new LinkCheckerSettings();
            config.setExpiredConfig(DEFAULT_CONFIG);
            config.setInvalidConfig(DEFAULT_CONFIG);
            config.setPredatedConfig(DEFAULT_CONFIG);
        }
        if (settings.getInvalidConfig() == null) {
            settings.setInvalidConfig(config.getInvalidConfig());
        }
        if (settings.getExpiredConfig() == null) {
            settings.setExpiredConfig(config.getExpiredConfig());
        }
        if (settings.getPredatedConfig() == null) {
            settings.setPredatedConfig(config.getPredatedConfig());
        }
        return settings;
    }

    @Override
    public boolean isSpecial(String url) {
        if (url == null) {
            return true;
        }
        String urlLower = url.toLowerCase();
        for (String prefix : this.specialLinkPrefix) {
            if (!urlLower.startsWith(prefix)) continue;
            return true;
        }
        for (Pattern p : this.specialLinkPatterns) {
            if (!p.matcher(urlLower).find()) continue;
            return true;
        }
        return false;
    }

    private String[] getFilteredList(Dictionary<String, Object> props, String propName, boolean lowercase) {
        Object prop = props.get(propName);
        ArrayList<String> filteredList = new ArrayList<String>();
        if (prop != null) {
            String[] list;
            for (String item : list = prop instanceof String[] ? (String[])prop : prop.toString().split("\\s+")) {
                if (item == null || item.trim().length() <= 0) continue;
                if (lowercase) {
                    item = item.toLowerCase();
                }
                filteredList.add(item);
            }
        }
        return filteredList.toArray(new String[filteredList.size()]);
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Activate
    protected void activate(ComponentContext context) throws RepositoryException {
        Dictionary props = context.getProperties();
        this.badLinkToleranceInterval = Integer.valueOf(props.get("service.bad_link_tolerance_interval").toString());
        String[] patterns = this.getFilteredList(props, "service.check_override_patterns", false);
        this.checkOverridePatterns.clear();
        for (String pattern2 : patterns) {
            try {
                this.checkOverridePatterns.add(Pattern.compile(pattern2));
                continue;
            }
            catch (PatternSyntaxException e) {
                this.logger.warn("Invalid link check override pattern: {}", (Object)pattern2);
            }
        }
        this.cacheBrokenInternalLinks = (Boolean)props.get("service.cache_broken_internal_links");
        this.specialLinkPrefix = this.getFilteredList(props, "service.special_link_prefix", true);
        patterns = this.getFilteredList(props, "service.special_link_patterns", false);
        this.specialLinkPatterns.clear();
        for (String pattern2 : patterns) {
            try {
                this.specialLinkPatterns.add(Pattern.compile(pattern2, 2));
                continue;
            }
            catch (PatternSyntaxException e) {
                this.logger.warn("Invalid special link pattern: {}", (Object)pattern2);
            }
        }
        LinkCheckerImpl arr$ = this;
        synchronized (arr$) {
            this.extensionList = new ExtensionList(context);
            for (ServiceReference ref : this.delayedExtensionList) {
                this.extensionList.addExtension(ref);
            }
            this.delayedExtensionList.clear();
        }
        this.logger.debug("LinkChecker service activated");
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Deactivate
    protected void deactivate(ComponentContext componentContext) {
        this.logger.debug("LinkChecker service shut down");
        LinkCheckerImpl linkCheckerImpl = this;
        synchronized (linkCheckerImpl) {
            this.extensionList = null;
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    protected void bindExtension(ServiceReference ref) {
        LinkCheckerImpl linkCheckerImpl = this;
        synchronized (linkCheckerImpl) {
            if (this.extensionList == null) {
                this.delayedExtensionList.add(ref);
            } else {
                this.extensionList.addExtension(ref);
            }
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    protected void unbindExtension(ServiceReference ref) {
        LinkCheckerImpl linkCheckerImpl = this;
        synchronized (linkCheckerImpl) {
            if (this.extensionList != null) {
                this.extensionList.removeExtension(ref);
            }
            this.delayedExtensionList.remove((Object)ref);
        }
    }

    protected void bindStorage(LinkInfoStorage linkInfoStorage) {
        this.storage = linkInfoStorage;
    }

    protected void unbindStorage(LinkInfoStorage linkInfoStorage) {
        if (this.storage == linkInfoStorage) {
            this.storage = null;
        }
    }

    protected void bindSettingsProvider(LinkCheckerSettingsProvider linkCheckerSettingsProvider) {
        this.settingsProvider = linkCheckerSettingsProvider;
    }

    protected void unbindSettingsProvider(LinkCheckerSettingsProvider linkCheckerSettingsProvider) {
        if (this.settingsProvider == linkCheckerSettingsProvider) {
            this.settingsProvider = null;
        }
    }
}