Rewriter.java 23 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 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.rewriter.htmlparser.AttributeList
 *  com.day.cq.rewriter.htmlparser.DocumentHandler
 *  com.day.cq.rewriter.htmlparser.HtmlParser
 *  com.day.text.Text
 *  javax.servlet.ServletOutputStream
 *  javax.servlet.http.HttpServletRequest
 *  javax.servlet.http.HttpServletResponse
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.http.Header
 *  org.apache.http.HttpEntity
 *  org.apache.http.HttpHost
 *  org.apache.http.HttpRequest
 *  org.apache.http.HttpResponse
 *  org.apache.http.StatusLine
 *  org.apache.http.client.config.RequestConfig
 *  org.apache.http.client.config.RequestConfig$Builder
 *  org.apache.http.client.entity.UrlEncodedFormEntity
 *  org.apache.http.client.methods.HttpGet
 *  org.apache.http.client.methods.HttpPost
 *  org.apache.http.config.SocketConfig
 *  org.apache.http.config.SocketConfig$Builder
 *  org.apache.http.entity.mime.MultipartEntityBuilder
 *  org.apache.http.impl.client.CloseableHttpClient
 *  org.apache.http.impl.client.HttpClientBuilder
 *  org.apache.http.impl.client.HttpClients
 *  org.apache.http.message.BasicNameValuePair
 *  org.apache.http.osgi.services.HttpClientBuilderFactory
 *  org.apache.http.protocol.BasicHttpContext
 *  org.apache.http.protocol.HttpContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.wcm.foundation.impl;

import com.day.cq.rewriter.htmlparser.AttributeList;
import com.day.cq.rewriter.htmlparser.DocumentHandler;
import com.day.cq.rewriter.htmlparser.HtmlParser;
import com.day.cq.wcm.foundation.External;
import com.day.cq.wcm.foundation.impl.EncodingScanner;
import com.day.text.Text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.PushbackInputStream;
import java.io.Reader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.felix.scr.annotations.Reference;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.SocketConfig;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.osgi.services.HttpClientBuilderFactory;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Rewriter
implements DocumentHandler {
    private static final Logger log = LoggerFactory.getLogger(Rewriter.class);
    @Reference
    private HttpClientBuilderFactory httpClientBuilderFactory;
    private final String pagePath;
    private final String resourcePath;
    private final String target;
    private final String targetParamName;
    private External.Limit limit = External.Limit.NO;
    private String identifier;
    private URI targetURL;
    private PrintWriter writer;
    private boolean respectTypeAttribute;
    private String hostPrefix;
    private Map<String, String> extraParams = new HashMap<String, String>();
    private boolean passInput;
    private int soTimeout = 60000;
    private int connectionTimeout = 5000;
    protected final String postSelector;

    public Rewriter(String pagePath, String resourcePath, String target, String postSelector, String targetParamName) {
        this.pagePath = pagePath;
        this.resourcePath = resourcePath;
        this.target = target;
        this.postSelector = postSelector;
        this.targetParamName = targetParamName;
    }

    public void setPassInput(boolean passInput) {
        this.passInput = passInput;
    }

    public void addExtraParameter(String name, String value) {
        this.extraParams.put(name, value);
    }

    public void setLimit(External.Limit limit) {
        this.limit = limit;
    }

    public void setRespectTypeAttribute(boolean respectTypeAttribute) {
        this.respectTypeAttribute = respectTypeAttribute;
    }

    public void setIdentifier(String identifier) {
        this.identifier = identifier;
    }

    private void setWriter(PrintWriter writer) {
        this.writer = writer;
    }

    public void setSoTimeout(int soTimeout) {
        this.soTimeout = soTimeout;
    }

    public void setConnectionTimeout(int connectionTimeout) {
        this.connectionTimeout = connectionTimeout;
    }

    public void onStart() throws IOException {
    }

    public void onStartElement(String name, AttributeList attList, char[] ch, int off, int len, boolean endSlash) {
        String suffix = null;
        String upperName = name.toUpperCase();
        if (this.limit != External.Limit.OFF) {
            if (upperName.equals("A")) {
                this.rewriteARef(attList);
            } else if (upperName.equals("AREA")) {
                this.rewriteRef(attList, "HREF", false);
            } else if (upperName.equals("BASE")) {
                this.rewriteBase(attList);
            } else if (upperName.equals("FORM")) {
                suffix = this.rewriteForm(attList);
            } else if (upperName.equals("FRAME")) {
                this.rewriteRef(attList, "SRC", true);
            } else if (upperName.equals("IFRAME")) {
                this.rewriteRef(attList, "SRC", true);
            } else if (upperName.equals("IMG")) {
                this.rewriteRef(attList, "SRC", true);
            } else if (upperName.equals("INPUT")) {
                this.rewriteRef(attList, "SRC", true);
            } else if (upperName.equals("LINK")) {
                this.rewriteRef(attList, "HREF", true);
            } else if (upperName.equals("SCRIPT")) {
                this.rewriteRef(attList, "SRC", true);
            } else if (upperName.equals("TABLE")) {
                this.rewriteRef(attList, "BACKGROUND", true);
            } else if (upperName.equals("TD")) {
                this.rewriteRef(attList, "BACKGROUND", true);
            } else if (upperName.equals("TR")) {
                this.rewriteRef(attList, "BACKGROUND", true);
            }
        }
        if (attList.isModified()) {
            this.writer.write(this.serialize(name, attList, endSlash));
        } else {
            this.writer.write(ch, off, len);
        }
        if (suffix != null) {
            this.writer.write(suffix);
        }
    }

    private void rewriteARef(AttributeList attList) {
        String protocol;
        String href = attList.getValue("href");
        if (href == null) {
            return;
        }
        int sep = href.indexOf(58);
        if (sep != -1 && ((protocol = href.substring(0, sep)).equals("mailto") || protocol.equals("javascript") || protocol.equals("ftp"))) {
            return;
        }
        boolean hasType = this.respectTypeAttribute && attList.containsAttribute("type");
        boolean blankTarget = "_blank".equals(attList.getValue("target"));
        this.rewriteRef(attList, "HREF", hasType || blankTarget);
    }

    private String serialize(String name, AttributeList attList, boolean endSlash) {
        StringBuffer buffer = new StringBuffer(256);
        buffer.append("<");
        buffer.append(name);
        Iterator attNames = attList.attributeNames();
        while (attNames.hasNext()) {
            String attName = (String)attNames.next();
            String attValue = attList.getQuotedValue(attName);
            buffer.append(" ");
            buffer.append(attName);
            if (attValue == null) continue;
            buffer.append('=');
            buffer.append(attValue);
        }
        if (endSlash) {
            buffer.append(" /");
        }
        buffer.append(">");
        return buffer.toString();
    }

    public void characters(char[] ch, int off, int len) throws IOException {
        this.writer.write(ch, off, len);
    }

    public void onEndElement(String name, char[] ch, int off, int len) {
        this.writer.write(ch, off, len);
    }

    public void onEnd() throws IOException {
    }

    private String getAbsoluteURL(String relativeURI) {
        if (relativeURI.startsWith("http:") || relativeURI.startsWith("https:")) {
            return relativeURI;
        }
        StringBuffer result = new StringBuffer(256);
        result.append(this.targetURL.getScheme());
        result.append("://");
        result.append(this.targetURL.getHost());
        if (this.targetURL.getPort() != -1) {
            result.append(':');
            result.append(Integer.toString(this.targetURL.getPort()));
        }
        if (relativeURI.startsWith("/")) {
            result.append(relativeURI);
        } else {
            String targetURI = this.targetURL.getPath();
            int lastSep = targetURI.lastIndexOf(47);
            targetURI = lastSep != -1 ? targetURI.substring(0, targetURI.lastIndexOf(47) + 1) : "/";
            result.append(targetURI);
            result.append(relativeURI);
        }
        return result.toString();
    }

    private void rewriteBase(AttributeList attList) {
        String href = attList.getValue("HREF");
        if (href != null && (this.limit != External.Limit.HOST || this.sameHost(href))) {
            try {
                this.targetURL = new URI(href);
            }
            catch (URISyntaxException e) {
                // empty catch block
            }
            attList.setValue("HREF", "");
        }
    }

    private String rewriteForm(AttributeList attList) {
        String action = attList.getValue("ACTION");
        if (action != null && (this.limit != External.Limit.HOST || this.sameHost(action))) {
            action = this.getAbsoluteURL(action);
            String formSelector = "";
            String method = attList.getValue("METHOD");
            if (method != null) {
                method = method.toUpperCase();
                attList.setValue("METHOD", method);
            }
            if ("POST".equals(method)) {
                formSelector = "." + this.postSelector;
            }
            attList.setValue("ACTION", this.pagePath + formSelector + ".html");
            StringBuffer hidden = new StringBuffer();
            hidden.append("<input type=\"hidden\" name=\"");
            hidden.append(this.targetParamName);
            if (this.identifier != null) {
                hidden.append('_');
                hidden.append(this.identifier);
            }
            hidden.append("\" value=\"");
            hidden.append(action);
            hidden.append("\">");
            return hidden.toString();
        }
        return null;
    }

    private void rewriteRef(AttributeList attList, String attName, boolean appendSelector) {
        String ref = attList.getValue(attName);
        if (ref != null && (this.limit != External.Limit.HOST || this.sameHost(ref))) {
            attList.setValue(attName, this.rewriteURL(ref, appendSelector));
        }
    }

    private String rewriteURL(String url, boolean appendSelector) {
        StringBuffer newValue = new StringBuffer();
        if (appendSelector) {
            newValue.append(this.resourcePath);
            newValue.append("?");
        } else {
            newValue.append(this.pagePath);
            newValue.append(".html?");
        }
        newValue.append(this.targetParamName);
        if (!appendSelector && this.identifier != null) {
            newValue.append('_');
            newValue.append(this.identifier);
        }
        newValue.append('=');
        newValue.append(URLEncoder.encode(this.getAbsoluteURL(url)));
        return newValue.toString();
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void rewriteHtml(InputStream in, String contentType, HttpServletResponse response) throws IOException {
        String encoding = "8859_1";
        int charsetIndex = contentType.indexOf("charset=");
        if (charsetIndex != -1) {
            encoding = contentType.substring(charsetIndex + "charset=".length()).trim();
        } else {
            byte[] buf = new byte[2048];
            int len = this.fillBuffer(in, buf);
            String scanned = EncodingScanner.scan(buf, 0, len);
            if (scanned != null) {
                encoding = scanned;
                contentType = contentType + "; charset=" + encoding;
            }
            PushbackInputStream pb = new PushbackInputStream(in, buf.length);
            pb.unread(buf, 0, len);
            in = pb;
        }
        response.setContentType(contentType);
        PrintWriter writer = response.getWriter();
        this.setWriter(writer);
        HashSet<String> inclusionSet = new HashSet<String>();
        inclusionSet.add("A");
        inclusionSet.add("AREA");
        inclusionSet.add("BASE");
        inclusionSet.add("FORM");
        inclusionSet.add("FRAME");
        inclusionSet.add("IFRAME");
        inclusionSet.add("IMG");
        inclusionSet.add("INPUT");
        inclusionSet.add("LINK");
        inclusionSet.add("SCRIPT");
        inclusionSet.add("TABLE");
        inclusionSet.add("TD");
        inclusionSet.add("TR");
        inclusionSet.add("NOREWRITE");
        HtmlParser parser = new HtmlParser();
        parser.setTagInclusionSet(inclusionSet);
        parser.setDocumentHandler((DocumentHandler)this);
        BufferedReader reader = null;
        try {
            int len;
            reader = new BufferedReader(new InputStreamReader(in, encoding));
            char[] buf = new char[2048];
            while ((len = reader.read(buf)) != -1) {
                parser.update(buf, 0, len);
            }
            parser.finished();
        }
        finally {
            if (reader != null) {
                reader.close();
            }
        }
    }

    private int fillBuffer(InputStream in, byte[] buf) throws IOException {
        int chunk;
        int total;
        for (total = 0; total < buf.length && (chunk = in.read(buf, total, buf.length - total)) > 0; total += chunk) {
        }
        return total;
    }

    private void setHostPrefix(URI uri) {
        StringBuffer buf = new StringBuffer();
        buf.append(uri.getScheme());
        buf.append("://");
        buf.append(uri.getHost());
        int port = uri.getPort();
        if (port != -1) {
            buf.append(':');
            buf.append(String.valueOf(port));
        }
        buf.append('/');
        this.hostPrefix = buf.toString();
    }

    private boolean sameHost(String ref) {
        if (!ref.startsWith("http:") && !ref.startsWith("https:")) {
            return true;
        }
        return ref.startsWith(this.hostPrefix);
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public void rewrite(HttpServletRequest request, HttpServletResponse response) throws IOException {
        CloseableHttpClient httpClient;
        String contentType;
        HttpPost httpMethod;
        try {
            this.targetURL = new URI(this.target);
        }
        catch (URISyntaxException e) {
            IOException ioe = new IOException("Bad URI syntax: " + this.target);
            ioe.initCause(e);
            throw ioe;
        }
        this.setHostPrefix(this.targetURL);
        RequestConfig rc = RequestConfig.custom().setConnectTimeout(this.connectionTimeout).build();
        SocketConfig sc = SocketConfig.custom().setSoTimeout(this.soTimeout).build();
        BasicHttpContext httpContext = new BasicHttpContext();
        HttpHost httpHost = new HttpHost(this.targetURL.getHost(), this.targetURL.getPort(), this.targetURL.getScheme());
        String method = (String)request.getAttribute("cq.ext.app.method");
        if (method == null) {
            method = request.getMethod();
        }
        method = method.toUpperCase();
        boolean isPost = "POST".equals(method);
        String urlString = this.targetURL.getPath();
        StringBuffer query = new StringBuffer();
        if (this.targetURL.getQuery() != null) {
            query.append("?");
            query.append(this.targetURL.getQuery());
        }
        if ("GET".equals(method)) {
            httpClient = this.httpClientBuilderFactory != null && this.httpClientBuilderFactory.newBuilder() != null ? this.httpClientBuilderFactory.newBuilder().setDefaultRequestConfig(rc).setDefaultSocketConfig(sc).build() : HttpClients.custom().setDefaultRequestConfig(rc).setDefaultSocketConfig(sc).build();
            for (String name : this.extraParams.keySet()) {
                String value = this.extraParams.get(name);
                if (query.length() == 0) {
                    query.append("?");
                } else {
                    query.append("&");
                }
                query.append(Text.escape((String)name));
                query.append("=");
                query.append(Text.escape((String)value));
            }
            if (this.passInput) {
                Enumeration e = request.getParameterNames();
                while (e.hasMoreElements()) {
                    String name2 = (String)e.nextElement();
                    if (this.targetParamName.equals(name2)) continue;
                    String[] values = request.getParameterValues(name2);
                    for (int i = 0; i < values.length; ++i) {
                        if (query.length() == 0) {
                            query.append("?");
                        } else {
                            query.append("&");
                        }
                        query.append(Text.escape((String)name2));
                        query.append("=");
                        query.append(Text.escape((String)values[i]));
                    }
                }
            }
            httpMethod = new HttpGet(urlString + query);
        } else if ("POST".equals(method)) {
            boolean mp;
            HttpPost m;
            httpClient = this.httpClientBuilderFactory != null && this.httpClientBuilderFactory.newBuilder() != null ? this.httpClientBuilderFactory.newBuilder().setDefaultRequestConfig(rc).setDefaultSocketConfig(sc).disableRedirectHandling().build() : HttpClients.custom().setDefaultRequestConfig(rc).setDefaultSocketConfig(sc).disableRedirectHandling().build();
            httpMethod = m = new HttpPost(urlString + query);
            contentType = request.getContentType();
            boolean bl = mp = contentType != null && contentType.toLowerCase().startsWith("multipart/");
            if (mp) {
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                for (String name4 : this.extraParams.keySet()) {
                    String value = this.extraParams.get(name4);
                    builder.addTextBody(name4, value);
                }
                if (this.passInput) {
                    Enumeration e = request.getParameterNames();
                    while (e.hasMoreElements()) {
                        String name3 = (String)e.nextElement();
                        if (this.targetParamName.equals(name3)) continue;
                        String[] values = request.getParameterValues(name3);
                        for (int i = 0; i < values.length; ++i) {
                            builder.addTextBody(name3, values[i]);
                        }
                    }
                }
                HttpEntity multipart = builder.build();
                m.setEntity(multipart);
            } else {
                for (String name : this.extraParams.keySet()) {
                    String value = this.extraParams.get(name);
                    List<BasicNameValuePair> nvps = Collections.singletonList(new BasicNameValuePair(name, value));
                    m.setEntity((HttpEntity)new UrlEncodedFormEntity(nvps));
                }
                if (this.passInput) {
                    Enumeration e = request.getParameterNames();
                    while (e.hasMoreElements()) {
                        String name4;
                        name4 = (String)e.nextElement();
                        if (this.targetParamName.equals(name4)) continue;
                        String[] values = request.getParameterValues(name4);
                        for (int i = 0; i < values.length; ++i) {
                            List<BasicNameValuePair> nvps = Collections.singletonList(new BasicNameValuePair(name4, values[i]));
                            m.setEntity((HttpEntity)new UrlEncodedFormEntity(nvps));
                        }
                    }
                }
            }
        } else {
            log.error("Unsupported method ''{}''", (Object)method);
            throw new IOException("Unsupported http method " + method);
        }
        log.debug("created http connection for method {} to {}", (Object)method, (Object)(urlString + query));
        httpMethod.addHeader("User-Agent", request.getHeader("User-Agent"));
        HttpResponse httpResp = httpClient.execute(httpHost, (HttpRequest)httpMethod, (HttpContext)httpContext);
        contentType = null;
        if (httpResp.getFirstHeader("Content-Type").getValue() != null) {
            contentType = httpResp.getFirstHeader("Content-Type").getValue();
        }
        log.debug("External app responded: {}", (Object)httpResp.getStatusLine());
        log.debug("External app contenttype: {}", (Object)contentType);
        int statusCode = httpResp.getStatusLine().getStatusCode();
        if (statusCode >= 400) {
            PrintWriter writer = response.getWriter();
            writer.println("External application returned status code: " + statusCode);
            return;
        }
        if (statusCode == 302 || statusCode == 301) {
            String location = httpResp.getFirstHeader("Location").getValue();
            if (location == null) {
                response.sendError(404);
                return;
            }
            response.sendRedirect(this.rewriteURL(location, false));
            return;
        }
        InputStream in = httpResp.getEntity().getContent();
        if (contentType != null && contentType.startsWith("text/html")) {
            this.rewriteHtml(in, contentType, response);
        } else {
            if (contentType != null) {
                response.setContentType(contentType);
            }
            ServletOutputStream outs = response.getOutputStream();
            try {
                int len;
                byte[] buf = new byte[8192];
                while ((len = in.read(buf)) != -1) {
                    outs.write(buf, 0, len);
                }
            }
            finally {
                if (in != null) {
                    in.close();
                }
            }
        }
    }
}