Skip to main content
summaryrefslogtreecommitdiffstats
blob: 370693c518017d2621b8ada28ea15dbea193aace (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
//
//  ========================================================================
//  Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd.
//  ------------------------------------------------------------------------
//  All rights reserved. This program and the accompanying materials
//  are made available under the terms of the Eclipse Public License v1.0
//  and Apache License v2.0 which accompanies this distribution.
//
//      The Eclipse Public License is available at
//      http://www.eclipse.org/legal/epl-v10.html
//
//      The Apache License v2.0 is available at
//      http://www.opensource.org/licenses/apache2.0.php
//
//  You may elect to redistribute this code under either of these licenses.
//  ========================================================================
//

package org.eclipse.jetty.util;

import java.util.BitSet;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;


/* ------------------------------------------------------------ */
/**
 * Internet address map to object
 * <p>
 * Internet addresses may be specified as absolute address or as a combination of 
 * four octet wildcard specifications (a.b.c.d) that are defined as follows.
 * </p>
 * <pre>
 * nnn - an absolute value (0-255)
 * mmm-nnn - an inclusive range of absolute values, 
 *           with following shorthand notations:
 *           nnn- => nnn-255
 *           -nnn => 0-nnn
 *           -    => 0-255
 * a,b,... - a list of wildcard specifications
 * </pre>
 */
@SuppressWarnings("serial")
public class IPAddressMap<TYPE> extends HashMap<String, TYPE>
{
    private final HashMap<String,IPAddrPattern> _patterns = new HashMap<String,IPAddrPattern>();

    /* --------------------------------------------------------------- */
    /** Construct empty IPAddressMap.
     */
    public IPAddressMap()
    {
        super(11);
    }
   
    /* --------------------------------------------------------------- */
    /** Construct empty IPAddressMap.
     * 
     * @param capacity initial capacity
     */
    public IPAddressMap(int capacity)
    {
        super (capacity);
    }

    /* ------------------------------------------------------------ */
    /**
     * Insert a new internet address into map
     * 
     * @see java.util.HashMap#put(java.lang.Object, java.lang.Object)
     */
    @Override
    public TYPE put(String addrSpec, TYPE object)
        throws IllegalArgumentException
    {
        if (addrSpec == null || addrSpec.trim().length() == 0)
            throw new IllegalArgumentException("Invalid IP address pattern: "+addrSpec);
        
        String spec = addrSpec.trim();
        if (_patterns.get(spec) == null)
            _patterns.put(spec,new IPAddrPattern(spec));
        
        return super.put(spec, object);
    }
    
    /* ------------------------------------------------------------ */
    /**
     * Retrieve the object mapped to the specified internet address literal
     * 
     * @see java.util.HashMap#get(java.lang.Object)
     */
    @Override
    public TYPE get(Object key)
    {
        return super.get(key);
    }
    
    /* ------------------------------------------------------------ */
    /**
     * Retrieve the first object that is associated with the specified 
     * internet address by taking into account the wildcard specifications.
     * 
     * @param addr internet address
     * @return associated object
     */
    public TYPE match(String addr)
    {
        Map.Entry<String, TYPE> entry = getMatch(addr);
        return entry==null ? null : entry.getValue();
    }
    
    /* ------------------------------------------------------------ */
    /**
     * Retrieve the first map entry that is associated with the specified 
     * internet address by taking into account the wildcard specifications.
     * 
     * @param addr internet address
     * @return map entry associated
     */
    public Map.Entry<String, TYPE> getMatch(String addr)
    {
        if (addr != null)
        {
            for(Map.Entry<String, TYPE> entry: super.entrySet())
            {
                if (_patterns.get(entry.getKey()).match(addr))
                {
                    return entry;
                }
            }
        }
        return null;
    }
    
    /* ------------------------------------------------------------ */
    /**
     * Retrieve a lazy list of map entries associated with specified
     * internet address by taking into account the wildcard specifications.
     * 
     * @param addr  internet address
     * @return lazy list of map entries
     */
    public Object getLazyMatches(String addr)
    {
        if (addr == null)
            return LazyList.getList(super.entrySet());
        
        Object entries = null;
        for(Map.Entry<String, TYPE> entry: super.entrySet())
        {
            if (_patterns.get(entry.getKey()).match(addr))
            {
                entries = LazyList.add(entries,entry);
            }
        }
        return entries;        
    }
    
    /* ------------------------------------------------------------ */
    /**
     * IPAddrPattern
     * 
     * Represents internet address wildcard. 
     * Matches the wildcard to provided internet address.
     */
    private static class IPAddrPattern
    {
        private final OctetPattern[] _octets = new OctetPattern[4];
        /* ------------------------------------------------------------ */
        /**
         * Create new IPAddrPattern
         * 
         * @param value internet address wildcard specification
         * @throws IllegalArgumentException if wildcard specification is invalid
         */
        public IPAddrPattern(String value)
            throws IllegalArgumentException
        {
            if (value == null || value.trim().length() == 0)
                throw new IllegalArgumentException("Invalid IP address pattern: "+value);
                
            try
            {
                StringTokenizer parts = new StringTokenizer(value, ".");
                
                String part;
                for (int idx=0; idx<4; idx++)
                {
                    part = parts.hasMoreTokens() ? parts.nextToken().trim() : "0-255";
                    
                    int len = part.length();
                    if (len == 0 && parts.hasMoreTokens())
                        throw new IllegalArgumentException("Invalid IP address pattern: "+value);
                    
                    _octets[idx] = new OctetPattern(len==0 ? "0-255" : part);
                }
            }
            catch (IllegalArgumentException ex)
            {
                throw new IllegalArgumentException("Invalid IP address pattern: "+value, ex);
            }
        }
        
        /* ------------------------------------------------------------ */
        /**
         * Match the specified internet address against the wildcard
         * 
         * @param value internet address
         * @return true if specified internet address matches wildcard specification
         * 
         * @throws IllegalArgumentException if specified internet address is invalid
         */
        public boolean match(String value)
            throws IllegalArgumentException
        {
            if (value == null || value.trim().length() == 0)
                throw new IllegalArgumentException("Invalid IP address: "+value);
            
            try
            {
                StringTokenizer parts = new StringTokenizer(value, ".");
                
                boolean result = true;
                for (int idx=0; idx<4; idx++)
                {
                    if (!parts.hasMoreTokens())
                        throw new IllegalArgumentException("Invalid IP address: "+value);
                        
                    if (!(result &= _octets[idx].match(parts.nextToken())))
                        break;
                }
                return result;
            }
            catch (IllegalArgumentException ex)
            {
                throw new IllegalArgumentException("Invalid IP address: "+value, ex);
            }
        }
    }
        
    /* ------------------------------------------------------------ */
    /**
     * OctetPattern
     * 
     * Represents a single octet wildcard.
     * Matches the wildcard to the specified octet value.
     */
    private static class OctetPattern extends BitSet
    {
        private final BitSet _mask = new BitSet(256);
        
        /* ------------------------------------------------------------ */
        /**
         * Create new OctetPattern
         * 
         * @param octetSpec octet wildcard specification
         * @throws IllegalArgumentException if wildcard specification is invalid
         */
        public OctetPattern(String octetSpec)
            throws IllegalArgumentException
        {
            try
            {
                if (octetSpec != null)
                {
                    String spec = octetSpec.trim();
                    if(spec.length() == 0)
                    {
                        _mask.set(0,255);
                    }
                    else
                    {
                        StringTokenizer parts = new StringTokenizer(spec,",");
                        while (parts.hasMoreTokens())
                        {
                            String part = parts.nextToken().trim();
                            if (part.length() > 0)
                            {
                                if (part.indexOf('-') < 0)
                                {
                                    Integer value = Integer.valueOf(part);
                                    _mask.set(value);
                                }
                                else
                                {
                                    int low = 0, high = 255;
                                    
                                    String[] bounds = part.split("-",-2);
                                    if (bounds.length != 2)
                                    {
                                        throw new IllegalArgumentException("Invalid octet spec: "+octetSpec);
                                    }
                                    
                                    if (bounds[0].length() > 0)
                                    {
                                        low = Integer.parseInt(bounds[0]);
                                    }
                                    if (bounds[1].length() > 0)
                                    {
                                        high = Integer.parseInt(bounds[1]);
                                    }
                                    
                                    if (low > high)
                                    {
                                        throw new IllegalArgumentException("Invalid octet spec: "+octetSpec);
                                    }
                                    
                                    _mask.set(low, high+1);
                                }
                            }
                        }
                    }
                }
            }
            catch (NumberFormatException ex)
            {
                throw new IllegalArgumentException("Invalid octet spec: "+octetSpec, ex);
            }
        }
        
        /* ------------------------------------------------------------ */
        /**
         * Match specified octet value against the wildcard
         * 
         * @param value octet value
         * @return true if specified octet value matches the wildcard
         * @throws IllegalArgumentException if specified octet value is invalid
         */
        public boolean match(String value)
            throws IllegalArgumentException
        {
            if (value == null || value.trim().length() == 0)
                throw new IllegalArgumentException("Invalid octet: "+value);

            try
            {
                int number = Integer.parseInt(value);
                return match(number);
            }
            catch (NumberFormatException ex)
            {
                throw new IllegalArgumentException("Invalid octet: "+value);
            }
        }
        
        /* ------------------------------------------------------------ */
        /**
         * Match specified octet value against the wildcard
         * 
         * @param number octet value
         * @return true if specified octet value matches the wildcard
         * @throws IllegalArgumentException if specified octet value is invalid
         */
        public boolean match(int number)
            throws IllegalArgumentException
        {
            if (number < 0 || number > 255)
                throw new IllegalArgumentException("Invalid octet: "+number);
            
            return _mask.get(number);
        }
    }   
}

Back to the top