forked from apache/dubbo
/
URLStrParser.java
361 lines (319 loc) · 12.8 KB
/
URLStrParser.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
/*
* 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.dubbo.common;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX;
import static org.apache.dubbo.common.utils.StringUtils.EMPTY_STRING;
import static org.apache.dubbo.common.utils.StringUtils.decodeHexByte;
import static org.apache.dubbo.common.utils.Utf8Utils.decodeUtf8;
public final class URLStrParser {
private static final char SPACE = 0x20;
private static final ThreadLocal<TempBuf> DECODE_TEMP_BUF = ThreadLocal.withInitial(() -> new TempBuf(1024));
private URLStrParser() {
//empty
}
/**
* @param decodedURLStr : after {@link URL#decode} string
* decodedURLStr format: protocol://username:password@host:port/path?k1=v1&k2=v2
* [protocol://][username:password@][host:port]/[path][?k1=v1&k2=v2]
*/
public static URL parseDecodedStr(String decodedURLStr) {
Map<String, String> parameters = null;
int pathEndIdx = decodedURLStr.indexOf('?');
if (pathEndIdx >= 0) {
parameters = parseDecodedParams(decodedURLStr, pathEndIdx + 1);
} else {
pathEndIdx = decodedURLStr.length();
}
String decodedBody = decodedURLStr.substring(0, pathEndIdx);
return parseURLBody(decodedURLStr, decodedBody, parameters);
}
private static Map<String, String> parseDecodedParams(String str, int from) {
int len = str.length();
if (from >= len) {
return Collections.emptyMap();
}
TempBuf tempBuf = DECODE_TEMP_BUF.get();
Map<String, String> params = new HashMap<>();
int nameStart = from;
int valueStart = -1;
int i;
for (i = from; i < len; i++) {
char ch = str.charAt(i);
switch (ch) {
case '=':
if (nameStart == i) {
nameStart = i + 1;
} else if (valueStart < nameStart) {
valueStart = i + 1;
}
break;
case ';':
case '&':
addParam(str, false, nameStart, valueStart, i, params, tempBuf);
nameStart = i + 1;
break;
default:
// continue
}
}
addParam(str, false, nameStart, valueStart, i, params, tempBuf);
return params;
}
/**
* @param fullURLStr : fullURLString
* @param decodedBody : format: [protocol://][username:password@][host:port]/[path]
* @param parameters :
* @return URL
*/
private static URL parseURLBody(String fullURLStr, String decodedBody, Map<String, String> parameters) {
int starIdx = 0, endIdx = decodedBody.length();
// ignore the url content following '#'
int poundIndex = decodedBody.indexOf('#');
if (poundIndex != -1) {
endIdx = poundIndex;
}
String protocol = null;
int protoEndIdx = decodedBody.indexOf("://");
if (protoEndIdx >= 0) {
if (protoEndIdx == 0) {
throw new IllegalStateException("url missing protocol: \"" + fullURLStr + "\"");
}
protocol = decodedBody.substring(0, protoEndIdx);
starIdx = protoEndIdx + 3;
} else {
// case: file:/path/to/file.txt
protoEndIdx = decodedBody.indexOf(":/");
if (protoEndIdx >= 0) {
if (protoEndIdx == 0) {
throw new IllegalStateException("url missing protocol: \"" + fullURLStr + "\"");
}
protocol = decodedBody.substring(0, protoEndIdx);
starIdx = protoEndIdx + 1;
}
}
String path = null;
int pathStartIdx = indexOf(decodedBody, '/', starIdx, endIdx);
if (pathStartIdx >= 0) {
path = decodedBody.substring(pathStartIdx + 1, endIdx);
endIdx = pathStartIdx;
}
String username = null;
String password = null;
int pwdEndIdx = lastIndexOf(decodedBody, '@', starIdx, endIdx);
if (pwdEndIdx > 0) {
int userNameEndIdx = indexOf(decodedBody, ':', starIdx, pwdEndIdx);
username = decodedBody.substring(starIdx, userNameEndIdx);
password = decodedBody.substring(userNameEndIdx + 1, pwdEndIdx);
starIdx = pwdEndIdx + 1;
}
String host = null;
int port = 0;
int hostEndIdx = lastIndexOf(decodedBody, ':', starIdx, endIdx);
if (hostEndIdx > 0 && hostEndIdx < decodedBody.length() - 1) {
if (lastIndexOf(decodedBody, '%', starIdx, endIdx) > hostEndIdx) {
// ipv6 address with scope id
// e.g. fe80:0:0:0:894:aeec:f37d:23e1%en0
// see https://howdoesinternetwork.com/2013/ipv6-zone-id
// ignore
} else {
port = Integer.parseInt(decodedBody.substring(hostEndIdx + 1, endIdx));
endIdx = hostEndIdx;
}
}
if (endIdx > starIdx) {
host = decodedBody.substring(starIdx, endIdx);
}
return new URL(protocol, username, password, host, port, path, parameters);
}
/**
* @param encodedURLStr : after {@link URL#encode(String)} string
* encodedURLStr after decode format: protocol://username:password@host:port/path?k1=v1&k2=v2
* [protocol://][username:password@][host:port]/[path][?k1=v1&k2=v2]
*/
public static URL parseEncodedStr(String encodedURLStr) {
Map<String, String> parameters = null;
int pathEndIdx = encodedURLStr.toUpperCase().indexOf("%3F");// '?'
if (pathEndIdx >= 0) {
parameters = parseEncodedParams(encodedURLStr, pathEndIdx + 3);
} else {
pathEndIdx = encodedURLStr.length();
}
//decodedBody format: [protocol://][username:password@][host:port]/[path]
String decodedBody = decodeComponent(encodedURLStr, 0, pathEndIdx, false, DECODE_TEMP_BUF.get());
return parseURLBody(encodedURLStr, decodedBody, parameters);
}
private static Map<String, String> parseEncodedParams(String str, int from) {
int len = str.length();
if (from >= len) {
return Collections.emptyMap();
}
TempBuf tempBuf = DECODE_TEMP_BUF.get();
Map<String, String> params = new HashMap<>();
int nameStart = from;
int valueStart = -1;
int i;
for (i = from; i < len; i++) {
char ch = str.charAt(i);
if (ch == '%') {
if (i + 3 > len) {
throw new IllegalArgumentException("unterminated escape sequence at index " + i + " of: " + str);
}
ch = (char) decodeHexByte(str, i + 1);
i += 2;
}
switch (ch) {
case '=':
if (nameStart == i) {
nameStart = i + 1;
} else if (valueStart < nameStart) {
valueStart = i + 1;
}
break;
case ';':
case '&':
addParam(str, true, nameStart, valueStart, i - 2, params, tempBuf);
nameStart = i + 1;
break;
default:
// continue
}
}
addParam(str, true, nameStart, valueStart, i, params, tempBuf);
return params;
}
private static boolean addParam(String str, boolean isEncoded, int nameStart, int valueStart, int valueEnd, Map<String, String> params,
TempBuf tempBuf) {
if (nameStart >= valueEnd) {
return false;
}
if (valueStart <= nameStart) {
valueStart = valueEnd + 1;
}
String name;
String value;
if (isEncoded) {
name = decodeComponent(str, nameStart, valueStart - 3, false, tempBuf);
value = valueStart >= valueEnd ? name : decodeComponent(str, valueStart, valueEnd, false, tempBuf);
} else {
name = str.substring(nameStart, valueStart - 1);
value = valueStart >= valueEnd ? name : str.substring(valueStart, valueEnd);
}
params.put(name, value);
// compatible with lower versions registering "default." keys
if (name.startsWith(DEFAULT_KEY_PREFIX)) {
params.putIfAbsent(name.substring(DEFAULT_KEY_PREFIX.length()), value);
}
return true;
}
private static String decodeComponent(String s, int from, int toExcluded, boolean isPath, TempBuf tempBuf) {
int len = toExcluded - from;
if (len <= 0) {
return EMPTY_STRING;
}
int firstEscaped = -1;
for (int i = from; i < toExcluded; i++) {
char c = s.charAt(i);
if (c == '%' || c == '+' && !isPath) {
firstEscaped = i;
break;
}
}
if (firstEscaped == -1) {
return s.substring(from, toExcluded);
}
// Each encoded byte takes 3 characters (e.g. "%20")
int decodedCapacity = (toExcluded - firstEscaped) / 3;
byte[] buf = tempBuf.byteBuf(decodedCapacity);
char[] charBuf = tempBuf.charBuf(len);
s.getChars(from, firstEscaped, charBuf, 0);
int charBufIdx = firstEscaped - from;
return decodeUtf8Component(s, firstEscaped, toExcluded, isPath, buf, charBuf, charBufIdx);
}
private static String decodeUtf8Component(String str, int firstEscaped, int toExcluded, boolean isPath, byte[] buf,
char[] charBuf, int charBufIdx) {
int bufIdx;
for (int i = firstEscaped; i < toExcluded; i++) {
char c = str.charAt(i);
if (c != '%') {
charBuf[charBufIdx++] = c != '+' || isPath ? c : SPACE;
continue;
}
bufIdx = 0;
do {
if (i + 3 > toExcluded) {
throw new IllegalArgumentException("unterminated escape sequence at index " + i + " of: " + str);
}
buf[bufIdx++] = decodeHexByte(str, i + 1);
i += 3;
} while (i < toExcluded && str.charAt(i) == '%');
i--;
charBufIdx += decodeUtf8(buf, 0, bufIdx, charBuf, charBufIdx);
}
return new String(charBuf, 0, charBufIdx);
}
private static int indexOf(String str, char ch, int from, int toExclude) {
from = Math.max(from, 0);
toExclude = Math.min(toExclude, str.length());
if (from > toExclude) {
return -1;
}
for (int i = from; i < toExclude; i++) {
if (str.charAt(i) == ch) {
return i;
}
}
return -1;
}
private static int lastIndexOf(String str, char ch, int from, int toExclude) {
from = Math.max(from, 0);
toExclude = Math.min(toExclude, str.length() - 1);
if (from > toExclude) {
return -1;
}
for (int i = toExclude; i >= from; i--) {
if (str.charAt(i) == ch) {
return i;
}
}
return -1;
}
private static final class TempBuf {
private final char[] chars;
private final byte[] bytes;
TempBuf(int bufSize) {
this.chars = new char[bufSize];
this.bytes = new byte[bufSize];
}
public char[] charBuf(int size) {
char[] chars = this.chars;
if (size <= chars.length) {
return chars;
}
return new char[size];
}
public byte[] byteBuf(int size) {
byte[] bytes = this.bytes;
if (size <= bytes.length) {
return bytes;
}
return new byte[size];
}
}
}