1 /** 2 * 3 * Licensed to the Apache Software Foundation (ASF) under one or more 4 * contributor license agreements. See the NOTICE file distributed with 5 * this work for additional information regarding copyright ownership. 6 * The ASF licenses this file to You under the Apache License, Version 2.0 7 * (the "License"); you may not use this file except in compliance with 8 * the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 package org.apache.openejb.server.auth; 19 20 import java.util.regex.Pattern; 21 import java.util.regex.Matcher; 22 import java.net.InetAddress; 23 import java.net.Inet4Address; 24 25 /** 26 * @version $Revision$ $Date$ 27 */ 28 public class ExactIPAddressPermission implements IPAddressPermission { 29 private static final Pattern MASK_VALIDATOR = Pattern.compile("^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$"); 30 31 public static boolean canSupport(String mask) { 32 Matcher matcher = MASK_VALIDATOR.matcher(mask); 33 return matcher.matches(); 34 } 35 36 private final byte[] bytes; 37 38 public ExactIPAddressPermission(byte[] bytes) { 39 this.bytes = bytes; 40 } 41 42 public ExactIPAddressPermission(String mask) { 43 Matcher matcher = MASK_VALIDATOR.matcher(mask); 44 if (false == matcher.matches()) { 45 throw new IllegalArgumentException("Mask " + mask + " does not match pattern " + MASK_VALIDATOR.pattern()); 46 } 47 48 bytes = new byte[4]; 49 for (int i = 0; i < 4; i++) { 50 String group = matcher.group(i + 1); 51 int value = Integer.parseInt(group); 52 if (value < 0 || 255 < value) { 53 throw new IllegalArgumentException("byte #" + i + " is not valid."); 54 } 55 bytes[i] = (byte) value; 56 } 57 } 58 59 public boolean implies(InetAddress address) { 60 if (false == address instanceof Inet4Address) { 61 return false; 62 } 63 64 byte[] byteAddress = address.getAddress(); 65 for (int i = 0; i < 4; i++) { 66 if (byteAddress[i] != bytes[i]) { 67 return false; 68 } 69 } 70 return true; 71 } 72 }