PackageShareImpl.java 15.7 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.license.License
 *  com.adobe.granite.license.ProductInfoService
 *  com.day.jcr.vault.packaging.JcrPackage
 *  com.day.jcr.vault.packaging.JcrPackageDefinition
 *  com.day.jcr.vault.packaging.JcrPackageManager
 *  com.day.jcr.vault.packaging.PackageId
 *  com.day.jcr.vault.packaging.PackagingService
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.servlet.http.Cookie
 *  javax.servlet.http.HttpServletRequest
 *  javax.servlet.http.HttpServletResponse
 *  org.apache.felix.scr.annotations.Activate
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Deactivate
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.http.Header
 *  org.apache.http.HttpHost
 *  org.apache.http.StatusLine
 *  org.apache.http.auth.Credentials
 *  org.apache.http.auth.UsernamePasswordCredentials
 *  org.apache.http.client.config.RequestConfig
 *  org.apache.http.client.config.RequestConfig$Builder
 *  org.apache.http.client.methods.CloseableHttpResponse
 *  org.apache.http.client.methods.HttpGet
 *  org.apache.http.client.methods.HttpUriRequest
 *  org.apache.http.client.protocol.HttpClientContext
 *  org.apache.http.client.utils.URIUtils
 *  org.apache.http.conn.HttpClientConnectionManager
 *  org.apache.http.impl.client.CloseableHttpClient
 *  org.apache.http.impl.client.HttpClientBuilder
 *  org.apache.http.impl.conn.PoolingHttpClientConnectionManager
 *  org.apache.http.message.BasicHeader
 *  org.apache.http.osgi.services.HttpClientBuilderFactory
 *  org.apache.http.protocol.HttpContext
 *  org.apache.jackrabbit.util.Text
 *  org.apache.sling.commons.json.JSONException
 *  org.apache.sling.commons.json.JSONObject
 *  org.osgi.service.component.ComponentContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.crx.packaging.impl;

import com.adobe.granite.license.License;
import com.adobe.granite.license.ProductInfoService;
import com.day.crx.packaging.PackageShare;
import com.day.crx.packaging.PackageShareSession;
import com.day.crx.packaging.Proxy;
import com.day.crx.packaging.impl.EasyX509TrustManager;
import com.day.crx.packaging.impl.PackageShareSessionImpl;
import com.day.crx.packaging.impl.proxy.ProxyImpl;
import com.day.jcr.vault.packaging.JcrPackage;
import com.day.jcr.vault.packaging.JcrPackageDefinition;
import com.day.jcr.vault.packaging.JcrPackageManager;
import com.day.jcr.vault.packaging.PackageId;
import com.day.jcr.vault.packaging.PackagingService;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.StatusLine;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.osgi.services.HttpClientBuilderFactory;
import org.apache.http.protocol.HttpContext;
import org.apache.jackrabbit.util.Text;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(metatype=0, immediate=1)
@Service(value={PackageShare.class})
public class PackageShareImpl
implements PackageShare {
    private static final Logger log = LoggerFactory.getLogger(PackageShareImpl.class);
    public static final int CLIENT_VERSION_2 = 2;
    public static final int CLIENT_VERSION = 2;
    private static final String SHARE_LOGIN_PATH = "/content/packageshare.login.html?sling:authRequestLogin=1";
    private static final int MAX_HOST_CONNECTIONS = 10;
    @Property(value={"https://www.adobe.com/go/packageshare"})
    private static final String SERVER_URL = "url";
    @Property(value={"true"})
    private static final String RELAXED_SSL = "relaxedSSL";
    @Property(value={"true"})
    private static final String EXPIRED_SSL = "expiredSSL";
    @Reference
    private ProductInfoService prodSvc;
    @Reference
    HttpClientBuilderFactory builderFactory;
    private int connectionTimeout = 30000;
    private int socketTimeout = 60000;
    private PoolingHttpClientConnectionManager connectionManager;
    private boolean relaxedSSL;
    private boolean expiredSSL;
    private URI initialURL;
    private HttpHost targetHost;
    private final Map<String, PackageShareSession> pool = new HashMap<String, PackageShareSession>();

    @Activate
    protected void activate(ComponentContext context) throws RepositoryException {
        Dictionary dict = context.getProperties();
        this.relaxedSSL = dict.get("relaxedSSL") == null || "true".equals(dict.get("relaxedSSL"));
        boolean bl = this.expiredSSL = dict.get("expiredSSL") == null || "true".equals(dict.get("expiredSSL"));
        if (dict.get("url") != null) {
            try {
                this.initialURL = new URI(dict.get("url").toString());
            }
            catch (URISyntaxException e) {
                log.error("Unable to initialize Package Share service", (Throwable)e);
            }
        } else {
            log.error("Initial server url not specified.");
        }
        this.connectionManager = new PoolingHttpClientConnectionManager();
        this.connectionManager.setDefaultMaxPerRoute(10);
    }

    @Deactivate
    protected void deactivate() {
        if (this.connectionManager != null) {
            this.connectionManager.shutdown();
            this.connectionManager = null;
        }
    }

    private CloseableHttpClient createHttpClient() {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(this.connectionTimeout).setConnectionRequestTimeout(this.connectionTimeout).setSocketTimeout(this.socketTimeout).build();
        HttpClientBuilder httpClient = this.builderFactory.newBuilder().setDefaultRequestConfig(config).setConnectionManager((HttpClientConnectionManager)this.connectionManager);
        try {
            this.establishInitialHttpClient(this.initialURL, httpClient);
            this.validateInitialURL(httpClient);
            return httpClient.build();
        }
        catch (IOException e) {
            log.error("Unable to create http client", (Throwable)e);
            return null;
        }
        catch (URISyntaxException e) {
            log.error("Unable to create http client", (Throwable)e);
            return null;
        }
    }

    private void establishInitialHttpClient(URI uri, HttpClientBuilder httpClient) throws IOException {
        log.info("Initializing Package Share Host {}", (Object)uri);
        if ("https".equals(uri.getScheme())) {
            log.info("* Accept self-certified SSL certificates: {}", (Object)this.relaxedSSL);
            log.info("* Accept expired SSL certificates: {}", (Object)this.expiredSSL);
            if (this.relaxedSSL) {
                try {
                    SSLContext context = SSLContext.getInstance("SSL");
                    context.init(null, new TrustManager[]{new EasyX509TrustManager(null, this.expiredSSL)}, null);
                    httpClient.setSslcontext(context);
                }
                catch (Exception e) {
                    throw new IOException(e);
                }
            }
        }
        this.targetHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void validateInitialURL(HttpClientBuilder httpClient) throws IOException, URISyntaxException {
        URI location;
        CloseableHttpClient client = httpClient.build();
        HttpClientContext context = HttpClientContext.create();
        HttpGet get = new HttpGet(this.initialURL);
        get.addHeader((Header)new BasicHeader("User-Agent", "Day cq-packageshare-client"));
        get.setConfig(RequestConfig.custom().setRedirectsEnabled(true).build());
        CloseableHttpResponse resp = client.execute((HttpUriRequest)get, (HttpContext)context);
        location = null;
        try {
            if (resp.getStatusLine().getStatusCode() == 200) {
                HttpHost target = context.getTargetHost();
                List redirectLocations = context.getRedirectLocations();
                location = URIUtils.resolve((URI)get.getURI(), (HttpHost)target, (List)redirectLocations);
                log.info("validateInitialURL({}) -> {}", (Object)this.initialURL, (Object)location);
            }
        }
        finally {
            resp.close();
        }
        if (location != null) {
            this.establishInitialHttpClient(location, httpClient);
        }
    }

    private String getLicenseId() {
        String id = "unknown";
        License lic = this.prodSvc.getLicense();
        if (lic != null) {
            id = lic.getDownloadId();
        }
        return id;
    }

    private String getProductVersion() {
        return "2.1.0";
    }

    private String getProductName() {
        return "CRX";
    }

    private String getIdString() {
        StringBuilder b = new StringBuilder();
        b.append("i=").append(Text.escape((String)this.getLicenseId()));
        b.append(",p=").append(Text.escape((String)this.getProductName()));
        b.append(",v=").append(Text.escape((String)this.getProductVersion()));
        b.append(",cv=").append(2);
        return b.toString();
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Override
    public PackageShareSession getSession(String id) {
        Map<String, PackageShareSession> map = this.pool;
        synchronized (map) {
            return this.pool.get(id);
        }
    }

    @Override
    public PackageShareSession getSession(HttpServletRequest req) {
        Cookie[] cs = req.getCookies();
        if (cs != null) {
            for (Cookie c : cs) {
                if (!c.getName().equals("daypsid")) continue;
                return this.getSession(c.getValue());
            }
        }
        return null;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Override
    public PackageShareSession getSession(HttpServletRequest req, HttpServletResponse resp) {
        PackageShareSession s = this.getSession(req);
        if (s == null) {
            s = new PackageShareSessionImpl(this, UUID.randomUUID().toString(), this.createHttpClient());
            Cookie c = new Cookie("daypsid", s.getId());
            c.setPath("/");
            c.setHttpOnly(true);
            resp.addCookie(c);
            Map<String, PackageShareSession> map = this.pool;
            synchronized (map) {
                this.pool.put(s.getId(), s);
            }
        }
        return s;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    protected void discardSession(String id) {
        Map<String, PackageShareSession> map = this.pool;
        synchronized (map) {
            this.pool.remove(id);
        }
    }

    protected Proxy createProxy(boolean suppressId, CloseableHttpClient httpClient) {
        ProxyImpl p = new ProxyImpl(httpClient, this.targetHost, "/crx/packageshare/index.html", "/crx/packageshare/res");
        if (!suppressId) {
            p.setIdString(this.getIdString());
        }
        return p;
    }

    @Override
    public PackageShareSession login(Session session, HttpServletRequest req, HttpServletResponse resp, String user, String pass) throws IOException {
        PackageShareSessionImpl s = (PackageShareSessionImpl)this.getSession(req, resp);
        Proxy p = this.createProxy(false, s.getHttpClient());
        p.setContextPath(req.getContextPath());
        UsernamePasswordCredentials creds = null;
        if (user == null || user.length() == 0) {
            user = "anonymous";
        } else {
            creds = new UsernamePasswordCredentials(user, pass);
            p.setCredentials((Credentials)creds);
        }
        p.setFollowRedirects(true);
        try {
            JSONObject json;
            int status = p.doGet("/content/packageshare.login.html?sling:authRequestLogin=1");
            if (status != 200) {
                log.info("PackageShare login for {} failed: {}", (Object)user, (Object)status);
                PackageShareSession packageShareSession = null;
                return packageShareSession;
            }
            String data = p.fetch();
            try {
                json = new JSONObject(data);
            }
            catch (JSONException e2) {
                log.info("PackageShare login for {} failed: JSONException", (Object)user);
                PackageShareSession packageShareSession = null;
                p.close();
                return packageShareSession;
            }
            s.setUser(user, (Credentials)creds, json);
            log.info("PackageShare login of {} successful.", (Object)user);
            PackageShareSessionImpl e2 = s;
            return e2;
        }
        catch (IOException io) {
            log.info("PackageShare login for {} failed: {}", (Object)user, (Object)io.toString());
            throw io;
        }
        finally {
            p.close();
        }
    }

    private List<PackageId> getLocalPackages(Session session) {
        LinkedList<PackageId> ret = new LinkedList<PackageId>();
        try {
            JcrPackageManager packMgr = PackagingService.getPackageManager((Session)session);
            List packs = packMgr.listPackages(null, true);
            for (JcrPackage p : packs) {
                PackageId id = p.getDefinition().getId();
                if (!"day".equals(id.getGroup()) && !id.getGroup().startsWith("day/")) continue;
                ret.add(id);
            }
        }
        catch (RepositoryException e) {
            log.error("error during package retrieval.", (Throwable)e);
        }
        return ret;
    }

    protected void bindProdSvc(ProductInfoService productInfoService) {
        this.prodSvc = productInfoService;
    }

    protected void unbindProdSvc(ProductInfoService productInfoService) {
        if (this.prodSvc == productInfoService) {
            this.prodSvc = null;
        }
    }

    protected void bindBuilderFactory(HttpClientBuilderFactory httpClientBuilderFactory) {
        this.builderFactory = httpClientBuilderFactory;
    }

    protected void unbindBuilderFactory(HttpClientBuilderFactory httpClientBuilderFactory) {
        if (this.builderFactory == httpClientBuilderFactory) {
            this.builderFactory = null;
        }
    }
}