Allow-listing IP addresses using `call.cancel()` from within `EventListener.dnsEnd()` in OkHttp

Viewed 56

i am overriding the dnsEnd() function in EventListener:

@Override
    public void dnsEnd(Call call, String domainName, List<InetAddress> inetAddressList) {
        inetAddressList.forEach(address -> {
            logger.debug("checking if url ({}) is in allowlist", address.toString());
            if (!allowlist.contains(address)) {
                call.cancel();
            }
        });
    }

i know, in the documentation it says not to alter call parameters etc:

"All event methods must execute fast, without external locking, cannot throw exceptions, attempt to mutate the event parameters, or be re-entrant back into the client. Any IO - writing to files or network should be done asynchronously."

but, as i don't care about the call if it is trying to get to an address outside the allowlist, i fail to see the issue with this implementation.

I want to know if anyone has experience with this, and why it may be an issue? I tested this and it seems to work fine.

1 Answers

This is fine and safe. Probably the strangest consequence of this is the canceled event will be triggered by the thread already processing the DNS event.

But cancelling is not the best way to constrain permitted IP addresses to a list. You can instead implement the Dns interface. Your implementation should delegate to Dns.SYSTEM and them filter its results to your allowlist. That way you don't have to worry about races on cancelation.

Related