File: StructuredField.java

package info (click to toggle)
tomcat11 11.0.11-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 47,028 kB
  • sloc: java: 366,244; xml: 55,681; jsp: 4,783; sh: 1,304; perl: 324; makefile: 25; ansic: 14
file content (595 lines) | stat: -rw-r--r-- 17,151 bytes parent folder | download | duplicates (5)
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.tomcat.util.http.parser;

import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.tomcat.util.res.StringManager;

/**
 * Parsing of structured fields as per RFC 8941.
 * <p>
 * The parsing implementation is complete but not all elements are currently exposed via getters. Additional getters
 * will be added as required as the use of structured fields expands.
 * <p>
 * The serialization of structured fields has not been implemented.
 */
public class StructuredField {

    private static final StringManager sm = StringManager.getManager(StructuredField.class);

    private static final int ARRAY_SIZE = 128;

    private static final boolean[] IS_KEY_FIRST = new boolean[ARRAY_SIZE];
    private static final boolean[] IS_KEY = new boolean[ARRAY_SIZE];
    private static final boolean[] IS_OWS = new boolean[ARRAY_SIZE];
    private static final boolean[] IS_BASE64 = new boolean[ARRAY_SIZE];
    private static final boolean[] IS_TOKEN = new boolean[ARRAY_SIZE];

    static {
        for (int i = 0; i < ARRAY_SIZE; i++) {
            if (i == '*' || i >= 'a' && i <= 'z') {
                IS_KEY_FIRST[i] = true;
                IS_KEY[i] = true;
            } else if (i >= '0' && i <= '9' || i == '_' || i == '-' || i == '.') {
                IS_KEY[i] = true;
            }
        }

        for (int i = 0; i < ARRAY_SIZE; i++) {
            if (i == 9 || i == ' ') {
                IS_OWS[i] = true;
            }
        }

        for (int i = 0; i < ARRAY_SIZE; i++) {
            if (i == '+' || i == '/' || i >= '0' && i <= '9' || i == '=' || i >= 'A' && i <= 'Z' ||
                    i >= 'a' && i <= 'z') {
                IS_BASE64[i] = true;
            }
        }

        for (int i = 0; i < ARRAY_SIZE; i++) {
            if (HttpParser.isToken(i) || i == ':' || i == '/') {
                IS_TOKEN[i] = true;
            }
        }
    }


    static SfList parseSfList(Reader input) throws IOException {
        skipSP(input);

        SfList result = new SfList();

        if (peek(input) != -1) {
            while (true) {
                SfListMember listMember = parseSfListMember(input);
                result.addListMember(listMember);
                skipOWS(input);
                if (peek(input) == -1) {
                    break;
                }
                requireChar(input, ',');
                skipOWS(input);
                requireNotChar(input, -1);
            }
        }

        skipSP(input);
        requireChar(input, -1);
        return result;
    }


    // Item or inner list
    static SfListMember parseSfListMember(Reader input) throws IOException {
        SfListMember listMember;
        if (peek(input) == '(') {
            listMember = parseSfInnerList(input);
        } else {
            listMember = parseSfBareItem(input);
        }
        parseSfParameters(input, listMember);
        return listMember;
    }


    static SfInnerList parseSfInnerList(Reader input) throws IOException {
        requireChar(input, '(');

        SfInnerList innerList = new SfInnerList();

        while (true) {
            skipSP(input);
            if (peek(input) == ')') {
                break;
            }
            SfItem<?> item = parseSfBareItem(input);
            parseSfParameters(input, item);
            innerList.addListItem(item);
            input.mark(1);
            requireChar(input, ' ', ')');
            input.reset();
        }
        requireChar(input, ')');

        return innerList;
    }


    static SfDictionary parseSfDictionary(Reader input) throws IOException {
        skipSP(input);

        SfDictionary result = new SfDictionary();

        if (peek(input) != -1) {
            while (true) {
                String key = parseSfKey(input);
                SfListMember listMember;
                input.mark(1);
                int c = input.read();
                if (c == '=') {
                    listMember = parseSfListMember(input);
                } else {
                    listMember = new SfBoolean(true);
                    input.reset();
                }
                parseSfParameters(input, listMember);
                result.addDictionaryMember(key, listMember);
                skipOWS(input);
                if (peek(input) == -1) {
                    break;
                }
                requireChar(input, ',');
                skipOWS(input);
                requireNotChar(input, -1);
            }
        }

        skipSP(input);
        requireChar(input, -1);
        return result;
    }


    static SfItem<?> parseSfItem(Reader input) throws IOException {
        skipSP(input);

        SfItem<?> item = parseSfBareItem(input);
        parseSfParameters(input, item);

        skipSP(input);
        requireChar(input, -1);
        return item;
    }


    static SfItem<?> parseSfBareItem(Reader input) throws IOException {
        int c = input.read();

        SfItem<?> item;
        if (c == '-' || HttpParser.isNumeric(c)) {
            item = parseSfNumeric(input, c);
        } else if (c == '\"') {
            item = parseSfString(input);
        } else if (c == '*' || HttpParser.isAlpha(c)) {
            item = parseSfToken(input, c);
        } else if (c == ':') {
            item = parseSfByteSequence(input);
        } else if (c == '?') {
            item = parseSfBoolean(input);
        } else {
            throw new IllegalArgumentException(
                    sm.getString("sf.bareitem.invalidCharacter", String.format("\\u%04X", Integer.valueOf(c))));
        }

        return item;
    }


    static void parseSfParameters(Reader input, SfListMember listMember) throws IOException {
        while (peek(input) == ';') {
            requireChar(input, ';');
            skipSP(input);
            String key = parseSfKey(input);
            SfItem<?> item;
            input.mark(1);
            int c = input.read();
            if (c == '=') {
                item = parseSfBareItem(input);
            } else {
                item = new SfBoolean(true);
                input.reset();
            }
            listMember.addParameter(key, item);
        }
    }


    static String parseSfKey(Reader input) throws IOException {
        StringBuilder result = new StringBuilder();

        input.mark(1);
        int c = input.read();
        if (!isKeyFirst(c)) {
            throw new IllegalArgumentException(
                    sm.getString("sf.key.invalidFirstCharacter", String.format("\\u%04X", Integer.valueOf(c))));
        }

        while (c != -1 && isKey(c)) {
            result.append((char) c);
            input.mark(1);
            c = input.read();
        }
        input.reset();
        return result.toString();
    }


    static SfItem<?> parseSfNumeric(Reader input, int first) throws IOException {
        int sign = 1;
        boolean integer = true;
        int decimalPos = 0;

        StringBuilder result = new StringBuilder();

        int c;
        if (first == '-') {
            sign = -1;
            c = input.read();
        } else {
            c = first;
        }

        if (!HttpParser.isNumeric(c)) {
            throw new IllegalArgumentException(
                    sm.getString("sf.numeric.invalidCharacter", String.format("\\u%04X", Integer.valueOf(c))));
        }
        result.append((char) c);
        input.mark(1);
        c = input.read();

        while (c != -1) {
            if (HttpParser.isNumeric(c)) {
                result.append((char) c);
            } else if (integer && c == '.') {
                if (result.length() > 12) {
                    throw new IllegalArgumentException(sm.getString("sf.numeric.integralPartTooLong"));
                }
                integer = false;
                result.append((char) c);
                decimalPos = result.length();
            } else {
                input.reset();
                break;
            }
            if (integer && result.length() > 15) {
                throw new IllegalArgumentException(sm.getString("sf.numeric.integerTooLong"));
            }
            if (!integer && result.length() > 16) {
                throw new IllegalArgumentException(sm.getString("sf.numeric.decimalTooLong"));
            }
            input.mark(1);
            c = input.read();
        }

        if (integer) {
            return new SfInteger(Long.parseLong(result.toString()) * sign);
        }

        if (result.charAt(result.length() - 1) == '.') {
            throw new IllegalArgumentException(sm.getString("sf.numeric.decimalInvalidFinal"));
        }

        if (result.length() - decimalPos > 3) {
            throw new IllegalArgumentException(sm.getString("sf.numeric.decimalPartTooLong"));
        }

        return new SfDecimal(Double.parseDouble(result.toString()) * sign);
    }


    static SfString parseSfString(Reader input) throws IOException {
        // It is known first character was '"'
        StringBuilder result = new StringBuilder();

        while (true) {
            int c = input.read();
            if (c == '\\') {
                requireNotChar(input, -1);
                c = input.read();
                if (c != '\\' && c != '\"') {
                    throw new IllegalArgumentException(
                            sm.getString("sf.string.invalidEscape", String.format("\\u%04X", Integer.valueOf(c))));
                }
            } else {
                if (c == '\"') {
                    break;
                }
                // This test also covers unexpected EOF
                if (c < 32 || c > 126) {
                    throw new IllegalArgumentException(
                            sm.getString("sf.string.invalidCharacter", String.format("\\u%04X", Integer.valueOf(c))));
                }
            }
            result.append((char) c);
        }

        return new SfString(result.toString());
    }


    static SfToken parseSfToken(Reader input, int first) throws IOException {
        // It is known first character is valid
        StringBuilder result = new StringBuilder();

        result.append((char) first);
        while (true) {
            input.mark(1);
            int c = input.read();
            if (!isToken(c)) {
                input.reset();
                break;
            }
            result.append((char) c);
        }

        return new SfToken(result.toString());
    }


    static SfByteSequence parseSfByteSequence(Reader input) throws IOException {
        // It is known first character was ':'
        StringBuilder base64 = new StringBuilder();

        while (true) {
            int c = input.read();

            if (c == ':') {
                break;
            } else if (isBase64(c)) {
                base64.append((char) c);
            } else {
                throw new IllegalArgumentException(
                        sm.getString("sf.base64.invalidCharacter", String.format("\\u%04X", Integer.valueOf(c))));
            }
        }

        return new SfByteSequence(Base64.getDecoder().decode(base64.toString()));
    }


    static SfBoolean parseSfBoolean(Reader input) throws IOException {
        // It is known first character was '?'
        int c = input.read();

        if (c == '1') {
            return new SfBoolean(true);
        } else if (c == '0') {
            return new SfBoolean(false);
        } else {
            throw new IllegalArgumentException(
                    sm.getString("sf.boolean.invalidCharacter", String.format("\\u%04X", Integer.valueOf(c))));
        }
    }


    static void skipSP(Reader input) throws IOException {
        input.mark(1);
        int c = input.read();
        while (c == 32) {
            input.mark(1);
            c = input.read();
        }
        input.reset();
    }


    static void skipOWS(Reader input) throws IOException {
        input.mark(1);
        int c = input.read();
        while (isOws(c)) {
            input.mark(1);
            c = input.read();
        }
        input.reset();
    }


    static void requireChar(Reader input, int... required) throws IOException {
        int c = input.read();
        for (int r : required) {
            if (c == r) {
                return;
            }
        }
        throw new IllegalArgumentException(
                sm.getString("sf.invalidCharacter", String.format("\\u%04X", Integer.valueOf(c))));
    }


    static void requireNotChar(Reader input, int required) throws IOException {
        input.mark(1);
        int c = input.read();
        if (c == required) {
            throw new IllegalArgumentException(
                    sm.getString("sf.invalidCharacter", String.format("\\u%04X", Integer.valueOf(c))));
        }
        input.reset();
    }


    static int peek(Reader input) throws IOException {
        input.mark(1);
        int c = input.read();
        input.reset();
        return c;
    }


    static boolean isKeyFirst(int c) {
        try {
            return IS_KEY_FIRST[c];
        } catch (ArrayIndexOutOfBoundsException ex) {
            return false;
        }
    }


    static boolean isKey(int c) {
        try {
            return IS_KEY[c];
        } catch (ArrayIndexOutOfBoundsException ex) {
            return false;
        }
    }


    static boolean isOws(int c) {
        try {
            return IS_OWS[c];
        } catch (ArrayIndexOutOfBoundsException ex) {
            return false;
        }
    }


    static boolean isBase64(int c) {
        try {
            return IS_BASE64[c];
        } catch (ArrayIndexOutOfBoundsException ex) {
            return false;
        }
    }


    static boolean isToken(int c) {
        try {
            return IS_TOKEN[c];
        } catch (ArrayIndexOutOfBoundsException ex) {
            return false;
        }
    }


    private StructuredField() {
        // Utility class. Hide default constructor.
    }


    static class SfDictionary {
        private final Map<String,SfListMember> dictionary = new LinkedHashMap<>();

        void addDictionaryMember(String key, SfListMember value) {
            dictionary.put(key, value);
        }

        SfListMember getDictionaryMember(String key) {
            return dictionary.get(key);
        }
    }

    static class SfList {
        private final List<SfListMember> listMembers = new ArrayList<>();

        void addListMember(SfListMember listMember) {
            listMembers.add(listMember);
        }
    }

    static class SfListMember {
        private Map<String,SfItem<?>> parameters = null;

        void addParameter(String key, SfItem<?> value) {
            if (parameters == null) {
                parameters = new LinkedHashMap<>();
            }
            parameters.put(key, value);
        }
    }

    static class SfInnerList extends SfListMember {
        List<SfItem<?>> listItems = new ArrayList<>();

        SfInnerList() {
            // Default constructor is NO-OP
        }

        void addListItem(SfItem<?> item) {
            listItems.add(item);
        }

        List<SfItem<?>> getListItem() {
            return listItems;
        }
    }

    abstract static class SfItem<T> extends SfListMember {
        private final T value;

        SfItem(T value) {
            this.value = value;
        }

        T getVaue() {
            return value;
        }
    }

    static class SfInteger extends SfItem<Long> {
        SfInteger(long value) {
            super(Long.valueOf(value));
        }
    }

    static class SfDecimal extends SfItem<Double> {
        SfDecimal(double value) {
            super(Double.valueOf(value));
        }
    }

    static class SfString extends SfItem<String> {
        SfString(String value) {
            super(value);
        }
    }

    static class SfToken extends SfItem<String> {
        SfToken(String value) {
            super(value);
        }
    }

    static class SfByteSequence extends SfItem<byte[]> {
        SfByteSequence(byte[] value) {
            super(value);
        }
    }

    static class SfBoolean extends SfItem<Boolean> {
        SfBoolean(boolean value) {
            super(Boolean.valueOf(value));
        }
    }
}