/*
 * Copyright (C)2009 - SSHJ Contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package be.iminds.ilabt.jfed.util;

import net.schmizz.sshj.common.*;
import net.schmizz.sshj.transport.verification.HostKeyVerifier;
import net.schmizz.sshj.transport.verification.OpenSSHKnownHosts.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.RSAPublicKeySpec;
import java.util.ArrayList;
import java.util.List;

/**
 * A {@link HostKeyVerifier} implementation for a {@code known_hosts} file i.e. in the format used by OpenSSH read from memory.
 *
 * @see <a href="http://nms.lcs.mit.edu/projects/ssh/README.hashed-hosts">Hashed hostnames spec</a>
 */
public class OpenSSHKnownHostsInMemory
        implements HostKeyVerifier {

    private static final Logger LOG = LoggerFactory.getLogger(OpenSSHKnownHostsInMemory.class);
    protected final Logger log = LoggerFactory.getLogger(getClass());

    protected final List<HostEntry> entries = new ArrayList<>();

    public OpenSSHKnownHostsInMemory(String contents)
            throws IOException {
        String[] lines = contents.split("\n");

        // Read in the contents, storing each line as an entry
        for (String line : lines)
            try {
                HostEntry entry = EntryFactory.parseEntry(line);
                if (entry != null) {
                    entries.add(entry);
                }
            } catch (SSHException ignore) {
                log.debug("Bad line ({}): {} ", ignore.toString(), line);
            }

    }

    @Override
    public boolean verify(final String hostname, final int port, final PublicKey key) {
        final KeyType type = KeyType.fromKey(key);

        if (type == KeyType.UNKNOWN)
            return false;

        final String adjustedHostname = (port != 22) ? "[" + hostname + "]:" + port : hostname;

        for (HostEntry e : entries) {
            try {
                if (e.appliesTo(type, adjustedHostname))
                    return e.verify(key) || hostKeyChangedAction(e, adjustedHostname, key);
            } catch (IOException ioe) {
                log.error("Error with {}: {}", e, ioe.getMessage(), ioe);
                return false;
            }
        }

        return hostKeyUnverifiableAction(adjustedHostname, key);
    }

    protected boolean hostKeyUnverifiableAction(String hostname, PublicKey key) {
        return false;
    }

    protected boolean hostKeyChangedAction(HostEntry entry, String hostname, PublicKey key) {
        log.warn("Host key for `{}` has changed!", hostname);
        return false;
    }

    public List<HostEntry> entries() {
        return entries;
    }

    /**
     * Each line in these files contains the following fields: markers
     * (optional), hostnames, bits, exponent, modulus, comment.  The fields are
     * separated by spaces.
     * <p/>
     * The marker is optional, but if it is present then it must be one of
     * ``@cert-authority'', to indicate that the line contains a certification
     * authority (CA) key, or ``@revoked'', to indicate that the key contained
     * on the line is revoked and must not ever be accepted.  Only one marker
     * should be used on a key line.
     * <p/>
     * Hostnames is a comma-separated list of patterns (`*' and `?' act as
     * wildcards); each pattern in turn is matched against the canonical host
     * name (when authenticating a client) or against the user-supplied name
     * (when authenticating a server).  A pattern may also be preceded by `!' to
     * indicate negation: if the host name matches a negated pattern, it is not
     * accepted (by that line) even if it matched another pattern on the line.
     * A hostname or address may optionally be enclosed within `[' and `]'
     * brackets then followed by `:' and a non-standard port number.
     * <p/>
     * Alternately, hostnames may be stored in a hashed form which hides host
     * names and addresses should the file's contents be disclosed.  Hashed
     * hostnames start with a `|' character.  Only one hashed hostname may
     * appear on a single line and none of the above negation or wildcard
     * operators may be applied.
     * <p/>
     * Bits, exponent, and modulus are taken directly from the RSA host key;
     * they can be obtained, for example, from /etc/ssh/ssh_host_key.pub.  The
     * optional comment field continues to the end of the line, and is not used.
     * <p/>
     * Lines starting with `#' and empty lines are ignored as comments.
     */
    public static class EntryFactory {

        public static HostEntry parseEntry(String line)
                throws IOException {
            if (isComment(line)) {
                return new CommentEntry(line);
            }

            final String[] split = line.split(" ");

            int i = 0;
            final Marker marker = Marker.fromString(split[i]);
            if (marker != null) {
                i++;
            }
            if (split.length < 3) {
                LOG.error("Error reading entry `{}`", line);
                return null;
            }
            final String hostnames = split[i++];
            final String sType = split[i++];

            KeyType type = KeyType.fromString(sType);
            PublicKey key;

            if (type != KeyType.UNKNOWN) {
                final String sKey = split[i++];
                key = getKey(sKey);
            } else if (isBits(sType)) {
                type = KeyType.RSA;
                // int bits = Integer.valueOf(sType);
                final BigInteger e = new BigInteger(split[i++]);
                final BigInteger n = new BigInteger(split[i++]);
                try {
                    final KeyFactory keyFactory = SecurityUtils.getKeyFactory("RSA");
                    key = keyFactory.generatePublic(new RSAPublicKeySpec(n, e));
                } catch (Exception ex) {
                    LOG.error("Error reading entry `{}`, could not create key", line, ex);
                    return null;
                }
            } else {
                LOG.error("Error reading entry `{}`, could not determine type", line);
                return null;
            }

            if (isHashed(hostnames)) {
                return new HashedEntry(marker, hostnames, type, key);
            } else {
                return new SimpleEntry(marker, hostnames, type, key);
            }
        }

        private static PublicKey getKey(String sKey)
                throws IOException {
            return new Buffer.PlainBuffer(Base64.decode(sKey)).readPublicKey();
        }

        @SuppressWarnings("ResultOfMethodCallIgnored")
        private static boolean isBits(String type) {
            try {
                Integer.parseInt(type);
                return true;
            } catch (NumberFormatException e) {
                return false;
            }
        }

        private static boolean isComment(String line) {
            return line.isEmpty() || line.startsWith("#");
        }

        public static boolean isHashed(String line) {
            return line.startsWith("|1|");
        }

    }


}