View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.codec.net;
19  
20  import java.nio.ByteBuffer;
21  import java.util.BitSet;
22  
23  import org.apache.commons.codec.BinaryDecoder;
24  import org.apache.commons.codec.BinaryEncoder;
25  import org.apache.commons.codec.DecoderException;
26  import org.apache.commons.codec.EncoderException;
27  
28  /**
29   * Implements the Percent-Encoding scheme, as described in HTTP 1.1 specification. For extensibility, an array of
30   * special US-ASCII characters can be specified in order to perform proper URI encoding for the different parts
31   * of the URI.
32   * <p>
33   * This class is immutable. It is also thread-safe besides using BitSet which is not thread-safe, but its public
34   * interface only call the access
35   * </p>
36   *
37   * @see <a href="https://tools.ietf.org/html/rfc3986#section-2.1">Percent-Encoding</a>
38   * @since 1.12
39   */
40  public class PercentCodec implements BinaryEncoder, BinaryDecoder {
41  
42      /**
43       * The escape character used by the Percent-Encoding in order to introduce an encoded character.
44       */
45      private static final byte ESCAPE_CHAR = '%';
46  
47      /**
48       * The plus character used to encode spaces when plusForSpace is true.
49       */
50      private static final byte PLUS_CHAR = '+';
51  
52      /**
53       * The bit set used to store the character that should be always encoded.
54       */
55      private final BitSet alwaysEncodeChars = new BitSet();
56  
57      /**
58       * The flag defining if the space character should be encoded as '+'.
59       */
60      private final boolean plusForSpace;
61  
62      /**
63       * The minimum and maximum code of the bytes that is inserted in the bit set, used to prevent look-ups
64       */
65      private int alwaysEncodeCharsMin = Integer.MAX_VALUE, alwaysEncodeCharsMax = Integer.MIN_VALUE;
66  
67      /**
68       * Constructs a Percent coded that will encode all the non US-ASCII characters using the Percent-Encoding
69       * while it will not encode all the US-ASCII characters, except for character '%' that is used as escape
70       * character for Percent-Encoding.
71       */
72      public PercentCodec() {
73          this.plusForSpace = false;
74          insertAlwaysEncodeChar(ESCAPE_CHAR);
75      }
76  
77      /**
78       * Constructs a Percent codec by specifying the characters that belong to US-ASCII that should
79       * always be encoded. The rest US-ASCII characters will not be encoded, except for character '%' that
80       * is used as escape character for Percent-Encoding.
81       *
82       * @param alwaysEncodeChars The unsafe characters that should always be encoded.
83       * @param plusForSpace      The flag defining if the space character should be encoded as '+'.
84       */
85      public PercentCodec(final byte[] alwaysEncodeChars, final boolean plusForSpace) {
86          this.plusForSpace = plusForSpace;
87          insertAlwaysEncodeChars(alwaysEncodeChars);
88          if (plusForSpace) {
89              insertAlwaysEncodeChar(PLUS_CHAR);
90          }
91      }
92  
93      private boolean canEncode(final byte c) {
94          return !isAsciiChar(c) || inAlwaysEncodeCharsRange(c) && alwaysEncodeChars.get(c);
95      }
96  
97      private boolean containsSpace(final byte[] bytes) {
98          for (final byte b : bytes) {
99              if (b == ' ') {
100                 return true;
101             }
102         }
103         return false;
104     }
105 
106     /**
107      * Decodes bytes encoded with Percent-Encoding based on RFC 3986. The reverse process is performed in order to
108      * decode the encoded characters to Unicode.
109      */
110     @Override
111     public byte[] decode(final byte[] bytes) throws DecoderException {
112         if (bytes == null) {
113             return null;
114         }
115         final ByteBuffer buffer = ByteBuffer.allocate(expectedDecodingBytes(bytes));
116         for (int i = 0; i < bytes.length; i++) {
117             final byte b = bytes[i];
118             if (b == ESCAPE_CHAR) {
119                 try {
120                     final int u = Utils.digit16(bytes[++i]);
121                     final int l = Utils.digit16(bytes[++i]);
122                     buffer.put((byte) ((u << 4) + l));
123                 } catch (final ArrayIndexOutOfBoundsException e) {
124                     throw new DecoderException("Invalid percent decoding: ", e);
125                 }
126             } else if (plusForSpace && b == '+') {
127                 buffer.put((byte) ' ');
128             } else {
129                 buffer.put(b);
130             }
131         }
132         return buffer.array();
133     }
134 
135     /**
136      * Decodes a byte[] Object, whose bytes are encoded with Percent-Encoding.
137      *
138      * @param obj The object to decode.
139      * @return The decoding result byte[] as Object.
140      * @throws DecoderException Thrown if the object is not a byte array.
141      */
142     @Override
143     public Object decode(final Object obj) throws DecoderException {
144         if (obj == null) {
145             return null;
146         }
147         if (obj instanceof byte[]) {
148             return decode((byte[]) obj);
149         }
150         throw new DecoderException("Objects of type " + obj.getClass().getName() + " cannot be Percent decoded");
151     }
152 
153     private byte[] doEncode(final byte[] bytes, final int expectedLength, final boolean willEncode) {
154         final ByteBuffer buffer = ByteBuffer.allocate(expectedLength);
155         for (final byte b : bytes) {
156             if (willEncode && canEncode(b)) {
157                 byte bb = b;
158                 if (bb < 0) {
159                     bb = (byte) (256 + bb);
160                 }
161                 final char hex1 = Utils.hexChar(bb >> 4);
162                 final char hex2 = Utils.hexChar(bb);
163                 buffer.put(ESCAPE_CHAR);
164                 buffer.put((byte) hex1);
165                 buffer.put((byte) hex2);
166             } else if (plusForSpace && b == ' ') {
167                 buffer.put((byte) '+');
168             } else {
169                 buffer.put(b);
170             }
171         }
172         return buffer.array();
173     }
174 
175     /**
176      * Percent-Encoding based on RFC 3986. The non US-ASCII characters are encoded, as well as the
177      * US-ASCII characters that are configured to be always encoded.
178      */
179     @Override
180     public byte[] encode(final byte[] bytes) throws EncoderException {
181         if (bytes == null) {
182             return null;
183         }
184         final int expectedEncodingBytes = expectedEncodingBytes(bytes);
185         final boolean willEncode = expectedEncodingBytes != bytes.length;
186         if (willEncode || plusForSpace && containsSpace(bytes)) {
187             return doEncode(bytes, expectedEncodingBytes, willEncode);
188         }
189         return bytes;
190     }
191 
192     /**
193      * Encodes an object into using the Percent-Encoding. Only byte[] objects are accepted.
194      *
195      * @param obj The object to encode.
196      * @return The encoding result byte[] as Object.
197      * @throws EncoderException Thrown if the object is not a byte array.
198      */
199     @Override
200     public Object encode(final Object obj) throws EncoderException {
201         if (obj == null) {
202             return null;
203         }
204         if (obj instanceof byte[]) {
205             return encode((byte[]) obj);
206         }
207         throw new EncoderException("Objects of type " + obj.getClass().getName() + " cannot be Percent encoded");
208     }
209 
210     private int expectedDecodingBytes(final byte[] bytes) {
211         int byteCount = 0;
212         for (int i = 0; i < bytes.length;) {
213             final byte b = bytes[i];
214             i += b == ESCAPE_CHAR ? 3 : 1;
215             byteCount++;
216         }
217         return byteCount;
218     }
219 
220     private int expectedEncodingBytes(final byte[] bytes) {
221         int byteCount = 0;
222         for (final byte b : bytes) {
223             byteCount += canEncode(b) ? 3 : 1;
224         }
225         return byteCount;
226     }
227 
228     private boolean inAlwaysEncodeCharsRange(final byte c) {
229         return c >= alwaysEncodeCharsMin && c <= alwaysEncodeCharsMax;
230     }
231 
232     /**
233      * Inserts a single character into a BitSet and maintains the min and max of the characters of the
234      * {@code BitSet alwaysEncodeChars} in order to avoid look-ups when a byte is out of this range.
235      *
236      * @param b The byte that is candidate for min and max limit.
237      */
238     private void insertAlwaysEncodeChar(final byte b) {
239         if (b < 0) {
240             throw new IllegalArgumentException("byte must be >= 0");
241         }
242         this.alwaysEncodeChars.set(b);
243         if (b < alwaysEncodeCharsMin) {
244             alwaysEncodeCharsMin = b;
245         }
246         if (b > alwaysEncodeCharsMax) {
247             alwaysEncodeCharsMax = b;
248         }
249     }
250 
251     /**
252      * Inserts the byte array into a BitSet for faster lookup.
253      *
254      * @param alwaysEncodeCharsArray The byte array into a BitSet for faster lookup.
255      */
256     private void insertAlwaysEncodeChars(final byte[] alwaysEncodeCharsArray) {
257         if (alwaysEncodeCharsArray != null) {
258             for (final byte b : alwaysEncodeCharsArray) {
259                 insertAlwaysEncodeChar(b);
260             }
261         }
262         insertAlwaysEncodeChar(ESCAPE_CHAR);
263     }
264 
265     private boolean isAsciiChar(final byte c) {
266         return c >= 0;
267     }
268 }