<commit_before>/*
 * Copyright 2017 National Library of Norway.
 *
 * 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 no.nb.nna.broprox.harvester.proxy;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;

import com.google.common.net.InetAddresses;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.opentracing.tag.Tags;
import no.nb.nna.broprox.commons.opentracing.OpenTracingWrapper;
import no.nb.nna.broprox.db.DbAdapter;
import no.nb.nna.broprox.db.ProtoUtils;
import no.nb.nna.broprox.model.MessagesProto.CrawlLog;
import org.littleshoot.proxy.HostResolver;
import org.netpreserve.commons.util.datetime.DateFormat;
import org.netpreserve.commons.util.datetime.Granularity;
import org.netpreserve.commons.util.datetime.VariablePrecisionDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xbill.DNS.ARecord;
import org.xbill.DNS.CNAMERecord;
import org.xbill.DNS.Cache;
import org.xbill.DNS.Credibility;
import org.xbill.DNS.DClass;
import org.xbill.DNS.DNAMERecord;
import org.xbill.DNS.Message;
import org.xbill.DNS.Name;
import org.xbill.DNS.NameTooLongException;
import org.xbill.DNS.RRset;
import org.xbill.DNS.Rcode;
import org.xbill.DNS.Record;
import org.xbill.DNS.ResolverConfig;
import org.xbill.DNS.SetResponse;
import org.xbill.DNS.SimpleResolver;
import org.xbill.DNS.Type;

/**
 *
 */
public class DnsLookup implements HostResolver {

    private static final Logger LOG = LoggerFactory.getLogger(DnsLookup.class);

    private static final short DCLASS = DClass.IN;

    private static final short TYPE = Type.A;

    final Cache cache;

    String digestAlgorithm = "SHA-1";

    boolean digestContent = true;

    private final DbAdapter db;

    private final ContentWriterClient contentWriterClient;

    /**
     * If a DNS lookup fails, whether or not to fallback to InetAddress resolution, which may use local 'hosts' files or
     * other mechanisms.
     */
    protected boolean acceptNonDnsResolves = false;

    InetAddress serverInetAddr = null;

    private final SimpleResolver[] resolvers;

    public DnsLookup(final DbAdapter db, final ContentWriterClient contentWriterClient, List<String> dnsServers) {
        this.db = db;
        this.contentWriterClient = contentWriterClient;
        cache = new Cache(DCLASS);
        cache.setMaxCache(24 * 3600); // Cache an answer for a maximum of one day
        cache.setMaxNCache(24 * 3600); // Cache negative answers for one day
        cache.setMaxEntries(500000);

        try {
            if (dnsServers == null || dnsServers.isEmpty()) {
                dnsServers = Arrays.asList(ResolverConfig.getCurrentConfig().servers());
                LOG.info("No DNS server configured.");
            }
            resolvers = new SimpleResolver[dnsServers.size()];
            for (int i = 0; i < dnsServers.size(); i++) {
                LOG.info("Initializing DNS server: " + dnsServers.get(i));
                resolvers[i] = new SimpleResolver(dnsServers.get(i));
            }
        } catch (UnknownHostException ex) {
            throw new RuntimeException(ex);
        }
    }

    private class Resolver implements Callable<InetSocketAddress> {

        String host;

        Integer port;

        public Resolver(String host, Integer port) {<commit_msg>Added support for setting dns servers port<commit_after>/*
 * Copyright 2017 National Library of Norway.
 *
 * 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 no.nb.nna.broprox.harvester.proxy;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;

import com.google.common.net.InetAddresses;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.opentracing.tag.Tags;
import no.nb.nna.broprox.commons.opentracing.OpenTracingWrapper;
import no.nb.nna.broprox.db.DbAdapter;
import no.nb.nna.broprox.db.ProtoUtils;
import no.nb.nna.broprox.model.MessagesProto.CrawlLog;
import org.littleshoot.proxy.HostResolver;
import org.netpreserve.commons.util.datetime.DateFormat;
import org.netpreserve.commons.util.datetime.Granularity;
import org.netpreserve.commons.util.datetime.VariablePrecisionDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xbill.DNS.ARecord;
import org.xbill.DNS.CNAMERecord;
import org.xbill.DNS.Cache;
import org.xbill.DNS.Credibility;
import org.xbill.DNS.DClass;
import org.xbill.DNS.DNAMERecord;
import org.xbill.DNS.Message;
import org.xbill.DNS.Name;
import org.xbill.DNS.NameTooLongException;
import org.xbill.DNS.RRset;
import org.xbill.DNS.Rcode;
import org.xbill.DNS.Record;
import org.xbill.DNS.ResolverConfig;
import org.xbill.DNS.SetResponse;
import org.xbill.DNS.SimpleResolver;
import org.xbill.DNS.Type;

/**
 *
 */
public class DnsLookup implements HostResolver {

    private static final Logger LOG = LoggerFactory.getLogger(DnsLookup.class);

    private static final short DCLASS = DClass.IN;

    private static final short TYPE = Type.A;

    final Cache cache;

    String digestAlgorithm = "SHA-1";

    boolean digestContent = true;

    private final DbAdapter db;

    private final ContentWriterClient contentWriterClient;

    /**
     * If a DNS lookup fails, whether or not to fallback to InetAddress resolution, which may use local 'hosts' files or
     * other mechanisms.
     */
    protected boolean acceptNonDnsResolves = false;

    InetAddress serverInetAddr = null;

    private final SimpleResolver[] resolvers;

    public DnsLookup(final DbAdapter db, final ContentWriterClient contentWriterClient, List<String> dnsServers) {
        this.db = db;
        this.contentWriterClient = contentWriterClient;
        cache = new Cache(DCLASS);
        cache.setMaxCache(24 * 3600); // Cache an answer for a maximum of one day
        cache.setMaxNCache(24 * 3600); // Cache negative answers for one day
        cache.setMaxEntries(500000);

        try {
            if (dnsServers == null || dnsServers.isEmpty()) {
                dnsServers = Arrays.asList(ResolverConfig.getCurrentConfig().servers());
                LOG.info("No DNS server configured.");
            }
            resolvers = new SimpleResolver[dnsServers.size()];
            for (int i = 0; i < dnsServers.size(); i++) {
                LOG.info("Initializing DNS server: " + dnsServers.get(i));
                String[] dnsServer = dnsServers.get(i).split(":");
                resolvers[i] = new SimpleResolver(dnsServer[0]);
                if (dnsServer.length == 2) {
                    int dnsPort = Integer.parseInt(dnsServer[1]);
                    resolvers[i].setPort(dnsPort);
                }
            }
        } catch (UnknownHostException ex) {
            throw new RuntimeException(ex);
        }
    }

    private class Resolver implements Callable<InetSocketAddress> {

        String host;

        Integer port;

        public Resolver(String host, Integer port) {
{'fraction_non_alphanumeric': 0.09578414839797639, 'fraction_numerical': 0.007082630691399663, 'mean_word_length': 3.492929292929293, 'pattern_counts': {'":': 1, '<': 9, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2772987', 'n_tokens_mistral': 2734, 'n_tokens_neox': 2632, 'n_words': 692}