Skip to content

Commit

Permalink
extract ConcatenatingIterator, checkerframework changes
Browse files Browse the repository at this point in the history
  • Loading branch information
danthe1st committed Mar 10, 2024
1 parent fcfe934 commit 6310129
Show file tree
Hide file tree
Showing 13 changed files with 56 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@
public record Config(
HostMatcherConfig ignoredHosts,
List<PreForwardRule> preForwardRules,
List<PostForwardRule> postForwardRules
) {
List<PostForwardRule> postForwardRules) {

public Config(@Nullable HostMatcherConfig ignoredHosts, @Nullable List<PreForwardRule> preForwardRules, @Nullable List<PostForwardRule> postForwardRules) {
if(ignoredHosts == null){
Expand All @@ -38,7 +37,7 @@ public Config(@Nullable HostMatcherConfig ignoredHosts, @Nullable List<PreForwar
}

public static Config load(Path path) throws IOException {
if(!Files.exists(path)) {
if(!Files.exists(path)){
return new Config(null, null, null);
}
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public ServerHandlersInit(Bootstrap clientBootstrap, Config config) throws KeySt
postForwardMatcher = createMatcherFromRules(config.postForwardRules());
ignoredHostMatcher = new HostMatcher<>(List.of(Map.entry(config.ignoredHosts(), new Object())), false);
}

private <T extends ProcessingRule> HostMatcher<T> createMatcherFromRules(@UnderInitialization ServerHandlersInit this, List<T> ruleList) {
List<Map.Entry<HostMatcherConfig, T>> rules = new ArrayList<>();
for(T rule : ruleList){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public String getAsString() {
ensureBytesPresent();
return new String(bytes, StandardCharsets.UTF_8);
}

@EnsuresNonNull("bytes")
private void ensureBytesPresent() {
if(bytes == null){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,16 +85,15 @@ private void forwardRequest(ChannelHandlerContext channelHandlerContext, FullHtt
}
}


// in case Netty caught an exception (e.g. the server is unreachable),
// the client receives a 502 Bad Gateway response including the stack trace
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOG
.atError()
.addArgument(sniHandler::hostname)
.log("An exception occured trying to process a request to host '{}'", cause);
ctx.channel().close();
LOG
.atError()
.addArgument(sniHandler::hostname)
.log("An exception occured trying to process a request to host '{}'", cause);
ctx.channel().close();
}

private void writeException(Throwable cause, Channel channel) throws InterruptedException, IOException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
originalClientContext.channel().close();
ctx.channel().close();
}

private void processRules(FullHttpResponse res) {
HttpResponseContentAccessor contentAccessor = new HttpResponseContentAccessor(res);
for(PostForwardRule rule : postForwardRules){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public CustomSniHandler(Mapping<? super String, ? extends SslContext> mapping, B
this.clientBootstrapTemplate = clientBootstrapTemplate;
ignoredHosts = ignoredHostMatcher;
}

@Override
protected void replaceHandler(ChannelHandlerContext channelHandlerContext, String hostname, SslContext sslContext) throws Exception {
ChannelPipeline pipeline = channelHandlerContext.pipeline();
Expand All @@ -39,7 +39,7 @@ protected void replaceHandler(ChannelHandlerContext channelHandlerContext, Strin

boolean foundThis = false;

for(Iterator<Map.Entry<String, ChannelHandler>> it = pipeline.iterator();it.hasNext();) {
for(Iterator<Map.Entry<String, ChannelHandler>> it = pipeline.iterator(); it.hasNext();){
ChannelHandler handler = it.next().getValue();
if(foundThis){
it.remove();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public class SNIHandlerMapping implements Mapping<String, SslContext> {
private final Map<String, SslContextCacheEntry> certificateCache = new ConcurrentHashMap<>();
private final KeyPair rootKeyPair;
private final X509Certificate rootCert;

private final KeyPair serverKeyPair;

private SNIHandlerMapping() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {
Expand Down Expand Up @@ -87,7 +87,7 @@ public static SNIHandlerMapping createMapping() throws KeyStoreException, NoSuch
Thread.startVirtualThread(mapping::runCleanupDaemon);
return mapping;
}

private void runCleanupDaemon() {
try{
while(true){// NOSONAR ended by potential InterruptedException (or more likely the virtual thread ending)
Expand All @@ -101,7 +101,7 @@ private void runCleanupDaemon() {
Thread.currentThread().interrupt();
}
}

@Override
public SslContext map(String hostname) {
LOG.debug("loadding certificate for hostname {}", hostname);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package io.github.danthe1st.httpsintercept.matcher;

import java.util.Collections;
import java.util.Iterator;
import java.util.Queue;

import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;

final class ConcatenatingIterator<@NonNull T> extends IteratingIterator<T> {
private final Queue<Iterator<T>> iterators;
private @Nullable Iterator<T> current;

ConcatenatingIterator(Queue<Iterator<T>> iterators) {
this.iterators = iterators;
current = iterators.poll();
}

@Override
protected Iterator<T> findNextIterator() {
while(current != null && !current.hasNext()){
current = iterators.poll();
}
if(current == null){
return Collections.emptyIterator();
}
return current;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public FilterIterator(Iterator<@NonNull T> iterator, Predicate<@NonNull T> filte
this.iterator = iterator;
this.filter = filter;
}

@Override
@EnsuresNonNullIf(expression = "current", result = true)
public boolean hasNext() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import io.github.danthe1st.httpsintercept.config.HostMatcherConfig;
import org.checkerframework.checker.initialization.qual.UnderInitialization;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;

public final class HostMatcher<@NonNull T> {
private final Map<String, List<@NonNull T>> exactHosts;
Expand Down Expand Up @@ -48,9 +47,11 @@ public HostMatcher(List<Map.Entry<HostMatcherConfig, @NonNull T>> configs, boole

private <K> void addToMap(@UnderInitialization HostMatcher<T> this, Map<K, List<@NonNull T>> multimap, @NonNull T value, Set<String> configValue, Function<String, K> keyTransformer) {
for(String host : configValue){
multimap
.computeIfAbsent(keyTransformer.apply(host), h -> new ArrayList<@NonNull T>())
.add(value);
multimap.merge(
keyTransformer.apply(host),
new ArrayList<>(),
(existing, emptyList) -> existing
).add(value);
}
}

Expand All @@ -71,24 +72,9 @@ private <K> void addToMap(@UnderInitialization HostMatcher<T> this, Map<K, List<
iterators.add(new RegexIterator<>(hostRegexes, hostname));
iterators.add(wildcards.iterator());

Iterator<@NonNull T> it = new IteratingIterator<@NonNull T>() {
private @Nullable Iterator<@NonNull T> current = iterators.poll();

@Override
protected Iterator<@NonNull T> findNextIterator() {
while(current != null && !current.hasNext()){
current = iterators.poll();
}
if(current == null){
return Collections.emptyIterator();
}
return current;
}
};

return distinctIterator(it);
return distinctIterator(new ConcatenatingIterator<>(iterators));
}

private Iterator<@NonNull T> distinctIterator(Iterator<@NonNull T> it) {
Set<T> matchers = Collections.newSetFromMap(new IdentityHashMap<>());
return new FilterIterator<>(it, element -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,14 @@ protected Iterator<T> findNextIterator() {
}while(nextIndex() != -1);
return Collections.emptyIterator();
}

private int nextIndex() {
index = hostname.indexOf('.', index);
if(index != -1){
index++;
}
if(index >= hostname.length()){
index=-1;
index = -1;
}
return index;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ abstract class IteratingIterator<T> implements Iterator<T> {
public boolean hasNext() {
return findNextIterator().hasNext();
}

@Override
public T next() {
return findNextIterator().next();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public HtmlBasedBlocker(HostMatcherConfig hostMatcher,
if(status <= 0){
status = 500;
}
if(responseContentType==null) {
if(responseContentType == null){
responseContentType = "text/html";
}

Expand Down

0 comments on commit 6310129

Please sign in to comment.