Use YangNames CharMatchers
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / ApiPathParser.java
1 /*
2  * Copyright (c) 2021 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.restconf.nb.rfc8040;
9
10 import static com.google.common.base.Verify.verify;
11 import static com.google.common.base.Verify.verifyNotNull;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.ImmutableList.Builder;
16 import java.text.ParseException;
17 import java.util.function.Supplier;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.opendaylight.restconf.nb.rfc8040.ApiPath.ApiIdentifier;
21 import org.opendaylight.restconf.nb.rfc8040.ApiPath.ListInstance;
22 import org.opendaylight.restconf.nb.rfc8040.ApiPath.Step;
23 import org.opendaylight.yangtools.yang.common.YangNames;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 /**
28  * Parser for a sequence of {@link ApiPath}'s {@link Step}s.
29  */
30 class ApiPathParser {
31     private static final Logger LOG = LoggerFactory.getLogger(ApiPathParser.class);
32
33     /**
34      * A lenient interpretation: '//' is '/', i.e. there is no segment.
35      */
36     private static final class Lenient extends ApiPathParser {
37         @Override
38         int parseStep(final String str, final int offset, final int limit) throws ParseException {
39             return offset == limit ? limit : super.parseStep(str, offset, limit);
40         }
41     }
42
43     /**
44      * A lenient interpretation: '//' is '/', i.e. there is no segment, but also log offenders
45      */
46     private static final class Logging extends ApiPathParser {
47         @FunctionalInterface
48         private interface LogMethod {
49             void logLeniency(String format, Object arg0, Object arg1);
50         }
51
52         private final LogMethod method;
53
54         Logging(final LogMethod method) {
55             this.method = requireNonNull(method);
56         }
57
58         @Override
59         int parseStep(final String str, final int offset, final int limit) throws ParseException {
60             if (offset == limit) {
61                 method.logLeniency("Ignoring duplicate slash in '{}' at offset", str, offset);
62                 return limit;
63             }
64             return super.parseStep(str, offset, limit);
65         }
66     }
67
68     private static final Supplier<@NonNull ApiPathParser> URL_FACTORY;
69
70     static {
71         // Select the correct parser implementation where consecutive slashes are concerned. We default to lenient
72         // interpretation and treat them as a single slash, but allow this to be overridden through a system property.
73         // FIXME: 3.0.0: make "reject" the default
74         final String prop = System.getProperty("org.opendaylight.restconf.url.consecutive-slashes", "allow");
75         final String treatment;
76         switch (prop) {
77             case "allow":
78                 treatment = "are treated as a single slash";
79                 URL_FACTORY = Lenient::new;
80                 break;
81             case "debug":
82                 treatment = "are treated as a single slash and will be logged";
83                 URL_FACTORY = () -> new Logging(LOG::debug);
84                 break;
85             case "warn":
86                 treatment = "are treated as a single slash and will be warned about";
87                 URL_FACTORY = () -> new Logging(LOG::warn);
88                 break;
89             case "reject":
90                 treatment = "will be rejected";
91                 URL_FACTORY = ApiPathParser::new;
92                 break;
93             default:
94                 LOG.warn("Unknown property value '{}', assuming 'reject'", prop);
95                 treatment = "will be rejected";
96                 URL_FACTORY = ApiPathParser::new;
97         }
98
99         LOG.info("Consecutive slashes in REST URLs {}", treatment);
100     }
101
102     private final Builder<Step> steps = ImmutableList.builder();
103
104     /*
105      * State tracking for creating substrings:
106      *
107      * Usually we copy spans 'src', in which case subStart captures 'start' argument to String.substring(...).
108      * If we encounter a percent escape we need to interpret as part of the string, we start building the string in
109      * subBuilder -- in which case subStart is set to -1.
110      *
111      * Note that StringBuilder is lazily-instantiated, as we have no percents at all
112      */
113     private int subStart;
114     private StringBuilder subBuilder;
115
116     // Lazily-allocated when we need to decode UTF-8. Since we touch this only when we are not expecting
117     private Utf8Buffer buf;
118
119     // the offset of the character returned from last peekBasicLatin()
120     private int nextOffset;
121
122     private ApiPathParser() {
123         // Hidden on purpose
124     }
125
126     static @NonNull ApiPathParser newStrict() {
127         return new ApiPathParser();
128     }
129
130     static @NonNull ApiPathParser newUrl() {
131         return URL_FACTORY.get();
132     }
133
134     // Grammar:
135     //   steps : step ("/" step)*
136     final @NonNull ImmutableList<@NonNull Step> parseSteps(final String str) throws ParseException {
137         int idx = 0;
138
139         // First process while we are seeing a slash
140         while (true) {
141             final int slash = str.indexOf('/', idx);
142             if (slash != -1) {
143                 final int next = parseStep(str, idx, slash);
144                 verify(next == slash, "Unconsumed bytes: %s next %s limit", next, slash);
145                 idx = next + 1;
146             } else {
147                 break;
148             }
149         }
150
151         // Now process the tail of the string
152         final int length = str.length();
153         final int next = parseStep(str, idx, length);
154         verify(next == length, "Unconsumed trailing bytes: %s next %s limit", next, length);
155
156         return steps.build();
157     }
158
159     // Grammar:
160     //   step : identifier (":" identifier)? ("=" key-value ("," key-value)*)?
161     // Note: visible for subclasses
162     int parseStep(final String str, final int offset, final int limit) throws ParseException {
163         int idx = startIdentifier(str, offset, limit);
164         while (idx < limit) {
165             final char ch = peekBasicLatin(str, idx, limit);
166             if (ch == ':') {
167                 return parseStep(endSub(str, idx), str, nextOffset, limit);
168             } else if (ch == '=') {
169                 return parseStep(null, endSub(str, idx), str, nextOffset, limit);
170             }
171             idx = continueIdentifer(idx, ch);
172         }
173
174         steps.add(new ApiIdentifier(null, endSub(str, idx)));
175         return idx;
176     }
177
178     // Starting at second identifier
179     private int parseStep(final @Nullable String module, final String str, final int offset, final int limit)
180             throws ParseException {
181         int idx = startIdentifier(str, offset, limit);
182         while (idx < limit) {
183             final char ch = peekBasicLatin(str, idx, limit);
184             if (ch == '=') {
185                 return parseStep(module, endSub(str, idx), str, nextOffset, limit);
186             }
187             idx = continueIdentifer(idx, ch);
188         }
189
190         steps.add(new ApiIdentifier(module, endSub(str, idx)));
191         return idx;
192     }
193
194     // Starting at first key-value
195     private int parseStep(final @Nullable String module, final @NonNull String identifier,
196             final String str, final int offset, final int limit) throws ParseException {
197         final var values = ImmutableList.<String>builder();
198
199         startSub(offset);
200         int idx = offset;
201         while (idx < limit) {
202             final char ch = str.charAt(idx);
203             if (ch == ',') {
204                 values.add(endSub(str, idx));
205                 startSub(++idx);
206             } else if (ch != '%') {
207                 append(ch);
208                 idx++;
209             } else {
210                 // Save current string content and capture current index for reporting
211                 final var sb = flushSub(str, idx);
212                 final int errorOffset = idx;
213
214                 var utf = buf;
215                 if (utf == null) {
216                     buf = utf = new Utf8Buffer();
217                 }
218
219                 do {
220                     utf.appendByte(parsePercent(str, idx, limit));
221                     idx += 3;
222                 } while (idx < limit && str.charAt(idx) == '%');
223
224                 utf.flushTo(sb, errorOffset);
225             }
226         }
227
228         steps.add(new ListInstance(module, identifier, values.add(endSub(str, idx)).build()));
229         return idx;
230     }
231
232     private int startIdentifier(final String str, final int offset, final int limit) throws ParseException {
233         if (offset == limit) {
234             throw new ParseException("Identifier may not be empty", offset);
235         }
236
237         startSub(offset);
238         final char ch = peekBasicLatin(str, offset, limit);
239         if (!YangNames.IDENTIFIER_START.matches(ch)) {
240             throw new ParseException("Expecting [a-zA-Z_], not '" + ch + "'", offset);
241         }
242         append(ch);
243         return nextOffset;
244     }
245
246     private int continueIdentifer(final int offset, final char ch) throws ParseException {
247         if (YangNames.NOT_IDENTIFIER_PART.matches(ch)) {
248             throw new ParseException("Expecting [a-zA-Z_.-], not '" + ch + "'", offset);
249         }
250         append(ch);
251         return nextOffset;
252     }
253
254     // Assert current character comes from the Basic Latin block, i.e. 00-7F.
255     // Callers are expected to pick up 'nextIdx' to resume parsing at the next character
256     private char peekBasicLatin(final String str, final int offset, final int limit) throws ParseException {
257         final char ch = str.charAt(offset);
258         if (ch == '%') {
259             final byte b = parsePercent(str, offset, limit);
260             if (b < 0) {
261                 throw new ParseException("Expecting %00-%7F, not " + str.substring(offset, limit), offset);
262             }
263
264             flushSub(str, offset);
265             nextOffset = offset + 3;
266             return (char) b;
267         }
268
269         if (ch < 0 || ch > 127) {
270             throw new ParseException("Unexpected character '" + ch + "'", offset);
271         }
272         nextOffset = offset + 1;
273         return ch;
274     }
275
276     private void startSub(final int offset) {
277         subStart = offset;
278     }
279
280     private void append(final char ch) {
281         // We are not reusing string, append the char, otherwise
282         if (subStart == -1) {
283             verifyNotNull(subBuilder).append(ch);
284         }
285     }
286
287     private @NonNull String endSub(final String str, final int end) {
288         return subStart != -1 ? str.substring(subStart, end) : verifyNotNull(subBuilder).toString();
289     }
290
291     private @NonNull StringBuilder flushSub(final String str, final int end) {
292         var sb = subBuilder;
293         if (sb == null) {
294             subBuilder = sb = new StringBuilder();
295         }
296         if (subStart != -1) {
297             sb.setLength(0);
298             sb.append(str, subStart, end);
299             subStart = -1;
300         }
301         return sb;
302     }
303
304     private static byte parsePercent(final String str, final int offset, final int limit) throws ParseException {
305         if (limit - offset < 3) {
306             throw new ParseException("Incomplete escape '" + str.substring(offset, limit) + "'", offset);
307         }
308         return (byte) (parseHex(str, offset + 1) << 4 | parseHex(str, offset + 2));
309     }
310
311     // FIXME: Replace with HexFormat.fromHexDigit(str.charAt(offset)) when we have JDK17+
312     private static int parseHex(final String str, final int offset) throws ParseException {
313         final char ch = str.charAt(offset);
314         if (ch >= '0' && ch <= '9') {
315             return ch - '0';
316         }
317
318         final int zero;
319         if (ch >= 'a' && ch <= 'f') {
320             zero = 'a';
321         } else if (ch >= 'A' && ch <= 'F') {
322             zero = 'A';
323         } else {
324             throw new ParseException("Invalid escape character '" + ch + "'", offset);
325         }
326
327         return ch - zero + 10;
328     }
329 }