001/* 002 * Copyright 2025 Anyware Services 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.ametys.core.util; 017 018import java.util.regex.Pattern; 019 020import org.apache.hc.client5.http.DnsResolver; 021import org.apache.hc.client5.http.SchemePortResolver; 022import org.apache.hc.client5.http.impl.io.DefaultHttpClientConnectionOperator; 023import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder; 024import org.apache.hc.client5.http.io.HttpClientConnectionOperator; 025import org.apache.hc.client5.http.ssl.TlsSocketStrategy; 026import org.apache.hc.core5.http.URIScheme; 027import org.apache.hc.core5.http.config.RegistryBuilder; 028 029/** 030 * A connection manager builder able to build a connection operator that block any connection to a set of given IP address 031 */ 032public class IPRestrictedConnectionManagerBuilder extends PoolingHttpClientConnectionManagerBuilder 033{ 034 private Pattern _pattern; 035 036 /** 037 * Internal 038 * @param pattern a regex to match against IP address (v4 or v6). Any connection to an address that matches the regex will be block. 039 */ 040 protected IPRestrictedConnectionManagerBuilder(Pattern pattern) 041 { 042 super(); 043 _pattern = pattern; 044 } 045 046 /** 047 * Create a new builder 048 * @param pattern a regex to match against IP address (v4 or v6). Any connection to an address that matches the regex will be block. 049 * @return the builder 050 */ 051 public static IPRestrictedConnectionManagerBuilder create(Pattern pattern) 052 { 053 return new IPRestrictedConnectionManagerBuilder(pattern); 054 } 055 056 @Override 057 protected HttpClientConnectionOperator createConnectionOperator(SchemePortResolver schemePortResolver, DnsResolver dnsResolver, TlsSocketStrategy tlsSocketStrategy) 058 { 059 // replace the socket factory used by the super implementation 060 return new DefaultHttpClientConnectionOperator( 061 socksProxy -> socksProxy == null ? new IPRestrictedSocket(_pattern) : new IPRestrictedSocket(_pattern, socksProxy), 062 schemePortResolver, 063 dnsResolver, 064 RegistryBuilder.<TlsSocketStrategy>create() 065 .register(URIScheme.HTTPS.id, tlsSocketStrategy) 066 .build()); 067 } 068}