001/*
002 * acme4j - Java ACME client
003 *
004 * Copyright (C) 2015 Richard "Shred" Körber
005 *   http://acme4j.shredzone.org
006 *
007 * Licensed under the Apache License, Version 2.0 (the "License");
008 * you may not use this file except in compliance with the License.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
013 */
014package org.shredzone.acme4j.provider;
015
016import java.net.URI;
017import java.net.http.HttpClient;
018import java.time.ZonedDateTime;
019import java.util.Collections;
020import java.util.HashMap;
021import java.util.Map;
022import java.util.Objects;
023import java.util.ServiceLoader;
024
025import org.shredzone.acme4j.Login;
026import org.shredzone.acme4j.Session;
027import org.shredzone.acme4j.challenge.Challenge;
028import org.shredzone.acme4j.challenge.Dns01Challenge;
029import org.shredzone.acme4j.challenge.DnsAccount01Challenge;
030import org.shredzone.acme4j.challenge.Http01Challenge;
031import org.shredzone.acme4j.challenge.TlsAlpn01Challenge;
032import org.shredzone.acme4j.challenge.TokenChallenge;
033import org.shredzone.acme4j.connector.Connection;
034import org.shredzone.acme4j.connector.DefaultConnection;
035import org.shredzone.acme4j.connector.HttpConnector;
036import org.shredzone.acme4j.connector.NetworkSettings;
037import org.shredzone.acme4j.exception.AcmeException;
038import org.shredzone.acme4j.toolbox.JSON;
039
040/**
041 * Abstract implementation of {@link AcmeProvider}. It consists of a challenge
042 * registry and a standard {@link HttpConnector}.
043 * <p>
044 * Implementing classes must implement at least {@link AcmeProvider#accepts(URI)}
045 * and {@link AbstractAcmeProvider#resolve(URI)}.
046 */
047public abstract class AbstractAcmeProvider implements AcmeProvider {
048    private static final int HTTP_NOT_MODIFIED = 304;
049
050    private static final Map<String, ChallengeProvider> CHALLENGES = challengeMap();
051
052    @Override
053    public Connection connect(URI serverUri, NetworkSettings networkSettings, HttpClient httpClient) {
054        return new DefaultConnection(createHttpConnector(networkSettings, httpClient));
055    }
056
057    @Override
058    public JSON directory(Session session, URI serverUri) throws AcmeException {
059        var expires = session.getDirectoryExpires();
060        if (expires != null && expires.isAfter(ZonedDateTime.now())) {
061            // The cached directory is still valid
062            return null;
063        }
064
065        try (var nonceHolder = session.lockNonce();
066             var conn = connect(serverUri, session.networkSettings(), session.getHttpClient())) {
067            var lastModified = session.getDirectoryLastModified();
068            var rc = conn.sendRequest(resolve(serverUri), session, lastModified);
069            if (lastModified != null && rc == HTTP_NOT_MODIFIED) {
070                // The server has not been modified since
071                return null;
072            }
073
074            // evaluate caching headers
075            session.setDirectoryLastModified(conn.getLastModified().orElse(null));
076            session.setDirectoryExpires(conn.getExpiration().orElse(null));
077
078            // use nonce header if there is one, saves a HEAD request...
079            conn.getNonce().ifPresent(nonceHolder::setNonce);
080
081            return conn.readJsonResponse();
082        }
083    }
084
085    private static Map<String, ChallengeProvider> challengeMap() {
086        var map = new HashMap<String, ChallengeProvider>();
087
088        map.put(Dns01Challenge.TYPE, Dns01Challenge::new);
089        map.put(DnsAccount01Challenge.TYPE, DnsAccount01Challenge::new);
090        map.put(Http01Challenge.TYPE, Http01Challenge::new);
091        map.put(TlsAlpn01Challenge.TYPE, TlsAlpn01Challenge::new);
092
093        for (var provider : ServiceLoader.load(ChallengeProvider.class)) {
094            var typeAnno = provider.getClass().getAnnotation(ChallengeType.class);
095            if (typeAnno == null) {
096                throw new IllegalStateException("ChallengeProvider "
097                        + provider.getClass().getName()
098                        + " has no @ChallengeType annotation");
099            }
100            var type = typeAnno.value();
101            if (type == null || type.trim().isEmpty()) {
102                throw new IllegalStateException("ChallengeProvider "
103                        + provider.getClass().getName()
104                        + ": type must not be null or empty");
105            }
106            if (map.containsKey(type)) {
107                throw new IllegalStateException("ChallengeProvider "
108                        + provider.getClass().getName()
109                        + ": there is already a provider for challenge type "
110                        + type);
111            }
112            map.put(type, provider);
113        }
114
115        return Collections.unmodifiableMap(map);
116    }
117
118    /**
119     * {@inheritDoc}
120     * <p>
121     * This implementation handles the standard challenge types. For unknown types,
122     * generic {@link Challenge} or {@link TokenChallenge} instances are created.
123     * <p>
124     * Custom provider implementations may override this method to provide challenges that
125     * are proprietary to the provider.
126     */
127    @Override
128    public Challenge createChallenge(Login login, JSON data) {
129        Objects.requireNonNull(login, "login");
130        Objects.requireNonNull(data, "data");
131
132        var type = data.get("type").asString();
133
134        var constructor = CHALLENGES.get(type);
135        if (constructor != null) {
136            return constructor.create(login, data);
137        }
138
139        if (data.contains("token")) {
140            return new TokenChallenge(login, data);
141        } else {
142            return new Challenge(login, data);
143        }
144    }
145
146    /**
147     * Creates a {@link HttpConnector} with the given {@link NetworkSettings} and
148     * {@link HttpClient}.
149     * <p>
150     * Subclasses may override this method to configure the {@link HttpConnector}.
151     *
152     * @param settings The network settings to use
153     * @param httpClient The HTTP client to use
154     * @return A new {@link HttpConnector} instance
155     * @since 4.0.0
156     */
157    protected HttpConnector createHttpConnector(NetworkSettings settings, HttpClient httpClient) {
158        return new HttpConnector(settings, httpClient);
159    }
160
161}