forked from AsyncHttpClient/async-http-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUriParser.java
377 lines (324 loc) · 11.9 KB
/
UriParser.java
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
/*
* Copyright (c) 2014-2024 AsyncHttpClient Project. All rights reserved.
*
* Licensed 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.asynchttpclient.uri;
import org.jspecify.annotations.Nullable;
import static java.util.Objects.requireNonNull;
import static org.asynchttpclient.util.MiscUtils.isNonEmpty;
final class UriParser {
public @Nullable String scheme;
public @Nullable String host;
public int port = -1;
public @Nullable String query;
public @Nullable String fragment;
private @Nullable String authority;
public String path = "";
public @Nullable String userInfo;
private final String originalUrl;
private int start, end, currentIndex;
private UriParser(final String originalUrl) {
this.originalUrl = originalUrl;
}
private void trimLeft() {
while (start < end && originalUrl.charAt(start) <= ' ') {
start++;
}
if (originalUrl.regionMatches(true, start, "url:", 0, 4)) {
start += 4;
}
}
private void trimRight() {
end = originalUrl.length();
while (end > 0 && originalUrl.charAt(end - 1) <= ' ') {
end--;
}
}
private boolean isFragmentOnly() {
return start < originalUrl.length() && originalUrl.charAt(start) == '#';
}
private static boolean isValidProtocolChar(char c) {
return Character.isLetterOrDigit(c) && c != '.' && c != '+' && c != '-';
}
private static boolean isValidProtocolChars(String protocol) {
for (int i = 1; i < protocol.length(); i++) {
if (!isValidProtocolChar(protocol.charAt(i))) {
return false;
}
}
return true;
}
private static boolean isValidProtocol(String protocol) {
return protocol.length() > 0 && Character.isLetter(protocol.charAt(0)) && isValidProtocolChars(protocol);
}
private void computeInitialScheme() {
for (int i = currentIndex; i < end; i++) {
char c = originalUrl.charAt(i);
if (c == ':') {
String s = originalUrl.substring(currentIndex, i);
if (isValidProtocol(s)) {
scheme = s.toLowerCase();
currentIndex = i + 1;
}
break;
} else if (c == '/') {
break;
}
}
}
private boolean overrideWithContext(@Nullable Uri context) {
boolean isRelative = false;
// use context only if schemes match
if (context != null && (scheme == null || scheme.equalsIgnoreCase(context.getScheme()))) {
// see RFC2396 5.2.3
String contextPath = context.getPath();
if (isNonEmpty(contextPath) && contextPath.charAt(0) == '/') {
scheme = null;
}
if (scheme == null) {
scheme = context.getScheme();
userInfo = context.getUserInfo();
host = context.getHost();
port = context.getPort();
path = contextPath;
isRelative = true;
}
}
return isRelative;
}
private int findWithinCurrentRange(char c) {
int pos = originalUrl.indexOf(c, currentIndex);
return pos > end ? -1 : pos;
}
private void trimFragment() {
int charpPosition = findWithinCurrentRange('#');
if (charpPosition >= 0) {
end = charpPosition;
if (charpPosition + 1 < originalUrl.length()) {
fragment = originalUrl.substring(charpPosition + 1);
}
}
}
// isRelative can be true only when context is not null
@SuppressWarnings("NullAway")
private void inheritContextQuery(@Nullable Uri context, boolean isRelative) {
// see RFC2396 5.2.2: query and fragment inheritance
if (isRelative && currentIndex == end) {
query = context.getQuery();
fragment = context.getFragment();
}
}
private boolean computeQuery() {
if (currentIndex < end) {
int askPosition = findWithinCurrentRange('?');
if (askPosition != -1) {
query = originalUrl.substring(askPosition + 1, end);
if (end > askPosition) {
end = askPosition;
}
return askPosition == currentIndex;
}
}
return false;
}
private boolean currentPositionStartsWith4Slashes() {
return originalUrl.regionMatches(currentIndex, "////", 0, 4);
}
private boolean currentPositionStartsWith2Slashes() {
return originalUrl.regionMatches(currentIndex, "//", 0, 2);
}
private String computeAuthority() {
int authorityEndPosition = findWithinCurrentRange('/');
if (authorityEndPosition == -1) {
authorityEndPosition = findWithinCurrentRange('?');
if (authorityEndPosition == -1) {
authorityEndPosition = end;
}
}
host = authority = originalUrl.substring(currentIndex, authorityEndPosition);
currentIndex = authorityEndPosition;
return authority;
}
private void computeUserInfo(String nonNullAuthority) {
int atPosition = nonNullAuthority.indexOf('@');
if (atPosition != -1) {
userInfo = nonNullAuthority.substring(0, atPosition);
host = nonNullAuthority.substring(atPosition + 1);
} else {
userInfo = null;
}
}
private static boolean isMaybeIPV6(String nonNullHost) {
// If the host is surrounded by [ and ] then it's an IPv6
// literal address as specified in RFC2732
return nonNullHost.length() > 0 && nonNullHost.charAt(0) == '[';
}
private void computeIPV6(String nonNullHost) {
int positionAfterClosingSquareBrace = nonNullHost.indexOf(']') + 1;
if (positionAfterClosingSquareBrace > 1) {
port = -1;
if (nonNullHost.length() > positionAfterClosingSquareBrace) {
if (nonNullHost.charAt(positionAfterClosingSquareBrace) == ':') {
// see RFC2396: port can be null
int portPosition = positionAfterClosingSquareBrace + 1;
if (nonNullHost.length() > portPosition) {
port = Integer.parseInt(nonNullHost.substring(portPosition));
}
} else {
throw new IllegalArgumentException("Invalid authority field: " + authority);
}
}
host = nonNullHost.substring(0, positionAfterClosingSquareBrace);
} else {
throw new IllegalArgumentException("Invalid authority field: " + authority);
}
}
private void computeRegularHostPort(String nonNullHost) {
int colonPosition = nonNullHost.indexOf(':');
port = -1;
if (colonPosition >= 0) {
// see RFC2396: port can be null
int portPosition = colonPosition + 1;
if (nonNullHost.length() > portPosition) {
port = Integer.parseInt(nonNullHost.substring(portPosition));
}
host = nonNullHost.substring(0, colonPosition);
}
}
// /./
private void removeEmbeddedDot() {
path = path.replace("/./", "/");
}
// /../
private void removeEmbedded2Dots() {
int i = 0;
while ((i = path.indexOf("/../", i)) >= 0) {
if (i > 0) {
end = path.lastIndexOf('/', i - 1);
if (end >= 0 && path.indexOf("/../", end) != 0) {
path = path.substring(0, end) + path.substring(i + 3);
i = 0;
} else if (end == 0) {
break;
}
} else {
i += 3;
}
}
}
private void removeTailing2Dots() {
while (path.endsWith("/..")) {
end = path.lastIndexOf('/', path.length() - 4);
if (end >= 0) {
path = path.substring(0, end + 1);
} else {
break;
}
}
}
private void removeStartingDot() {
if (path.startsWith("./") && path.length() > 2) {
path = path.substring(2);
}
}
private void removeTrailingDot() {
if (path.endsWith("/.")) {
path = path.substring(0, path.length() - 1);
}
}
private void handleRelativePath() {
int lastSlashPosition = path.lastIndexOf('/');
String pathEnd = originalUrl.substring(currentIndex, end);
if (lastSlashPosition == -1) {
path = authority != null ? '/' + pathEnd : pathEnd;
} else {
path = path.substring(0, lastSlashPosition + 1) + pathEnd;
}
}
private void handlePathDots() {
if (path.indexOf('.') != -1) {
removeEmbeddedDot();
removeEmbedded2Dots();
removeTailing2Dots();
removeStartingDot();
removeTrailingDot();
}
}
private void parseAuthority() {
if (!currentPositionStartsWith4Slashes() && currentPositionStartsWith2Slashes()) {
currentIndex += 2;
String nonNullAuthority = computeAuthority();
computeUserInfo(nonNullAuthority);
if (host != null) {
String nonNullHost = host;
if (isMaybeIPV6(nonNullHost)) {
computeIPV6(nonNullHost);
} else {
computeRegularHostPort(nonNullHost);
}
}
if (port < -1) {
throw new IllegalArgumentException("Invalid port number :" + port);
}
// see RFC2396 5.2.4: ignore context path if authority is defined
if (isNonEmpty(authority)) {
path = "";
}
}
}
private void computeRegularPath() {
if (originalUrl.charAt(currentIndex) == '/') {
path = originalUrl.substring(currentIndex, end);
} else if (isNonEmpty(path)) {
handleRelativePath();
} else {
String pathEnd = originalUrl.substring(currentIndex, end);
path = isNonEmpty(pathEnd) && pathEnd.charAt(0) != '/' ? '/' + pathEnd : pathEnd;
}
handlePathDots();
}
private void computeQueryOnlyPath() {
int lastSlashPosition = path.lastIndexOf('/');
path = lastSlashPosition < 0 ? "/" : path.substring(0, lastSlashPosition) + '/';
}
private void computePath(boolean queryOnly) {
// Parse the file path if any
if (currentIndex < end) {
computeRegularPath();
} else if (queryOnly) {
computeQueryOnlyPath();
}
}
private void parse(@Nullable Uri context) {
end = originalUrl.length();
trimLeft();
trimRight();
currentIndex = start;
if (!isFragmentOnly()) {
computeInitialScheme();
}
boolean isRelative = overrideWithContext(context);
trimFragment();
inheritContextQuery(context, isRelative);
boolean queryOnly = computeQuery();
parseAuthority();
computePath(queryOnly);
}
public static UriParser parse(@Nullable Uri context, final String originalUrl) {
requireNonNull(originalUrl, "originalUrl");
final UriParser parser = new UriParser(originalUrl);
parser.parse(context);
return parser;
}
}