GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_url.cc Lines: 1160 1206 96.2 %
Date: 2020-06-24 22:13:30 Branches: 1076 1198 89.8 %

Line Branch Exec Source
1
#include "node_url.h"
2
#include "base_object-inl.h"
3
#include "node_errors.h"
4
#include "node_i18n.h"
5
#include "util-inl.h"
6
7
#include <cmath>
8
#include <cstdio>
9
#include <string>
10
#include <vector>
11
12
namespace node {
13
14
using errors::TryCatchScope;
15
16
using v8::Array;
17
using v8::Context;
18
using v8::Function;
19
using v8::FunctionCallbackInfo;
20
using v8::HandleScope;
21
using v8::Int32;
22
using v8::Integer;
23
using v8::Isolate;
24
using v8::Local;
25
using v8::MaybeLocal;
26
using v8::NewStringType;
27
using v8::Null;
28
using v8::Object;
29
using v8::String;
30
using v8::Undefined;
31
using v8::Value;
32
33
168385
Local<String> Utf8String(Isolate* isolate, const std::string& str) {
34
336772
  return String::NewFromUtf8(isolate,
35
                             str.data(),
36
                             NewStringType::kNormal,
37
336771
                             str.length()).ToLocalChecked();
38
}
39
40
namespace url {
41
42
namespace {
43
44
// https://url.spec.whatwg.org/#eof-code-point
45
constexpr char kEOL = -1;
46
47
// Used in ToUSVString().
48
constexpr char16_t kUnicodeReplacementCharacter = 0xFFFD;
49
50
// https://url.spec.whatwg.org/#concept-host
51
2358
class URLHost {
52
 public:
53
  ~URLHost();
54
55
  void ParseIPv4Host(const char* input, size_t length, bool* is_ipv4);
56
  void ParseIPv6Host(const char* input, size_t length);
57
  void ParseOpaqueHost(const char* input, size_t length);
58
  void ParseHost(const char* input,
59
                 size_t length,
60
                 bool is_special,
61
                 bool unicode = false);
62
63
2358
  bool ParsingFailed() const { return type_ == HostType::H_FAILED; }
64
  std::string ToString() const;
65
  // Like ToString(), but avoids a copy in exchange for invalidating `*this`.
66
  std::string ToStringMove();
67
68
 private:
69
  enum class HostType {
70
    H_FAILED,
71
    H_DOMAIN,
72
    H_IPV4,
73
    H_IPV6,
74
    H_OPAQUE,
75
  };
76
77
  union Value {
78
    std::string domain_or_opaque;
79
    uint32_t ipv4;
80
    uint16_t ipv6[8];
81
82
2358
    ~Value() {}
83
2358
    Value() : ipv4(0) {}
84
  };
85
86
  Value value_;
87
  HostType type_ = HostType::H_FAILED;
88
89
6496
  void Reset() {
90
    using string = std::string;
91
6496
    switch (type_) {
92
      case HostType::H_DOMAIN:
93
      case HostType::H_OPAQUE:
94
2031
        value_.domain_or_opaque.~string();
95
2031
        break;
96
      default:
97
4465
        break;
98
    }
99
6496
    type_ = HostType::H_FAILED;
100
6496
  }
101
102
  // Setting the string members of the union with = is brittle because
103
  // it relies on them being initialized to a state that requires no
104
  // destruction of old data.
105
  // For a long time, that worked well enough because ParseIPv6Host() happens
106
  // to zero-fill `value_`, but that really is relying on standard library
107
  // internals too much.
108
  // These helpers are the easiest solution but we might want to consider
109
  // just not forcing strings into an union.
110
139
  void SetOpaque(std::string&& string) {
111
139
    Reset();
112
139
    type_ = HostType::H_OPAQUE;
113
139
    new(&value_.domain_or_opaque) std::string(std::move(string));
114
139
  }
115
116
1892
  void SetDomain(std::string&& string) {
117
1892
    Reset();
118
1892
    type_ = HostType::H_DOMAIN;
119
1892
    new(&value_.domain_or_opaque) std::string(std::move(string));
120
1892
  }
121
};
122
123
4716
URLHost::~URLHost() {
124
2358
  Reset();
125
2358
}
126
127
#define ARGS(XX)                                                              \
128
  XX(ARG_FLAGS)                                                               \
129
  XX(ARG_PROTOCOL)                                                            \
130
  XX(ARG_USERNAME)                                                            \
131
  XX(ARG_PASSWORD)                                                            \
132
  XX(ARG_HOST)                                                                \
133
  XX(ARG_PORT)                                                                \
134
  XX(ARG_PATH)                                                                \
135
  XX(ARG_QUERY)                                                               \
136
  XX(ARG_FRAGMENT)                                                            \
137
  XX(ARG_COUNT)  // This one has to be last.
138
139
#define ERR_ARGS(XX)                                                          \
140
  XX(ERR_ARG_FLAGS)                                                           \
141
  XX(ERR_ARG_INPUT)                                                           \
142
143
enum url_cb_args {
144
#define XX(name) name,
145
  ARGS(XX)
146
#undef XX
147
};
148
149
enum url_error_cb_args {
150
#define XX(name) name,
151
  ERR_ARGS(XX)
152
#undef XX
153
};
154
155
#define CHAR_TEST(bits, name, expr)                                           \
156
  template <typename T>                                                       \
157
  bool name(const T ch) {                                              \
158
    static_assert(sizeof(ch) >= (bits) / 8,                                   \
159
                  "Character must be wider than " #bits " bits");             \
160
    return (expr);                                                            \
161
  }
162
163
#define TWO_CHAR_STRING_TEST(bits, name, expr)                                \
164
  template <typename T>                                                       \
165
  bool name(const T ch1, const T ch2) {                                \
166
    static_assert(sizeof(ch1) >= (bits) / 8,                                  \
167
                  "Character must be wider than " #bits " bits");             \
168
    return (expr);                                                            \
169
  }                                                                           \
170
  template <typename T>                                                       \
171
  bool name(const std::basic_string<T>& str) {                         \
172
    static_assert(sizeof(str[0]) >= (bits) / 8,                               \
173
                  "Character must be wider than " #bits " bits");             \
174
    return str.length() >= 2 && name(str[0], str[1]);                         \
175
  }
176
177
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
178

16997003
CHAR_TEST(8, IsASCIITabOrNewline, (ch == '\t' || ch == '\n' || ch == '\r'))
179
180
// https://infra.spec.whatwg.org/#c0-control-or-space
181

277517
CHAR_TEST(8, IsC0ControlOrSpace, (ch >= '\0' && ch <= ' '))
182
183
// https://infra.spec.whatwg.org/#ascii-digit
184

555252
CHAR_TEST(8, IsASCIIDigit, (ch >= '0' && ch <= '9'))
185
186
// https://infra.spec.whatwg.org/#ascii-hex-digit
187


910
CHAR_TEST(8, IsASCIIHexDigit, (IsASCIIDigit(ch) ||
188
                               (ch >= 'A' && ch <= 'F') ||
189
                               (ch >= 'a' && ch <= 'f')))
190
191
// https://infra.spec.whatwg.org/#ascii-alpha
192


1237644
CHAR_TEST(8, IsASCIIAlpha, ((ch >= 'A' && ch <= 'Z') ||
193
                            (ch >= 'a' && ch <= 'z')))
194
195
// https://infra.spec.whatwg.org/#ascii-alphanumeric
196

548491
CHAR_TEST(8, IsASCIIAlphanumeric, (IsASCIIDigit(ch) || IsASCIIAlpha(ch)))
197
198
// https://infra.spec.whatwg.org/#ascii-lowercase
199
template <typename T>
200
548528
T ASCIILowercase(T ch) {
201
548528
  return IsASCIIAlpha(ch) ? (ch | 0x20) : ch;
202
}
203
204
// https://url.spec.whatwg.org/#forbidden-host-code-point
205








65845
CHAR_TEST(8, IsForbiddenHostCodePoint,
206
          ch == '\0' || ch == '\t' || ch == '\n' || ch == '\r' ||
207
          ch == ' ' || ch == '#' || ch == '%' || ch == '/' ||
208
          ch == ':' || ch == '?' || ch == '@' || ch == '[' ||
209
          ch == '<' || ch == '>' || ch == '\\' || ch == ']' ||
210
          ch == '^')
211
212
// https://url.spec.whatwg.org/#windows-drive-letter
213


1648
TWO_CHAR_STRING_TEST(8, IsWindowsDriveLetter,
214
                     (IsASCIIAlpha(ch1) && (ch2 == ':' || ch2 == '|')))
215
216
// https://url.spec.whatwg.org/#normalized-windows-drive-letter
217


526
TWO_CHAR_STRING_TEST(8, IsNormalizedWindowsDriveLetter,
218
                     (IsASCIIAlpha(ch1) && ch2 == ':'))
219
220
// If a UTF-16 character is a low/trailing surrogate.
221
1
CHAR_TEST(16, IsUnicodeTrail, (ch & 0xFC00) == 0xDC00)
222
223
// If a UTF-16 character is a surrogate.
224
21
CHAR_TEST(16, IsUnicodeSurrogate, (ch & 0xF800) == 0xD800)
225
226
// If a UTF-16 surrogate is a low/trailing one.
227
13
CHAR_TEST(16, IsUnicodeSurrogateTrail, (ch & 0x400) != 0)
228
229
#undef CHAR_TEST
230
#undef TWO_CHAR_STRING_TEST
231
232
const char* hex[256] = {
233
  "%00", "%01", "%02", "%03", "%04", "%05", "%06", "%07",
234
  "%08", "%09", "%0A", "%0B", "%0C", "%0D", "%0E", "%0F",
235
  "%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17",
236
  "%18", "%19", "%1A", "%1B", "%1C", "%1D", "%1E", "%1F",
237
  "%20", "%21", "%22", "%23", "%24", "%25", "%26", "%27",
238
  "%28", "%29", "%2A", "%2B", "%2C", "%2D", "%2E", "%2F",
239
  "%30", "%31", "%32", "%33", "%34", "%35", "%36", "%37",
240
  "%38", "%39", "%3A", "%3B", "%3C", "%3D", "%3E", "%3F",
241
  "%40", "%41", "%42", "%43", "%44", "%45", "%46", "%47",
242
  "%48", "%49", "%4A", "%4B", "%4C", "%4D", "%4E", "%4F",
243
  "%50", "%51", "%52", "%53", "%54", "%55", "%56", "%57",
244
  "%58", "%59", "%5A", "%5B", "%5C", "%5D", "%5E", "%5F",
245
  "%60", "%61", "%62", "%63", "%64", "%65", "%66", "%67",
246
  "%68", "%69", "%6A", "%6B", "%6C", "%6D", "%6E", "%6F",
247
  "%70", "%71", "%72", "%73", "%74", "%75", "%76", "%77",
248
  "%78", "%79", "%7A", "%7B", "%7C", "%7D", "%7E", "%7F",
249
  "%80", "%81", "%82", "%83", "%84", "%85", "%86", "%87",
250
  "%88", "%89", "%8A", "%8B", "%8C", "%8D", "%8E", "%8F",
251
  "%90", "%91", "%92", "%93", "%94", "%95", "%96", "%97",
252
  "%98", "%99", "%9A", "%9B", "%9C", "%9D", "%9E", "%9F",
253
  "%A0", "%A1", "%A2", "%A3", "%A4", "%A5", "%A6", "%A7",
254
  "%A8", "%A9", "%AA", "%AB", "%AC", "%AD", "%AE", "%AF",
255
  "%B0", "%B1", "%B2", "%B3", "%B4", "%B5", "%B6", "%B7",
256
  "%B8", "%B9", "%BA", "%BB", "%BC", "%BD", "%BE", "%BF",
257
  "%C0", "%C1", "%C2", "%C3", "%C4", "%C5", "%C6", "%C7",
258
  "%C8", "%C9", "%CA", "%CB", "%CC", "%CD", "%CE", "%CF",
259
  "%D0", "%D1", "%D2", "%D3", "%D4", "%D5", "%D6", "%D7",
260
  "%D8", "%D9", "%DA", "%DB", "%DC", "%DD", "%DE", "%DF",
261
  "%E0", "%E1", "%E2", "%E3", "%E4", "%E5", "%E6", "%E7",
262
  "%E8", "%E9", "%EA", "%EB", "%EC", "%ED", "%EE", "%EF",
263
  "%F0", "%F1", "%F2", "%F3", "%F4", "%F5", "%F6", "%F7",
264
  "%F8", "%F9", "%FA", "%FB", "%FC", "%FD", "%FE", "%FF"
265
};
266
267
const uint8_t C0_CONTROL_ENCODE_SET[32] = {
268
  // 00     01     02     03     04     05     06     07
269
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
270
  // 08     09     0A     0B     0C     0D     0E     0F
271
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
272
  // 10     11     12     13     14     15     16     17
273
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
274
  // 18     19     1A     1B     1C     1D     1E     1F
275
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
276
  // 20     21     22     23     24     25     26     27
277
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
278
  // 28     29     2A     2B     2C     2D     2E     2F
279
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
280
  // 30     31     32     33     34     35     36     37
281
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
282
  // 38     39     3A     3B     3C     3D     3E     3F
283
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
284
  // 40     41     42     43     44     45     46     47
285
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
286
  // 48     49     4A     4B     4C     4D     4E     4F
287
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
288
  // 50     51     52     53     54     55     56     57
289
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
290
  // 58     59     5A     5B     5C     5D     5E     5F
291
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
292
  // 60     61     62     63     64     65     66     67
293
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
294
  // 68     69     6A     6B     6C     6D     6E     6F
295
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
296
  // 70     71     72     73     74     75     76     77
297
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
298
  // 78     79     7A     7B     7C     7D     7E     7F
299
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x80,
300
  // 80     81     82     83     84     85     86     87
301
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
302
  // 88     89     8A     8B     8C     8D     8E     8F
303
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
304
  // 90     91     92     93     94     95     96     97
305
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
306
  // 98     99     9A     9B     9C     9D     9E     9F
307
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
308
  // A0     A1     A2     A3     A4     A5     A6     A7
309
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
310
  // A8     A9     AA     AB     AC     AD     AE     AF
311
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
312
  // B0     B1     B2     B3     B4     B5     B6     B7
313
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
314
  // B8     B9     BA     BB     BC     BD     BE     BF
315
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
316
  // C0     C1     C2     C3     C4     C5     C6     C7
317
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
318
  // C8     C9     CA     CB     CC     CD     CE     CF
319
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
320
  // D0     D1     D2     D3     D4     D5     D6     D7
321
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
322
  // D8     D9     DA     DB     DC     DD     DE     DF
323
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
324
  // E0     E1     E2     E3     E4     E5     E6     E7
325
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
326
  // E8     E9     EA     EB     EC     ED     EE     EF
327
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
328
  // F0     F1     F2     F3     F4     F5     F6     F7
329
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
330
  // F8     F9     FA     FB     FC     FD     FE     FF
331
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80
332
};
333
334
const uint8_t FRAGMENT_ENCODE_SET[32] = {
335
  // 00     01     02     03     04     05     06     07
336
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
337
  // 08     09     0A     0B     0C     0D     0E     0F
338
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
339
  // 10     11     12     13     14     15     16     17
340
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
341
  // 18     19     1A     1B     1C     1D     1E     1F
342
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
343
  // 20     21     22     23     24     25     26     27
344
    0x01 | 0x00 | 0x04 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
345
  // 28     29     2A     2B     2C     2D     2E     2F
346
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
347
  // 30     31     32     33     34     35     36     37
348
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
349
  // 38     39     3A     3B     3C     3D     3E     3F
350
    0x00 | 0x00 | 0x00 | 0x00 | 0x10 | 0x00 | 0x40 | 0x00,
351
  // 40     41     42     43     44     45     46     47
352
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
353
  // 48     49     4A     4B     4C     4D     4E     4F
354
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
355
  // 50     51     52     53     54     55     56     57
356
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
357
  // 58     59     5A     5B     5C     5D     5E     5F
358
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
359
  // 60     61     62     63     64     65     66     67
360
    0x01 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
361
  // 68     69     6A     6B     6C     6D     6E     6F
362
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
363
  // 70     71     72     73     74     75     76     77
364
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
365
  // 78     79     7A     7B     7C     7D     7E     7F
366
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x80,
367
  // 80     81     82     83     84     85     86     87
368
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
369
  // 88     89     8A     8B     8C     8D     8E     8F
370
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
371
  // 90     91     92     93     94     95     96     97
372
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
373
  // 98     99     9A     9B     9C     9D     9E     9F
374
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
375
  // A0     A1     A2     A3     A4     A5     A6     A7
376
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
377
  // A8     A9     AA     AB     AC     AD     AE     AF
378
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
379
  // B0     B1     B2     B3     B4     B5     B6     B7
380
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
381
  // B8     B9     BA     BB     BC     BD     BE     BF
382
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
383
  // C0     C1     C2     C3     C4     C5     C6     C7
384
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
385
  // C8     C9     CA     CB     CC     CD     CE     CF
386
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
387
  // D0     D1     D2     D3     D4     D5     D6     D7
388
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
389
  // D8     D9     DA     DB     DC     DD     DE     DF
390
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
391
  // E0     E1     E2     E3     E4     E5     E6     E7
392
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
393
  // E8     E9     EA     EB     EC     ED     EE     EF
394
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
395
  // F0     F1     F2     F3     F4     F5     F6     F7
396
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
397
  // F8     F9     FA     FB     FC     FD     FE     FF
398
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80
399
};
400
401
402
const uint8_t PATH_ENCODE_SET[32] = {
403
  // 00     01     02     03     04     05     06     07
404
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
405
  // 08     09     0A     0B     0C     0D     0E     0F
406
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
407
  // 10     11     12     13     14     15     16     17
408
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
409
  // 18     19     1A     1B     1C     1D     1E     1F
410
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
411
  // 20     21     22     23     24     25     26     27
412
    0x01 | 0x00 | 0x04 | 0x08 | 0x00 | 0x00 | 0x00 | 0x00,
413
  // 28     29     2A     2B     2C     2D     2E     2F
414
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
415
  // 30     31     32     33     34     35     36     37
416
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
417
  // 38     39     3A     3B     3C     3D     3E     3F
418
    0x00 | 0x00 | 0x00 | 0x00 | 0x10 | 0x00 | 0x40 | 0x80,
419
  // 40     41     42     43     44     45     46     47
420
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
421
  // 48     49     4A     4B     4C     4D     4E     4F
422
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
423
  // 50     51     52     53     54     55     56     57
424
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
425
  // 58     59     5A     5B     5C     5D     5E     5F
426
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
427
  // 60     61     62     63     64     65     66     67
428
    0x01 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
429
  // 68     69     6A     6B     6C     6D     6E     6F
430
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
431
  // 70     71     72     73     74     75     76     77
432
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
433
  // 78     79     7A     7B     7C     7D     7E     7F
434
    0x00 | 0x00 | 0x00 | 0x08 | 0x00 | 0x20 | 0x00 | 0x80,
435
  // 80     81     82     83     84     85     86     87
436
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
437
  // 88     89     8A     8B     8C     8D     8E     8F
438
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
439
  // 90     91     92     93     94     95     96     97
440
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
441
  // 98     99     9A     9B     9C     9D     9E     9F
442
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
443
  // A0     A1     A2     A3     A4     A5     A6     A7
444
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
445
  // A8     A9     AA     AB     AC     AD     AE     AF
446
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
447
  // B0     B1     B2     B3     B4     B5     B6     B7
448
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
449
  // B8     B9     BA     BB     BC     BD     BE     BF
450
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
451
  // C0     C1     C2     C3     C4     C5     C6     C7
452
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
453
  // C8     C9     CA     CB     CC     CD     CE     CF
454
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
455
  // D0     D1     D2     D3     D4     D5     D6     D7
456
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
457
  // D8     D9     DA     DB     DC     DD     DE     DF
458
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
459
  // E0     E1     E2     E3     E4     E5     E6     E7
460
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
461
  // E8     E9     EA     EB     EC     ED     EE     EF
462
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
463
  // F0     F1     F2     F3     F4     F5     F6     F7
464
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
465
  // F8     F9     FA     FB     FC     FD     FE     FF
466
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80
467
};
468
469
const uint8_t USERINFO_ENCODE_SET[32] = {
470
  // 00     01     02     03     04     05     06     07
471
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
472
  // 08     09     0A     0B     0C     0D     0E     0F
473
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
474
  // 10     11     12     13     14     15     16     17
475
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
476
  // 18     19     1A     1B     1C     1D     1E     1F
477
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
478
  // 20     21     22     23     24     25     26     27
479
    0x01 | 0x00 | 0x04 | 0x08 | 0x00 | 0x00 | 0x00 | 0x00,
480
  // 28     29     2A     2B     2C     2D     2E     2F
481
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x80,
482
  // 30     31     32     33     34     35     36     37
483
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
484
  // 38     39     3A     3B     3C     3D     3E     3F
485
    0x00 | 0x00 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
486
  // 40     41     42     43     44     45     46     47
487
    0x01 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
488
  // 48     49     4A     4B     4C     4D     4E     4F
489
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
490
  // 50     51     52     53     54     55     56     57
491
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
492
  // 58     59     5A     5B     5C     5D     5E     5F
493
    0x00 | 0x00 | 0x00 | 0x08 | 0x10 | 0x20 | 0x40 | 0x00,
494
  // 60     61     62     63     64     65     66     67
495
    0x01 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
496
  // 68     69     6A     6B     6C     6D     6E     6F
497
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
498
  // 70     71     72     73     74     75     76     77
499
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
500
  // 78     79     7A     7B     7C     7D     7E     7F
501
    0x00 | 0x00 | 0x00 | 0x08 | 0x10 | 0x20 | 0x00 | 0x80,
502
  // 80     81     82     83     84     85     86     87
503
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
504
  // 88     89     8A     8B     8C     8D     8E     8F
505
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
506
  // 90     91     92     93     94     95     96     97
507
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
508
  // 98     99     9A     9B     9C     9D     9E     9F
509
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
510
  // A0     A1     A2     A3     A4     A5     A6     A7
511
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
512
  // A8     A9     AA     AB     AC     AD     AE     AF
513
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
514
  // B0     B1     B2     B3     B4     B5     B6     B7
515
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
516
  // B8     B9     BA     BB     BC     BD     BE     BF
517
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
518
  // C0     C1     C2     C3     C4     C5     C6     C7
519
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
520
  // C8     C9     CA     CB     CC     CD     CE     CF
521
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
522
  // D0     D1     D2     D3     D4     D5     D6     D7
523
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
524
  // D8     D9     DA     DB     DC     DD     DE     DF
525
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
526
  // E0     E1     E2     E3     E4     E5     E6     E7
527
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
528
  // E8     E9     EA     EB     EC     ED     EE     EF
529
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
530
  // F0     F1     F2     F3     F4     F5     F6     F7
531
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
532
  // F8     F9     FA     FB     FC     FD     FE     FF
533
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80
534
};
535
536
const uint8_t QUERY_ENCODE_SET_NONSPECIAL[32] = {
537
  // 00     01     02     03     04     05     06     07
538
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
539
  // 08     09     0A     0B     0C     0D     0E     0F
540
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
541
  // 10     11     12     13     14     15     16     17
542
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
543
  // 18     19     1A     1B     1C     1D     1E     1F
544
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
545
  // 20     21     22     23     24     25     26     27
546
    0x01 | 0x00 | 0x04 | 0x08 | 0x00 | 0x00 | 0x00 | 0x00,
547
  // 28     29     2A     2B     2C     2D     2E     2F
548
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
549
  // 30     31     32     33     34     35     36     37
550
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
551
  // 38     39     3A     3B     3C     3D     3E     3F
552
    0x00 | 0x00 | 0x00 | 0x00 | 0x10 | 0x00 | 0x40 | 0x00,
553
  // 40     41     42     43     44     45     46     47
554
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
555
  // 48     49     4A     4B     4C     4D     4E     4F
556
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
557
  // 50     51     52     53     54     55     56     57
558
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
559
  // 58     59     5A     5B     5C     5D     5E     5F
560
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
561
  // 60     61     62     63     64     65     66     67
562
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
563
  // 68     69     6A     6B     6C     6D     6E     6F
564
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
565
  // 70     71     72     73     74     75     76     77
566
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
567
  // 78     79     7A     7B     7C     7D     7E     7F
568
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x80,
569
  // 80     81     82     83     84     85     86     87
570
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
571
  // 88     89     8A     8B     8C     8D     8E     8F
572
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
573
  // 90     91     92     93     94     95     96     97
574
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
575
  // 98     99     9A     9B     9C     9D     9E     9F
576
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
577
  // A0     A1     A2     A3     A4     A5     A6     A7
578
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
579
  // A8     A9     AA     AB     AC     AD     AE     AF
580
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
581
  // B0     B1     B2     B3     B4     B5     B6     B7
582
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
583
  // B8     B9     BA     BB     BC     BD     BE     BF
584
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
585
  // C0     C1     C2     C3     C4     C5     C6     C7
586
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
587
  // C8     C9     CA     CB     CC     CD     CE     CF
588
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
589
  // D0     D1     D2     D3     D4     D5     D6     D7
590
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
591
  // D8     D9     DA     DB     DC     DD     DE     DF
592
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
593
  // E0     E1     E2     E3     E4     E5     E6     E7
594
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
595
  // E8     E9     EA     EB     EC     ED     EE     EF
596
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
597
  // F0     F1     F2     F3     F4     F5     F6     F7
598
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
599
  // F8     F9     FA     FB     FC     FD     FE     FF
600
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80
601
};
602
603
// Same as QUERY_ENCODE_SET_NONSPECIAL, but with 0x27 (') encoded.
604
const uint8_t QUERY_ENCODE_SET_SPECIAL[32] = {
605
  // 00     01     02     03     04     05     06     07
606
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
607
  // 08     09     0A     0B     0C     0D     0E     0F
608
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
609
  // 10     11     12     13     14     15     16     17
610
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
611
  // 18     19     1A     1B     1C     1D     1E     1F
612
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
613
  // 20     21     22     23     24     25     26     27
614
    0x01 | 0x00 | 0x04 | 0x08 | 0x00 | 0x00 | 0x00 | 0x80,
615
  // 28     29     2A     2B     2C     2D     2E     2F
616
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
617
  // 30     31     32     33     34     35     36     37
618
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
619
  // 38     39     3A     3B     3C     3D     3E     3F
620
    0x00 | 0x00 | 0x00 | 0x00 | 0x10 | 0x00 | 0x40 | 0x00,
621
  // 40     41     42     43     44     45     46     47
622
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
623
  // 48     49     4A     4B     4C     4D     4E     4F
624
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
625
  // 50     51     52     53     54     55     56     57
626
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
627
  // 58     59     5A     5B     5C     5D     5E     5F
628
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
629
  // 60     61     62     63     64     65     66     67
630
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
631
  // 68     69     6A     6B     6C     6D     6E     6F
632
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
633
  // 70     71     72     73     74     75     76     77
634
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
635
  // 78     79     7A     7B     7C     7D     7E     7F
636
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x80,
637
  // 80     81     82     83     84     85     86     87
638
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
639
  // 88     89     8A     8B     8C     8D     8E     8F
640
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
641
  // 90     91     92     93     94     95     96     97
642
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
643
  // 98     99     9A     9B     9C     9D     9E     9F
644
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
645
  // A0     A1     A2     A3     A4     A5     A6     A7
646
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
647
  // A8     A9     AA     AB     AC     AD     AE     AF
648
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
649
  // B0     B1     B2     B3     B4     B5     B6     B7
650
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
651
  // B8     B9     BA     BB     BC     BD     BE     BF
652
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
653
  // C0     C1     C2     C3     C4     C5     C6     C7
654
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
655
  // C8     C9     CA     CB     CC     CD     CE     CF
656
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
657
  // D0     D1     D2     D3     D4     D5     D6     D7
658
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
659
  // D8     D9     DA     DB     DC     DD     DE     DF
660
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
661
  // E0     E1     E2     E3     E4     E5     E6     E7
662
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
663
  // E8     E9     EA     EB     EC     ED     EE     EF
664
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
665
  // F0     F1     F2     F3     F4     F5     F6     F7
666
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
667
  // F8     F9     FA     FB     FC     FD     FE     FF
668
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80
669
};
670
671
14469134
bool BitAt(const uint8_t a[], const uint8_t i) {
672
14469134
  return !!(a[i >> 3] & (1 << (i & 7)));
673
}
674
675
// Appends ch to str. If ch position in encode_set is set, the ch will
676
// be percent-encoded then appended.
677
14469137
void AppendOrEscape(std::string* str,
678
                           const unsigned char ch,
679
                           const uint8_t encode_set[]) {
680
14469137
  if (BitAt(encode_set, ch))
681
805
    *str += hex[ch];
682
  else
683
14468335
    *str += ch;
684
14469140
}
685
686
template <typename T>
687
578
unsigned hex2bin(const T ch) {
688

578
  if (ch >= '0' && ch <= '9')
689
448
    return ch - '0';
690

130
  if (ch >= 'A' && ch <= 'F')
691
32
    return 10 + (ch - 'A');
692

98
  if (ch >= 'a' && ch <= 'f')
693
98
    return 10 + (ch - 'a');
694
  return static_cast<unsigned>(-1);
695
}
696
697
2106
std::string PercentDecode(const char* input, size_t len) {
698
2106
  std::string dest;
699
2106
  if (len == 0)
700
2
    return dest;
701
2104
  dest.reserve(len);
702
2104
  const char* pointer = input;
703
2104
  const char* end = input + len;
704
705
132716
  while (pointer < end) {
706
65306
    const char ch = pointer[0];
707
65306
    size_t remaining = end - pointer - 1;
708


130429
    if (ch != '%' || remaining < 2 ||
709
192
        (ch == '%' &&
710
381
         (!IsASCIIHexDigit(pointer[1]) ||
711
189
          !IsASCIIHexDigit(pointer[2])))) {
712
65123
      dest += ch;
713
65123
      pointer++;
714
65123
      continue;
715
    } else {
716
183
      unsigned a = hex2bin(pointer[1]);
717
183
      unsigned b = hex2bin(pointer[2]);
718
183
      char c = static_cast<char>(a * 16 + b);
719
183
      dest += c;
720
183
      pointer += 3;
721
    }
722
  }
723
2104
  return dest;
724
}
725
726
#define SPECIALS(XX)                                                          \
727
  XX(ftp, 21, "ftp:")                                                         \
728
  XX(file, -1, "file:")                                                       \
729
  XX(http, 80, "http:")                                                       \
730
  XX(https, 443, "https:")                                                    \
731
  XX(ws, 80, "ws:")                                                           \
732
  XX(wss, 443, "wss:")
733
734
352779
bool IsSpecial(const std::string& scheme) {
735
#define V(_, __, name) if (scheme == name) return true;
736



352779
  SPECIALS(V);
737
#undef V
738
1187
  return false;
739
}
740
741
167653
Local<String> GetSpecial(Environment* env, const std::string& scheme) {
742
#define V(key, _, name) if (scheme == name)                                  \
743
    return env->url_special_##key##_string();
744



167653
  SPECIALS(V)
745
#undef V
746
  UNREACHABLE();
747
}
748
749
136239
int NormalizePort(const std::string& scheme, int p) {
750
#define V(_, port, name) if (scheme == name && p == port) return -1;
751









136239
  SPECIALS(V);
752
#undef V
753
3088
  return p;
754
}
755
756
// https://url.spec.whatwg.org/#start-with-a-windows-drive-letter
757
1587
bool StartsWithWindowsDriveLetter(const char* p, const char* end) {
758
1587
  size_t length = end - p;
759
1562
  return length >= 2 &&
760

1616
    IsWindowsDriveLetter(p[0], p[1]) &&
761
14
    (length == 2 ||
762
21
      p[2] == '/' ||
763
10
      p[2] == '\\' ||
764
5
      p[2] == '?' ||
765
1589
      p[2] == '#');
766
}
767
768
#if defined(NODE_HAVE_I18N_SUPPORT)
769
193
bool ToUnicode(const std::string& input, std::string* output) {
770
386
  MaybeStackBuffer<char> buf;
771
193
  if (i18n::ToUnicode(&buf, input.c_str(), input.length()) < 0)
772
    return false;
773
193
  output->assign(*buf, buf.length());
774
193
  return true;
775
}
776
777
2093
bool ToASCII(const std::string& input, std::string* output) {
778
4186
  MaybeStackBuffer<char> buf;
779
2093
  if (i18n::ToASCII(&buf, input.c_str(), input.length()) < 0)
780
69
    return false;
781
2024
  output->assign(*buf, buf.length());
782
2024
  return true;
783
}
784
#else
785
// Intentional non-ops if ICU is not present.
786
bool ToUnicode(const std::string& input, std::string* output) {
787
  *output = input;
788
  return true;
789
}
790
791
bool ToASCII(const std::string& input, std::string* output) {
792
  *output = input;
793
  return true;
794
}
795
#endif
796
797
91
void URLHost::ParseIPv6Host(const char* input, size_t length) {
798
91
  CHECK_EQ(type_, HostType::H_FAILED);
799
91
  unsigned size = arraysize(value_.ipv6);
800
819
  for (unsigned n = 0; n < size; n++)
801
728
    value_.ipv6[n] = 0;
802
91
  uint16_t* piece_pointer = &value_.ipv6[0];
803
91
  uint16_t* const buffer_end = piece_pointer + size;
804
91
  uint16_t* compress_pointer = nullptr;
805
91
  const char* pointer = input;
806
91
  const char* end = pointer + length;
807
  unsigned value, len, numbers_seen;
808
91
  char ch = pointer < end ? pointer[0] : kEOL;
809
91
  if (ch == ':') {
810

33
    if (length < 2 || pointer[1] != ':')
811
3
      return;
812
30
    pointer += 2;
813
30
    ch = pointer < end ? pointer[0] : kEOL;
814
30
    piece_pointer++;
815
30
    compress_pointer = piece_pointer;
816
  }
817
404
  while (ch != kEOL) {
818
219
    if (piece_pointer >= buffer_end)
819
3
      return;
820
216
    if (ch == ':') {
821
17
      if (compress_pointer != nullptr)
822
3
        return;
823
14
      pointer++;
824
14
      ch = pointer < end ? pointer[0] : kEOL;
825
14
      piece_pointer++;
826
14
      compress_pointer = piece_pointer;
827
14
      continue;
828
    }
829
199
    value = 0;
830
199
    len = 0;
831

623
    while (len < 4 && IsASCIIHexDigit(ch)) {
832
212
      value = value * 0x10 + hex2bin(ch);
833
212
      pointer++;
834
212
      ch = pointer < end ? pointer[0] : kEOL;
835
212
      len++;
836
    }
837

199
    switch (ch) {
838
      case '.':
839
43
        if (len == 0)
840
3
          return;
841
40
        pointer -= len;
842
40
        ch = pointer < end ? pointer[0] : kEOL;
843
40
        if (piece_pointer > buffer_end - 2)
844
3
          return;
845
37
        numbers_seen = 0;
846
223
        while (ch != kEOL) {
847
123
          value = 0xffffffff;
848
123
          if (numbers_seen > 0) {
849

86
            if (ch == '.' && numbers_seen < 4) {
850
78
              pointer++;
851
78
              ch = pointer < end ? pointer[0] : kEOL;
852
            } else {
853
8
              return;
854
            }
855
          }
856
115
          if (!IsASCIIDigit(ch))
857
16
            return;
858
343
          while (IsASCIIDigit(ch)) {
859
128
            unsigned number = ch - '0';
860
128
            if (value == 0xffffffff) {
861
99
              value = number;
862
29
            } else if (value == 0) {
863
3
              return;
864
            } else {
865
26
              value = value * 10 + number;
866
            }
867
125
            if (value > 255)
868
3
              return;
869
122
            pointer++;
870
122
            ch = pointer < end ? pointer[0] : kEOL;
871
          }
872
93
          *piece_pointer = *piece_pointer * 0x100 + value;
873
93
          numbers_seen++;
874

93
          if (numbers_seen == 2 || numbers_seen == 4)
875
37
            piece_pointer++;
876
        }
877
7
        if (numbers_seen != 4)
878
3
          return;
879
4
        continue;
880
      case ':':
881
125
        pointer++;
882
125
        ch = pointer < end ? pointer[0] : kEOL;
883
125
        if (ch == kEOL)
884
3
          return;
885
122
        break;
886
      case kEOL:
887
18
        break;
888
      default:
889
13
        return;
890
    }
891
140
    *piece_pointer = value;
892
140
    piece_pointer++;
893
  }
894
895
27
  if (compress_pointer != nullptr) {
896
18
    unsigned swaps = piece_pointer - compress_pointer;
897
18
    piece_pointer = buffer_end - 1;
898

58
    while (piece_pointer != &value_.ipv6[0] && swaps > 0) {
899
20
      uint16_t temp = *piece_pointer;
900
20
      uint16_t* swap_piece = compress_pointer + swaps - 1;
901
20
      *piece_pointer = *swap_piece;
902
20
      *swap_piece = temp;
903
20
       piece_pointer--;
904
20
       swaps--;
905
    }
906

9
  } else if (compress_pointer == nullptr &&
907
             piece_pointer != buffer_end) {
908
3
    return;
909
  }
910
24
  type_ = HostType::H_IPV6;
911
}
912
913
2100
int64_t ParseNumber(const char* start, const char* end) {
914
2100
  unsigned R = 10;
915

2100
  if (end - start >= 2 && start[0] == '0' && (start[1] | 0x20) == 'x') {
916
26
    start += 2;
917
26
    R = 16;
918
  }
919
2100
  if (end - start == 0) {
920
4
    return 0;
921

2096
  } else if (R == 10 && end - start > 1 && start[0] == '0') {
922
32
    start++;
923
32
    R = 8;
924
  }
925
2096
  const char* p = start;
926
927
3586
  while (p < end) {
928
2629
    const char ch = p[0];
929

2629
    switch (R) {
930
      case 8:
931

173
        if (ch < '0' || ch > '7')
932
19
          return -1;
933
154
        break;
934
      case 10:
935
2334
        if (!IsASCIIDigit(ch))
936
1863
          return -1;
937
471
        break;
938
      case 16:
939
122
        if (!IsASCIIHexDigit(ch))
940
2
          return -1;
941
120
        break;
942
    }
943
745
    p++;
944
  }
945
212
  return strtoll(start, nullptr, R);
946
}
947
948
1965
void URLHost::ParseIPv4Host(const char* input, size_t length, bool* is_ipv4) {
949
1965
  CHECK_EQ(type_, HostType::H_FAILED);
950
1965
  *is_ipv4 = false;
951
1965
  const char* pointer = input;
952
1965
  const char* mark = input;
953
1965
  const char* end = pointer + length;
954
1965
  int parts = 0;
955
1965
  uint32_t val = 0;
956
  uint64_t numbers[4];
957
1965
  int tooBigNumbers = 0;
958
1965
  if (length == 0)
959
1913
    return;
960
961
38375
  while (pointer <= end) {
962
20099
    const char ch = pointer < end ? pointer[0] : kEOL;
963
20099
    int remaining = end - pointer - 1;
964

20099
    if (ch == '.' || ch == kEOL) {
965
2108
      if (++parts > static_cast<int>(arraysize(numbers)))
966
2
        return;
967
2106
      if (pointer == mark)
968
6
        return;
969
2100
      int64_t n = ParseNumber(mark, pointer);
970
2100
      if (n < 0)
971
1884
        return;
972
973
216
      if (n > 255) {
974
69
        tooBigNumbers++;
975
      }
976
216
      numbers[parts - 1] = n;
977
216
      mark = pointer + 1;
978

216
      if (ch == '.' && remaining == 0)
979
2
        break;
980
    }
981
18205
    pointer++;
982
  }
983
73
  CHECK_GT(parts, 0);
984
73
  *is_ipv4 = true;
985
986
  // If any but the last item in numbers is greater than 255, return failure.
987
  // If the last item in numbers is greater than or equal to
988
  // 256^(5 - the number of items in numbers), return failure.
989

143
  if (tooBigNumbers > 1 ||
990

181
      (tooBigNumbers == 1 && numbers[parts - 1] <= 255) ||
991
67
      numbers[parts - 1] >= pow(256, static_cast<double>(5 - parts))) {
992
21
    return;
993
  }
994
995
52
  type_ = HostType::H_IPV4;
996
52
  val = numbers[parts - 1];
997
137
  for (int n = 0; n < parts - 1; n++) {
998
85
    double b = 3 - n;
999
85
    val += numbers[n] * pow(256, b);
1000
  }
1001
1002
52
  value_.ipv4 = val;
1003
}
1004
1005
168
void URLHost::ParseOpaqueHost(const char* input, size_t length) {
1006
168
  CHECK_EQ(type_, HostType::H_FAILED);
1007
307
  std::string output;
1008
168
  output.reserve(length);
1009
1049
  for (size_t i = 0; i < length; i++) {
1010
910
    const char ch = input[i];
1011

910
    if (ch != '%' && IsForbiddenHostCodePoint(ch)) {
1012
29
      return;
1013
    } else {
1014
881
      AppendOrEscape(&output, ch, C0_CONTROL_ENCODE_SET);
1015
    }
1016
  }
1017
1018
139
  SetOpaque(std::move(output));
1019
}
1020
1021
2358
void URLHost::ParseHost(const char* input,
1022
                        size_t length,
1023
                        bool is_special,
1024
                        bool unicode) {
1025
2358
  CHECK_EQ(type_, HostType::H_FAILED);
1026
2358
  const char* pointer = input;
1027
1028
2358
  if (length == 0)
1029
466
    return;
1030
1031
2358
  if (pointer[0] == '[') {
1032
97
    if (pointer[length - 1] != ']')
1033
6
      return;
1034
91
    return ParseIPv6Host(++pointer, length - 2);
1035
  }
1036
1037
2261
  if (!is_special)
1038
168
    return ParseOpaqueHost(input, length);
1039
1040
  // First, we have to percent decode
1041
3985
  std::string decoded = PercentDecode(input, length);
1042
1043
  // Then we have to punycode toASCII
1044
2093
  if (!ToASCII(decoded, &decoded))
1045
69
    return;
1046
1047
  // If any of the following characters are still present, we have to fail
1048
66905
  for (size_t n = 0; n < decoded.size(); n++) {
1049
64940
    const char ch = decoded[n];
1050
64940
    if (IsForbiddenHostCodePoint(ch)) {
1051
59
      return;
1052
    }
1053
  }
1054
1055
  // Check to see if it's an IPv4 IP address
1056
  bool is_ipv4;
1057
1965
  ParseIPv4Host(decoded.c_str(), decoded.length(), &is_ipv4);
1058
1965
  if (is_ipv4)
1059
73
    return;
1060
1061
  // If the unicode flag is set, run the result through punycode ToUnicode
1062

1892
  if (unicode && !ToUnicode(decoded, &decoded))
1063
    return;
1064
1065
  // It's not an IPv4 or IPv6 address, it must be a domain
1066
1892
  SetDomain(std::move(decoded));
1067
}
1068
1069
// Locates the longest sequence of 0 segments in an IPv6 address
1070
// in order to use the :: compression when serializing
1071
template <typename T>
1072
24
T* FindLongestZeroSequence(T* values, size_t len) {
1073
24
  T* start = values;
1074
24
  T* end = start + len;
1075
24
  T* result = nullptr;
1076
1077
24
  T* current = nullptr;
1078
24
  unsigned counter = 0, longest = 1;
1079
1080
408
  while (start < end) {
1081
192
    if (*start == 0) {
1082
144
      if (current == nullptr)
1083
31
        current = start;
1084
144
      counter++;
1085
    } else {
1086
48
      if (counter > longest) {
1087
20
        longest = counter;
1088
20
        result = current;
1089
      }
1090
48
      counter = 0;
1091
48
      current = nullptr;
1092
    }
1093
192
    start++;
1094
  }
1095
24
  if (counter > longest)
1096
3
    result = current;
1097
24
  return result;
1098
}
1099
1100
2107
std::string URLHost::ToStringMove() {
1101
2107
  std::string return_value;
1102
2107
  switch (type_) {
1103
    case HostType::H_DOMAIN:
1104
    case HostType::H_OPAQUE:
1105
2031
      return_value = std::move(value_.domain_or_opaque);
1106
2031
      break;
1107
    default:
1108
76
      return_value = ToString();
1109
76
      break;
1110
  }
1111
2107
  Reset();
1112
2107
  return return_value;
1113
}
1114
1115
76
std::string URLHost::ToString() const {
1116
152
  std::string dest;
1117

76
  switch (type_) {
1118
    case HostType::H_DOMAIN:
1119
    case HostType::H_OPAQUE:
1120
      return value_.domain_or_opaque;
1121
      break;
1122
    case HostType::H_IPV4: {
1123
52
      dest.reserve(15);
1124
52
      uint32_t value = value_.ipv4;
1125
260
      for (int n = 0; n < 4; n++) {
1126
        char buf[4];
1127
208
        snprintf(buf, sizeof(buf), "%d", value % 256);
1128
208
        dest.insert(0, buf);
1129
208
        if (n < 3)
1130
156
          dest.insert(0, 1, '.');
1131
208
        value /= 256;
1132
      }
1133
52
      break;
1134
    }
1135
    case HostType::H_IPV6: {
1136
24
      dest.reserve(41);
1137
24
      dest += '[';
1138
24
      const uint16_t* start = &value_.ipv6[0];
1139
      const uint16_t* compress_pointer =
1140
24
          FindLongestZeroSequence(start, 8);
1141
24
      bool ignore0 = false;
1142
216
      for (int n = 0; n <= 7; n++) {
1143
192
        const uint16_t* piece = &value_.ipv6[n];
1144

192
        if (ignore0 && *piece == 0)
1145
246
          continue;
1146
80
        else if (ignore0)
1147
19
          ignore0 = false;
1148
80
        if (compress_pointer == piece) {
1149
22
          dest += n == 0 ? "::" : ":";
1150
22
          ignore0 = true;
1151
22
          continue;
1152
        }
1153
        char buf[5];
1154
58
        snprintf(buf, sizeof(buf), "%x", *piece);
1155
58
        dest += buf;
1156
58
        if (n < 7)
1157
37
          dest += ':';
1158
      }
1159
24
      dest += ']';
1160
24
      break;
1161
    }
1162
    case HostType::H_FAILED:
1163
      break;
1164
  }
1165
76
  return dest;
1166
}
1167
1168
1976
bool ParseHost(const std::string& input,
1169
               std::string* output,
1170
               bool is_special,
1171
               bool unicode = false) {
1172
1976
  if (input.length() == 0) {
1173
42
    output->clear();
1174
42
    return true;
1175
  }
1176
3868
  URLHost host;
1177
1934
  host.ParseHost(input.c_str(), input.length(), is_special, unicode);
1178
1934
  if (host.ParsingFailed())
1179
233
    return false;
1180
1701
  *output = host.ToStringMove();
1181
1701
  return true;
1182
}
1183
1184
2577
std::vector<std::string> FromJSStringArray(Environment* env,
1185
                                           Local<Array> array) {
1186
2577
  std::vector<std::string> vec;
1187
2577
  if (array->Length() > 0)
1188
2569
    vec.reserve(array->Length());
1189
33894
  for (size_t n = 0; n < array->Length(); n++) {
1190
43110
    Local<Value> val = array->Get(env->context(), n).ToLocalChecked();
1191
28740
    if (val->IsString()) {
1192
28740
      Utf8Value value(env->isolate(), val.As<String>());
1193
14370
      vec.emplace_back(*value, value.length());
1194
    }
1195
  }
1196
2577
  return vec;
1197
}
1198
1199
2577
url_data HarvestBase(Environment* env, Local<Object> base_obj) {
1200
2577
  url_data base;
1201
2577
  Local<Context> context = env->context();
1202
1203
  Local<Value> flags =
1204
10308
      base_obj->Get(env->context(), env->flags_string()).ToLocalChecked();
1205
2577
  if (flags->IsInt32())
1206
5154
    base.flags = flags->Int32Value(context).FromJust();
1207
1208
  Local<Value> port =
1209
10308
      base_obj->Get(env->context(), env->port_string()).ToLocalChecked();
1210
2577
  if (port->IsInt32())
1211
8
    base.port = port->Int32Value(context).FromJust();
1212
1213
  Local<Value> scheme =
1214
10308
      base_obj->Get(env->context(), env->scheme_string()).ToLocalChecked();
1215
2577
  base.scheme = Utf8Value(env->isolate(), scheme).out();
1216
1217
  auto GetStr = [&](std::string url_data::*member,
1218
                    int flag,
1219
                    Local<String> name,
1220
12885
                    bool empty_as_present) {
1221
45880
    Local<Value> value = base_obj->Get(env->context(), name).ToLocalChecked();
1222
25770
    if (value->IsString()) {
1223
14450
      Utf8Value utf8value(env->isolate(), value.As<String>());
1224
9308
      (base.*member).assign(*utf8value, utf8value.length());
1225

17533
      if (empty_as_present || value.As<String>()->Length() != 0) {
1226
2083
        base.flags |= flag;
1227
      }
1228
    }
1229
15462
  };
1230
2577
  GetStr(&url_data::username,
1231
         URL_FLAGS_HAS_USERNAME,
1232
         env->username_string(),
1233
2577
         false);
1234
2577
  GetStr(&url_data::password,
1235
         URL_FLAGS_HAS_PASSWORD,
1236
         env->password_string(),
1237
2577
         false);
1238
2577
  GetStr(&url_data::host, URL_FLAGS_HAS_HOST, env->host_string(), true);
1239
2577
  GetStr(&url_data::query, URL_FLAGS_HAS_QUERY, env->query_string(), true);
1240
2577
  GetStr(&url_data::fragment,
1241
         URL_FLAGS_HAS_FRAGMENT,
1242
         env->fragment_string(),
1243
2577
         true);
1244
1245
  Local<Value>
1246
10308
      path = base_obj->Get(env->context(), env->path_string()).ToLocalChecked();
1247
2577
  if (path->IsArray()) {
1248
2577
    base.flags |= URL_FLAGS_HAS_PATH;
1249
2577
    base.path = FromJSStringArray(env, path.As<Array>());
1250
  }
1251
2577
  return base;
1252
}
1253
1254
57005
url_data HarvestContext(Environment* env, Local<Object> context_obj) {
1255
57005
  url_data context;
1256
  Local<Value> flags =
1257
228022
      context_obj->Get(env->context(), env->flags_string()).ToLocalChecked();
1258
57006
  if (flags->IsInt32()) {
1259
    static constexpr int32_t kCopyFlagsMask =
1260
        URL_FLAGS_SPECIAL |
1261
        URL_FLAGS_CANNOT_BE_BASE |
1262
        URL_FLAGS_HAS_USERNAME |
1263
        URL_FLAGS_HAS_PASSWORD |
1264
        URL_FLAGS_HAS_HOST;
1265
114010
    context.flags |= flags.As<Int32>()->Value() & kCopyFlagsMask;
1266
  }
1267
  Local<Value> scheme =
1268
228024
      context_obj->Get(env->context(), env->scheme_string()).ToLocalChecked();
1269
114012
  if (scheme->IsString()) {
1270
114011
    Utf8Value value(env->isolate(), scheme);
1271
57006
    context.scheme.assign(*value, value.length());
1272
  }
1273
  Local<Value> port =
1274
228025
      context_obj->Get(env->context(), env->port_string()).ToLocalChecked();
1275
57006
  if (port->IsInt32())
1276
44
    context.port = port.As<Int32>()->Value();
1277
57006
  if (context.flags & URL_FLAGS_HAS_USERNAME) {
1278
    Local<Value> username =
1279
28
        context_obj->Get(env->context(),
1280
70
                         env->username_string()).ToLocalChecked();
1281
28
    CHECK(username->IsString());
1282
28
    Utf8Value value(env->isolate(), username);
1283
14
    context.username.assign(*value, value.length());
1284
  }
1285
57006
  if (context.flags & URL_FLAGS_HAS_PASSWORD) {
1286
    Local<Value> password =
1287
16
        context_obj->Get(env->context(),
1288
40
                         env->password_string()).ToLocalChecked();
1289
16
    CHECK(password->IsString());
1290
16
    Utf8Value value(env->isolate(), password);
1291
8
    context.password.assign(*value, value.length());
1292
  }
1293
  Local<Value> host =
1294
114012
      context_obj->Get(env->context(),
1295
285030
                       env->host_string()).ToLocalChecked();
1296
114012
  if (host->IsString()) {
1297
113992
    Utf8Value value(env->isolate(), host);
1298
56996
    context.host.assign(*value, value.length());
1299
  }
1300
57006
  return context;
1301
}
1302
1303
// Single dot segment can be ".", "%2e", or "%2E"
1304
3163160
bool IsSingleDotSegment(const std::string& str) {
1305
3163160
  switch (str.size()) {
1306
    case 1:
1307
1509
      return str == ".";
1308
    case 3:
1309
149314
      return str[0] == '%' &&
1310

149310
             str[1] == '2' &&
1311
149310
             ASCIILowercase(str[2]) == 'e';
1312
    default:
1313
3012367
      return false;
1314
  }
1315
}
1316
1317
// Double dot segment can be:
1318
//   "..", ".%2e", ".%2E", "%2e.", "%2E.",
1319
//   "%2e%2e", "%2E%2E", "%2e%2E", or "%2E%2e"
1320
1582775
bool IsDoubleDotSegment(const std::string& str) {
1321

1582775
  switch (str.size()) {
1322
    case 2:
1323
1773
      return str == "..";
1324
    case 4:
1325

383887
      if (str[0] != '.' && str[0] != '%')
1326
383873
        return false;
1327
25
      return ((str[0] == '.' &&
1328
13
               str[1] == '%' &&
1329
4
               str[2] == '2' &&
1330

33
               ASCIILowercase(str[3]) == 'e') ||
1331
15
              (str[0] == '%' &&
1332
6
               str[1] == '2' &&
1333
6
               ASCIILowercase(str[2]) == 'e' &&
1334
17
               str[3] == '.'));
1335
    case 6:
1336
62760
      return (str[0] == '%' &&
1337
8
              str[1] == '2' &&
1338
6
              ASCIILowercase(str[2]) == 'e' &&
1339
4
              str[3] == '%' &&
1340

62760
              str[4] == '2' &&
1341
62758
              ASCIILowercase(str[5]) == 'e');
1342
    default:
1343
1134359
      return false;
1344
  }
1345
}
1346
1347
2735
void ShortenUrlPath(struct url_data* url) {
1348
2735
  if (url->path.empty()) return;
1349


2785
  if (url->path.size() == 1 && url->scheme == "file:" &&
1350
175
      IsNormalizedWindowsDriveLetter(url->path[0])) return;
1351
2610
  url->path.pop_back();
1352
}
1353
1354
}  // anonymous namespace
1355
1356
221223
void URL::Parse(const char* input,
1357
                size_t len,
1358
                enum url_parse_state state_override,
1359
                struct url_data* url,
1360
                bool has_url,
1361
                const struct url_data* base,
1362
                bool has_base) {
1363
221223
  const char* p = input;
1364
221223
  const char* end = input + len;
1365
1366
221223
  if (!has_url) {
1367
138783
    for (const char* ptr = p; ptr < end; ptr++) {
1368
138760
      if (IsC0ControlOrSpace(*ptr))
1369
28
        p++;
1370
      else
1371
138732
        break;
1372
    }
1373
138780
    for (const char* ptr = end - 1; ptr >= p; ptr--) {
1374
138757
      if (IsC0ControlOrSpace(*ptr))
1375
25
        end--;
1376
      else
1377
138732
        break;
1378
    }
1379
138755
    input = p;
1380
138755
    len = end - p;
1381
  }
1382
1383
  // The spec says we should strip out any ASCII tabs or newlines.
1384
  // In those cases, we create another std::string instance with the filtered
1385
  // contents, but in the general case we avoid the overhead.
1386
440713
  std::string whitespace_stripped;
1387
17217913
  for (const char* ptr = p; ptr < end; ptr++) {
1388
16996709
    if (!IsASCIITabOrNewline(*ptr))
1389
16996690
      continue;
1390
    // Hit tab or newline. Allocate storage, copy what we have until now,
1391
    // and then iterate and filter all similar characters out.
1392
22
    whitespace_stripped.reserve(len - 1);
1393
22
    whitespace_stripped.assign(p, ptr - p);
1394
    // 'ptr + 1' skips the current char, which we know to be tab or newline.
1395
318
    for (ptr = ptr + 1; ptr < end; ptr++) {
1396
296
      if (!IsASCIITabOrNewline(*ptr))
1397
254
        whitespace_stripped += *ptr;
1398
    }
1399
1400
    // Update variables like they should have looked like if the string
1401
    // had been stripped of whitespace to begin with.
1402
22
    input = whitespace_stripped.c_str();
1403
22
    len = whitespace_stripped.size();
1404
22
    p = input;
1405
22
    end = input + len;
1406
22
    break;
1407
  }
1408
1409
221226
  bool atflag = false;  // Set when @ has been seen.
1410
221226
  bool square_bracket_flag = false;  // Set inside of [...]
1411
221226
  bool password_token_seen_flag = false;  // Set after a : after an username.
1412
1413
440716
  std::string buffer;
1414
1415
  // Set the initial parse state.
1416
221229
  const bool has_state_override = state_override != kUnknownState;
1417
221229
  enum url_parse_state state = has_state_override ? state_override :
1418
221229
                                                    kSchemeStart;
1419
1420

221229
  if (state < kSchemeStart || state > kFragment) {
1421
    url->flags |= URL_FLAGS_INVALID_PARSE_STATE;
1422
    return;
1423
  }
1424
1425

35175075
  while (p <= end) {
1426
17478662
    const char ch = p < end ? p[0] : kEOL;
1427
17478662
    bool special = (url->flags & URL_FLAGS_SPECIAL);
1428
    bool cannot_be_base;
1429

17478662
    const bool special_back_slash = (special && ch == '\\');
1430
1431





17478662
    switch (state) {
1432
      case kSchemeStart:
1433
138781
        if (IsASCIIAlpha(ch)) {
1434
136277
          buffer += ASCIILowercase(ch);
1435
136268
          state = kScheme;
1436
2504
        } else if (!has_state_override) {
1437
2501
          state = kNoScheme;
1438
2501
          continue;
1439
        } else {
1440
3
          url->flags |= URL_FLAGS_FAILED;
1441
3
          return;
1442
        }
1443
136268
        break;
1444
      case kScheme:
1445


548491
        if (IsASCIIAlphanumeric(ch) || ch == '+' || ch == '-' || ch == '.') {
1446
412214
          buffer += ASCIILowercase(ch);
1447

136277
        } else if (ch == ':' || (has_state_override && ch == kEOL)) {
1448

135733
          if (has_state_override && buffer.size() == 0) {
1449
            url->flags |= URL_FLAGS_TERMINATED;
1450
            return;
1451
          }
1452
135733
          buffer += ':';
1453
1454
135733
          bool new_is_special = IsSpecial(buffer);
1455
1456
135732
          if (has_state_override) {
1457

44
            if ((special != new_is_special) ||
1458
12
                ((buffer == "file:") &&
1459
2
                 ((url->flags & URL_FLAGS_HAS_USERNAME) ||
1460
                  (url->flags & URL_FLAGS_HAS_PASSWORD) ||
1461
                  (url->port != -1)))) {
1462
13
              url->flags |= URL_FLAGS_TERMINATED;
1463
13
              return;
1464
            }
1465
1466
            // File scheme && (host == empty or null) check left to JS-land
1467
            // as it can be done before even entering C++ binding.
1468
          }
1469
1470
135719
          url->scheme = std::move(buffer);
1471
135719
          url->port = NormalizePort(url->scheme, url->port);
1472
135719
          if (new_is_special) {
1473
134774
            url->flags |= URL_FLAGS_SPECIAL;
1474
134774
            special = true;
1475
          } else {
1476
945
            url->flags &= ~URL_FLAGS_SPECIAL;
1477
945
            special = false;
1478
          }
1479
135719
          buffer.clear();
1480
135719
          if (has_state_override)
1481
8
            return;
1482
135711
          if (url->scheme == "file:") {
1483
133124
            state = kFile;
1484

4236
          } else if (special &&
1485

3099
                     has_base &&
1486
511
                     url->scheme == base->scheme) {
1487
178
            state = kSpecialRelativeOrAuthority;
1488
2410
          } else if (special) {
1489
1470
            state = kSpecialAuthoritySlashes;
1490

940
          } else if (p + 1 < end && p[1] == '/') {
1491
260
            state = kPathOrAuthority;
1492
260
            p++;
1493
          } else {
1494
680
            url->flags |= URL_FLAGS_CANNOT_BE_BASE;
1495
680
            url->flags |= URL_FLAGS_HAS_PATH;
1496
680
            url->path.emplace_back("");
1497
680
            state = kCannotBeBase;
1498
135712
          }
1499
544
        } else if (!has_state_override) {
1500
542
          buffer.clear();
1501
542
          state = kNoScheme;
1502
542
          p = input;
1503
542
          continue;
1504
        } else {
1505
2
          url->flags |= URL_FLAGS_FAILED;
1506
2
          return;
1507
        }
1508
547926
        break;
1509
      case kNoScheme:
1510

3043
        cannot_be_base = has_base && (base->flags & URL_FLAGS_CANNOT_BE_BASE);
1511

3043
        if (!has_base || (cannot_be_base && ch != '#')) {
1512
1270
          url->flags |= URL_FLAGS_FAILED;
1513
1270
          return;
1514

1773
        } else if (cannot_be_base && ch == '#') {
1515
14
          url->scheme = base->scheme;
1516
14
          if (IsSpecial(url->scheme)) {
1517
            url->flags |= URL_FLAGS_SPECIAL;
1518
            special = true;
1519
          } else {
1520
14
            url->flags &= ~URL_FLAGS_SPECIAL;
1521
14
            special = false;
1522
          }
1523
14
          if (base->flags & URL_FLAGS_HAS_PATH) {
1524
14
            url->flags |= URL_FLAGS_HAS_PATH;
1525
14
            url->path = base->path;
1526
          }
1527
14
          if (base->flags & URL_FLAGS_HAS_QUERY) {
1528
2
            url->flags |= URL_FLAGS_HAS_QUERY;
1529
2
            url->query = base->query;
1530
          }
1531
14
          if (base->flags & URL_FLAGS_HAS_FRAGMENT) {
1532
            url->flags |= URL_FLAGS_HAS_FRAGMENT;
1533
            url->fragment = base->fragment;
1534
          }
1535
14
          url->flags |= URL_FLAGS_CANNOT_BE_BASE;
1536
14
          state = kFragment;
1537

3518
        } else if (has_base &&
1538
1759
                   base->scheme != "file:") {
1539
147
          state = kRelative;
1540
147
          continue;
1541
        } else {
1542
1612
          url->scheme = "file:";
1543
1612
          url->flags |= URL_FLAGS_SPECIAL;
1544
1612
          special = true;
1545
1612
          state = kFile;
1546
1612
          continue;
1547
        }
1548
14
        break;
1549
      case kSpecialRelativeOrAuthority:
1550

178
        if (ch == '/' && p + 1 < end && p[1] == '/') {
1551
162
          state = kSpecialAuthorityIgnoreSlashes;
1552
162
          p++;
1553
        } else {
1554
16
          state = kRelative;
1555
16
          continue;
1556
        }
1557
162
        break;
1558
      case kPathOrAuthority:
1559
260
        if (ch == '/') {
1560
202
          state = kAuthority;
1561
        } else {
1562
58
          state = kPath;
1563
58
          continue;
1564
        }
1565
202
        break;
1566
      case kRelative:
1567
163
        url->scheme = base->scheme;
1568
163
        if (IsSpecial(url->scheme)) {
1569
120
          url->flags |= URL_FLAGS_SPECIAL;
1570
120
          special = true;
1571
        } else {
1572
43
          url->flags &= ~URL_FLAGS_SPECIAL;
1573
43
          special = false;
1574
        }
1575

163
        switch (ch) {
1576
          case kEOL:
1577
8
            if (base->flags & URL_FLAGS_HAS_USERNAME) {
1578
2
              url->flags |= URL_FLAGS_HAS_USERNAME;
1579
2
              url->username = base->username;
1580
            }
1581
8
            if (base->flags & URL_FLAGS_HAS_PASSWORD) {
1582
2
              url->flags |= URL_FLAGS_HAS_PASSWORD;
1583
2
              url->password = base->password;
1584
            }
1585
8
            if (base->flags & URL_FLAGS_HAS_HOST) {
1586
8
              url->flags |= URL_FLAGS_HAS_HOST;
1587
8
              url->host = base->host;
1588
            }
1589
8
            if (base->flags & URL_FLAGS_HAS_QUERY) {
1590
              url->flags |= URL_FLAGS_HAS_QUERY;
1591
              url->query = base->query;
1592
            }
1593
8
            if (base->flags & URL_FLAGS_HAS_PATH) {
1594
8
              url->flags |= URL_FLAGS_HAS_PATH;
1595
8
              url->path = base->path;
1596
            }
1597
8
            url->port = base->port;
1598
8
            break;
1599
          case '/':
1600
35
            state = kRelativeSlash;
1601
35
            break;
1602
          case '?':
1603
24
            if (base->flags & URL_FLAGS_HAS_USERNAME) {
1604
              url->flags |= URL_FLAGS_HAS_USERNAME;
1605
              url->username = base->username;
1606
            }
1607
24
            if (base->flags & URL_FLAGS_HAS_PASSWORD) {
1608
              url->flags |= URL_FLAGS_HAS_PASSWORD;
1609
              url->password = base->password;
1610
            }
1611
24
            if (base->flags & URL_FLAGS_HAS_HOST) {
1612
22
              url->flags |= URL_FLAGS_HAS_HOST;
1613
22
              url->host = base->host;
1614
            }
1615
24
            if (base->flags & URL_FLAGS_HAS_PATH) {
1616
24
              url->flags |= URL_FLAGS_HAS_PATH;
1617
24
              url->path = base->path;
1618
            }
1619
24
            url->port = base->port;
1620
24
            state = kQuery;
1621
24
            break;
1622
          case '#':
1623
18
            if (base->flags & URL_FLAGS_HAS_USERNAME) {
1624
              url->flags |= URL_FLAGS_HAS_USERNAME;
1625
              url->username = base->username;
1626
            }
1627
18
            if (base->flags & URL_FLAGS_HAS_PASSWORD) {
1628
              url->flags |= URL_FLAGS_HAS_PASSWORD;
1629
              url->password = base->password;
1630
            }
1631
18
            if (base->flags & URL_FLAGS_HAS_HOST) {
1632
16
              url->flags |= URL_FLAGS_HAS_HOST;
1633
16
              url->host = base->host;
1634
            }
1635
18
            if (base->flags & URL_FLAGS_HAS_QUERY) {
1636
              url->flags |= URL_FLAGS_HAS_QUERY;
1637
              url->query = base->query;
1638
            }
1639
18
            if (base->flags & URL_FLAGS_HAS_PATH) {
1640
18
              url->flags |= URL_FLAGS_HAS_PATH;
1641
18
              url->path = base->path;
1642
            }
1643
18
            url->port = base->port;
1644
18
            state = kFragment;
1645
18
            break;
1646
          default:
1647
78
            if (special_back_slash) {
1648
4
              state = kRelativeSlash;
1649
            } else {
1650
74
              if (base->flags & URL_FLAGS_HAS_USERNAME) {
1651
1
                url->flags |= URL_FLAGS_HAS_USERNAME;
1652
1
                url->username = base->username;
1653
              }
1654
74
              if (base->flags & URL_FLAGS_HAS_PASSWORD) {
1655
1
                url->flags |= URL_FLAGS_HAS_PASSWORD;
1656
1
                url->password = base->password;
1657
              }
1658
74
              if (base->flags & URL_FLAGS_HAS_HOST) {
1659
68
                url->flags |= URL_FLAGS_HAS_HOST;
1660
68
                url->host = base->host;
1661
              }
1662
74
              if (base->flags & URL_FLAGS_HAS_PATH) {
1663
74
                url->flags |= URL_FLAGS_HAS_PATH;
1664
74
                url->path = base->path;
1665
74
                ShortenUrlPath(url);
1666
              }
1667
74
              url->port = base->port;
1668
74
              state = kPath;
1669
74
              continue;
1670
            }
1671
        }
1672
89
        break;
1673
      case kRelativeSlash:
1674


39
        if (IsSpecial(url->scheme) && (ch == '/' || ch == '\\')) {
1675
8
          state = kSpecialAuthorityIgnoreSlashes;
1676
31
        } else if (ch == '/') {
1677
3
          state = kAuthority;
1678
        } else {
1679
28
          if (base->flags & URL_FLAGS_HAS_USERNAME) {
1680
4
            url->flags |= URL_FLAGS_HAS_USERNAME;
1681
4
            url->username = base->username;
1682
          }
1683
28
          if (base->flags & URL_FLAGS_HAS_PASSWORD) {
1684
2
            url->flags |= URL_FLAGS_HAS_PASSWORD;
1685
2
            url->password = base->password;
1686
          }
1687
28
          if (base->flags & URL_FLAGS_HAS_HOST) {
1688
26
            url->flags |= URL_FLAGS_HAS_HOST;
1689
26
            url->host = base->host;
1690
          }
1691
28
          url->port = base->port;
1692
28
          state = kPath;
1693
28
          continue;
1694
        }
1695
11
        break;
1696
      case kSpecialAuthoritySlashes:
1697
1470
        state = kSpecialAuthorityIgnoreSlashes;
1698

1470
        if (ch == '/' && p + 1 < end && p[1] == '/') {
1699
1385
          p++;
1700
        } else {
1701
85
          continue;
1702
        }
1703
1385
        break;
1704
      case kSpecialAuthorityIgnoreSlashes:
1705

1683
        if (ch != '/' && ch != '\\') {
1706
1640
          state = kAuthority;
1707
1640
          continue;
1708
        }
1709
43
        break;
1710
      case kAuthority:
1711
56260
        if (ch == '@') {
1712
157
          if (atflag) {
1713
13
            buffer.reserve(buffer.size() + 3);
1714
13
            buffer.insert(0, "%40");
1715
          }
1716
157
          atflag = true;
1717
157
          size_t blen = buffer.size();
1718

157
          if (blen > 0 && buffer[0] != ':') {
1719
99
            url->flags |= URL_FLAGS_HAS_USERNAME;
1720
          }
1721
741
          for (size_t n = 0; n < blen; n++) {
1722
584
            const char bch = buffer[n];
1723
584
            if (bch == ':') {
1724
87
              url->flags |= URL_FLAGS_HAS_PASSWORD;
1725
87
              if (!password_token_seen_flag) {
1726
85
                password_token_seen_flag = true;
1727
85
                continue;
1728
              }
1729
            }
1730
499
            if (password_token_seen_flag) {
1731
189
              AppendOrEscape(&url->password, bch, USERINFO_ENCODE_SET);
1732
            } else {
1733
310
              AppendOrEscape(&url->username, bch, USERINFO_ENCODE_SET);
1734
            }
1735
          }
1736
157
          buffer.clear();
1737

56103
        } else if (ch == kEOL ||
1738
54294
                   ch == '/' ||
1739
54276
                   ch == '?' ||
1740
54266
                   ch == '#' ||
1741
                   special_back_slash) {
1742

1845
          if (atflag && buffer.size() == 0) {
1743
39
            url->flags |= URL_FLAGS_FAILED;
1744
39
            return;
1745
          }
1746
1806
          p -= buffer.size() + 1;
1747
1806
          buffer.clear();
1748
1806
          state = kHost;
1749
        } else {
1750
54258
          buffer += ch;
1751
        }
1752
56221
        break;
1753
      case kHost:
1754
      case kHostname:
1755

55417
        if (has_state_override && url->scheme == "file:") {
1756
6
          state = kFileHost;
1757
6
          continue;
1758

55411
        } else if (ch == ':' && !square_bracket_flag) {
1759
577
          if (buffer.size() == 0) {
1760
19
            url->flags |= URL_FLAGS_FAILED;
1761
19
            return;
1762
          }
1763
558
          url->flags |= URL_FLAGS_HAS_HOST;
1764
558
          if (!ParseHost(buffer, &url->host, special)) {
1765
3
            url->flags |= URL_FLAGS_FAILED;
1766
3
            return;
1767
          }
1768
555
          buffer.clear();
1769
555
          state = kPort;
1770
1108
          if (state_override == kHostname) {
1771
2
            return;
1772
          }
1773

54834
        } else if (ch == kEOL ||
1774
53510
                   ch == '/' ||
1775
53488
                   ch == '?' ||
1776
53474
                   ch == '#' ||
1777
                   special_back_slash) {
1778
1370
          p--;
1779

1370
          if (special && buffer.size() == 0) {
1780
12
            url->flags |= URL_FLAGS_FAILED;
1781
12
            return;
1782
          }
1783

1477
          if (has_state_override &&
1784

1380
              buffer.size() == 0 &&
1785

50
              ((url->username.size() > 0 || url->password.size() > 0) ||
1786
16
               url->port != -1)) {
1787
4
            url->flags |= URL_FLAGS_TERMINATED;
1788
4
            return;
1789
          }
1790
1354
          url->flags |= URL_FLAGS_HAS_HOST;
1791
1354
          if (!ParseHost(buffer, &url->host, special)) {
1792
216
            url->flags |= URL_FLAGS_FAILED;
1793
216
            return;
1794
          }
1795
1138
          buffer.clear();
1796
1138
          state = kPathStart;
1797
2197
          if (has_state_override) {
1798
79
            return;
1799
          }
1800
        } else {
1801
53464
          if (ch == '[')
1802
93
            square_bracket_flag = true;
1803
53464
          if (ch == ']')
1804
90
            square_bracket_flag = false;
1805
53464
          buffer += ch;
1806
        }
1807
55076
        break;
1808
      case kPort:
1809
3181
        if (IsASCIIDigit(ch)) {
1810
2611
          buffer += ch;
1811

570
        } else if (has_state_override ||
1812
185
                   ch == kEOL ||
1813
27
                   ch == '/' ||
1814
27
                   ch == '?' ||
1815
27
                   ch == '#' ||
1816
                   special_back_slash) {
1817
543
          if (buffer.size() > 0) {
1818
538
            unsigned port = 0;
1819
            // the condition port <= 0xffff prevents integer overflow
1820

2987
            for (size_t i = 0; port <= 0xffff && i < buffer.size(); i++)
1821
2449
              port = port * 10 + buffer[i] - '0';
1822
538
            if (port > 0xffff) {
1823
              // TODO(TimothyGu): This hack is currently needed for the host
1824
              // setter since it needs access to hostname if it is valid, and
1825
              // if the FAILED flag is set the entire response to JS layer
1826
              // will be empty.
1827
18
              if (state_override == kHost)
1828
1
                url->port = -1;
1829
              else
1830
17
                url->flags |= URL_FLAGS_FAILED;
1831
18
              return;
1832
            }
1833
            // the port is valid
1834
520
            url->port = NormalizePort(url->scheme, static_cast<int>(port));
1835
520
            if (url->port == -1)
1836
27
              url->flags |= URL_FLAGS_IS_DEFAULT_SCHEME_PORT;
1837
520
            buffer.clear();
1838
5
          } else if (has_state_override) {
1839
            // TODO(TimothyGu): Similar case as above.
1840
1
            if (state_override == kHost)
1841
1
              url->port = -1;
1842
            else
1843
              url->flags |= URL_FLAGS_TERMINATED;
1844
1
            return;
1845
          }
1846
524
          state = kPathStart;
1847
524
          continue;
1848
        } else {
1849
27
          url->flags |= URL_FLAGS_FAILED;
1850
27
          return;
1851
        }
1852
2611
        break;
1853
      case kFile:
1854
134736
        url->scheme = "file:";
1855

134735
        if (ch == '/' || ch == '\\') {
1856
133220
          state = kFileSlash;
1857

1515
        } else if (has_base && base->scheme == "file:") {
1858

1508
          switch (ch) {
1859
            case kEOL:
1860
15
              if (base->flags & URL_FLAGS_HAS_HOST) {
1861
15
                url->flags |= URL_FLAGS_HAS_HOST;
1862
15
                url->host = base->host;
1863
              }
1864
15
              if (base->flags & URL_FLAGS_HAS_PATH) {
1865
15
                url->flags |= URL_FLAGS_HAS_PATH;
1866
15
                url->path = base->path;
1867
              }
1868
15
              if (base->flags & URL_FLAGS_HAS_QUERY) {
1869
2
                url->flags |= URL_FLAGS_HAS_QUERY;
1870
2
                url->query = base->query;
1871
              }
1872
15
              break;
1873
            case '?':
1874
2
              if (base->flags & URL_FLAGS_HAS_HOST) {
1875
2
                url->flags |= URL_FLAGS_HAS_HOST;
1876
2
                url->host = base->host;
1877
              }
1878
2
              if (base->flags & URL_FLAGS_HAS_PATH) {
1879
2
                url->flags |= URL_FLAGS_HAS_PATH;
1880
2
                url->path = base->path;
1881
              }
1882
2
              url->flags |= URL_FLAGS_HAS_QUERY;
1883
2
              url->query.clear();
1884
2
              state = kQuery;
1885
2
              break;
1886
            case '#':
1887
2
              if (base->flags & URL_FLAGS_HAS_HOST) {
1888
2
                url->flags |= URL_FLAGS_HAS_HOST;
1889
2
                url->host = base->host;
1890
              }
1891
2
              if (base->flags & URL_FLAGS_HAS_PATH) {
1892
2
                url->flags |= URL_FLAGS_HAS_PATH;
1893
2
                url->path = base->path;
1894
              }
1895
2
              if (base->flags & URL_FLAGS_HAS_QUERY) {
1896
2
                url->flags |= URL_FLAGS_HAS_QUERY;
1897
2
                url->query = base->query;
1898
              }
1899
2
              url->flags |= URL_FLAGS_HAS_FRAGMENT;
1900
2
              url->fragment.clear();
1901
2
              state = kFragment;
1902
2
              break;
1903
            default:
1904
1489
              if (!StartsWithWindowsDriveLetter(p, end)) {
1905
1480
                if (base->flags & URL_FLAGS_HAS_HOST) {
1906
1480
                  url->flags |= URL_FLAGS_HAS_HOST;
1907
1480
                  url->host = base->host;
1908
                }
1909
1480
                if (base->flags & URL_FLAGS_HAS_PATH) {
1910
1480
                  url->flags |= URL_FLAGS_HAS_PATH;
1911
1480
                  url->path = base->path;
1912
                }
1913
1480
                ShortenUrlPath(url);
1914
              }
1915
1489
              state = kPath;
1916
1489
              continue;
1917
          }
1918
        } else {
1919
7
          state = kPath;
1920
7
          continue;
1921
        }
1922
133239
        break;
1923
      case kFileSlash:
1924

133221
        if (ch == '/' || ch == '\\') {
1925
133120
          state = kFileHost;
1926
        } else {
1927

202
          if (has_base &&
1928

199
              base->scheme == "file:" &&
1929
98
              !StartsWithWindowsDriveLetter(p, end)) {
1930
93
            if (IsNormalizedWindowsDriveLetter(base->path[0])) {
1931
1
              url->flags |= URL_FLAGS_HAS_PATH;
1932
1
              url->path.push_back(base->path[0]);
1933
            } else {
1934
92
              if (base->flags & URL_FLAGS_HAS_HOST) {
1935
92
                url->flags |= URL_FLAGS_HAS_HOST;
1936
92
                url->host = base->host;
1937
              } else {
1938
                url->flags &= ~URL_FLAGS_HAS_HOST;
1939
                url->host.clear();
1940
              }
1941
            }
1942
          }
1943
101
          state = kPath;
1944
101
          continue;
1945
        }
1946
133120
        break;
1947
      case kFileHost:
1948

133520
        if (ch == kEOL ||
1949
400
            ch == '/' ||
1950
395
            ch == '\\' ||
1951
395
            ch == '?' ||
1952
            ch == '#') {
1953

399369
          if (!has_state_override &&
1954

133132
              buffer.size() == 2 &&
1955
7
              IsWindowsDriveLetter(buffer)) {
1956
4
            state = kPath;
1957
133121
          } else if (buffer.size() == 0) {
1958
133057
            url->flags |= URL_FLAGS_HAS_HOST;
1959
133057
            url->host.clear();
1960
133057
            if (has_state_override)
1961
2
              return;
1962
133055
            state = kPathStart;
1963
          } else {
1964
112
            std::string host;
1965
64
            if (!ParseHost(buffer, &host, special)) {
1966
14
              url->flags |= URL_FLAGS_FAILED;
1967
14
              return;
1968
            }
1969
50
            if (host == "localhost")
1970
11
              host.clear();
1971
50
            url->flags |= URL_FLAGS_HAS_HOST;
1972
50
            url->host = host;
1973
50
            if (has_state_override)
1974
2
              return;
1975
48
            buffer.clear();
1976
48
            state = kPathStart;
1977
          }
1978
133107
          continue;
1979
        } else {
1980
395
          buffer += ch;
1981
        }
1982
395
        break;
1983
      case kPathStart:
1984
216832
        if (IsSpecial(url->scheme)) {
1985
216659
          state = kPath;
1986

216659
          if (ch != '/' && ch != '\\') {
1987
82681
            continue;
1988
          }
1989

172
        } else if (!has_state_override && ch == '?') {
1990
3
          url->flags |= URL_FLAGS_HAS_QUERY;
1991
3
          url->query.clear();
1992
3
          state = kQuery;
1993

169
        } else if (!has_state_override && ch == '#') {
1994
3
          url->flags |= URL_FLAGS_HAS_FRAGMENT;
1995
3
          url->fragment.clear();
1996
3
          state = kFragment;
1997
166
        } else if (ch != kEOL) {
1998
126
          state = kPath;
1999
126
          if (ch != '/') {
2000
6
            continue;
2001
          }
2002
        }
2003
134144
        break;
2004
      case kPath:
2005

16028992
        if (ch == kEOL ||
2006
14446372
            ch == '/' ||
2007
14446338
            special_back_slash ||
2008

19966857
            (!has_state_override && (ch == '?' || ch == '#'))) {
2009
1582774
          if (IsDoubleDotSegment(buffer)) {
2010
1181
            ShortenUrlPath(url);
2011

1181
            if (ch != '/' && !special_back_slash) {
2012
18
              url->flags |= URL_FLAGS_HAS_PATH;
2013
18
              url->path.emplace_back("");
2014
            }
2015

3163644
          } else if (IsSingleDotSegment(buffer) &&
2016

1581625
                     ch != '/' && !special_back_slash) {
2017
29
            url->flags |= URL_FLAGS_HAS_PATH;
2018
29
            url->path.emplace_back("");
2019
1581566
          } else if (!IsSingleDotSegment(buffer)) {
2020

4741270
            if (url->scheme == "file:" &&
2021
1769045
                url->path.empty() &&
2022

1771232
                buffer.size() == 2 &&
2023
36
                IsWindowsDriveLetter(buffer)) {
2024

51
              if ((url->flags & URL_FLAGS_HAS_HOST) &&
2025
16
                  !url->host.empty()) {
2026
3
                url->host.clear();
2027
3
                url->flags |= URL_FLAGS_HAS_HOST;
2028
              }
2029
35
              buffer[1] = ':';
2030
            }
2031
1581139
            url->flags |= URL_FLAGS_HAS_PATH;
2032
1581139
            url->path.emplace_back(std::move(buffer));
2033
          }
2034
1582775
          buffer.clear();
2035

1799608
          if (url->scheme == "file:" &&
2036
1363715
              (ch == kEOL ||
2037
1363703
               ch == '?' ||
2038
               ch == '#')) {
2039

267883
            while (url->path.size() > 1 && url->path[0].length() == 0) {
2040
25524
              url->path.erase(url->path.begin());
2041
            }
2042
          }
2043
3165546
          if (ch == '?') {
2044
109
            url->flags |= URL_FLAGS_HAS_QUERY;
2045
109
            state = kQuery;
2046
1582664
          } else if (ch == '#') {
2047
11
            state = kFragment;
2048
          }
2049
        } else {
2050
14446218
          AppendOrEscape(&buffer, ch, PATH_ENCODE_SET);
2051
        }
2052
16028998
        break;
2053
      case kCannotBeBase:
2054
18847
        switch (ch) {
2055
          case '?':
2056
2
            state = kQuery;
2057
2
            break;
2058
          case '#':
2059
5
            state = kFragment;
2060
5
            break;
2061
          default:
2062
18840
            if (url->path.size() == 0)
2063
              url->path.emplace_back("");
2064

18840
            if (url->path.size() > 0 && ch != kEOL)
2065
18167
              AppendOrEscape(&url->path[0], ch, C0_CONTROL_ENCODE_SET);
2066
        }
2067
18847
        break;
2068
      case kQuery:
2069

2973
        if (ch == kEOL || (!has_state_override && ch == '#')) {
2070
255
          url->flags |= URL_FLAGS_HAS_QUERY;
2071
255
          url->query = std::move(buffer);
2072
255
          buffer.clear();
2073
510
          if (ch == '#')
2074
54
            state = kFragment;
2075
        } else {
2076
2718
          AppendOrEscape(&buffer, ch, special ? QUERY_ENCODE_SET_SPECIAL :
2077
2718
                                                QUERY_ENCODE_SET_NONSPECIAL);
2078
        }
2079
2973
        break;
2080
      case kFragment:
2081
575
        switch (ch) {
2082
          case kEOL:
2083
126
            url->flags |= URL_FLAGS_HAS_FRAGMENT;
2084
126
            url->fragment = std::move(buffer);
2085
126
            break;
2086
          case 0:
2087
2
            break;
2088
          default:
2089
447
            AppendOrEscape(&buffer, ch, FRAGMENT_ENCODE_SET);
2090
        }
2091
575
        break;
2092
      default:
2093
        url->flags |= URL_FLAGS_INVALID_PARSE_STATE;
2094
        return;
2095
    }
2096
2097
17252299
    p++;
2098
  }
2099
}  // NOLINT(readability/fn_size)
2100
2101
namespace {
2102
168642
void SetArgs(Environment* env,
2103
             Local<Value> argv[ARG_COUNT],
2104
             const struct url_data& url) {
2105
168642
  Isolate* isolate = env->isolate();
2106
337282
  argv[ARG_FLAGS] = Integer::NewFromUnsigned(isolate, url.flags);
2107
168642
  argv[ARG_PROTOCOL] =
2108
168641
      url.flags & URL_FLAGS_SPECIAL ?
2109
167653
          GetSpecial(env, url.scheme) :
2110
673577
          OneByteString(isolate, url.scheme.c_str());
2111
168642
  if (url.flags & URL_FLAGS_HAS_USERNAME)
2112
176
    argv[ARG_USERNAME] = Utf8String(isolate, url.username);
2113
168642
  if (url.flags & URL_FLAGS_HAS_PASSWORD)
2114
152
    argv[ARG_PASSWORD] = Utf8String(isolate, url.password);
2115
168642
  if (url.flags & URL_FLAGS_HAS_HOST)
2116
335686
    argv[ARG_HOST] = Utf8String(isolate, url.host);
2117
168642
  if (url.flags & URL_FLAGS_HAS_QUERY)
2118
514
    argv[ARG_QUERY] = Utf8String(isolate, url.query);
2119
168642
  if (url.flags & URL_FLAGS_HAS_FRAGMENT)
2120
244
    argv[ARG_FRAGMENT] = Utf8String(isolate, url.fragment);
2121
168642
  if (url.port > -1)
2122
1008
    argv[ARG_PORT] = Integer::New(isolate, url.port);
2123
168642
  if (url.flags & URL_FLAGS_HAS_PATH)
2124
336733
    argv[ARG_PATH] = ToV8Value(env->context(), url.path).ToLocalChecked();
2125
168643
}
2126
2127
170278
void Parse(Environment* env,
2128
           Local<Value> recv,
2129
           const char* input,
2130
           size_t len,
2131
           enum url_parse_state state_override,
2132
           Local<Value> base_obj,
2133
           Local<Value> context_obj,
2134
           Local<Function> cb,
2135
           Local<Value> error_cb) {
2136
170278
  Isolate* isolate = env->isolate();
2137
170278
  Local<Context> context = env->context();
2138
340538
  HandleScope handle_scope(isolate);
2139
170260
  Context::Scope context_scope(context);
2140
2141
170278
  const bool has_context = context_obj->IsObject();
2142
170278
  const bool has_base = base_obj->IsObject();
2143
2144
340539
  url_data base;
2145
340539
  url_data url;
2146
170278
  if (has_context)
2147
57006
    url = HarvestContext(env, context_obj.As<Object>());
2148
170278
  if (has_base)
2149
2577
    base = HarvestBase(env, base_obj.As<Object>());
2150
2151
170278
  URL::Parse(input, len, state_override, &url, has_context, &base, has_base);
2152

170278
  if ((url.flags & URL_FLAGS_INVALID_PARSE_STATE) ||
2153
57006
      ((state_override != kUnknownState) &&
2154
57006
       (url.flags & URL_FLAGS_TERMINATED)))
2155
17
    return;
2156
2157
  // Define the return value placeholders
2158
  const Local<Value> undef = Undefined(isolate);
2159
  const Local<Value> null = Null(isolate);
2160
170261
  if (!(url.flags & URL_FLAGS_FAILED)) {
2161
    Local<Value> argv[] = {
2162
      undef,
2163
      undef,
2164
      undef,
2165
      undef,
2166
      null,  // host defaults to null
2167
      null,  // port defaults to null
2168
      undef,
2169
      null,  // query defaults to null
2170
      null,  // fragment defaults to null
2171
168642
    };
2172
168642
    SetArgs(env, argv, url);
2173
505922
    cb->Call(context, recv, arraysize(argv), argv).FromMaybe(Local<Value>());
2174
1619
  } else if (error_cb->IsFunction()) {
2175
1572
    Local<Value> argv[2] = { undef, undef };
2176
3144
    argv[ERR_ARG_FLAGS] = Integer::NewFromUnsigned(isolate, url.flags);
2177
1572
    argv[ERR_ARG_INPUT] =
2178
3144
      String::NewFromUtf8(env->isolate(),
2179
                          input,
2180
3144
                          NewStringType::kNormal).ToLocalChecked();
2181
6288
    error_cb.As<Function>()->Call(context, recv, arraysize(argv), argv)
2182
1572
        .FromMaybe(Local<Value>());
2183
  }
2184
}
2185
2186
170278
void Parse(const FunctionCallbackInfo<Value>& args) {
2187
170278
  Environment* env = Environment::GetCurrent(args);
2188
170279
  CHECK_GE(args.Length(), 5);
2189
510837
  CHECK(args[0]->IsString());  // input
2190


694740
  CHECK(args[2]->IsUndefined() ||  // base context
2191
        args[2]->IsNull() ||
2192
        args[2]->IsObject());
2193


795867
  CHECK(args[3]->IsUndefined() ||  // context
2194
        args[3]->IsNull() ||
2195
        args[3]->IsObject());
2196
340556
  CHECK(args[4]->IsFunction());  // complete callback
2197

737375
  CHECK(args[5]->IsUndefined() || args[5]->IsFunction());  // error callback
2198
2199
340554
  Utf8Value input(env->isolate(), args[0]);
2200
170278
  enum url_parse_state state_override = kUnknownState;
2201
340556
  if (args[1]->IsNumber()) {
2202
170278
    state_override = static_cast<enum url_parse_state>(
2203
851390
        args[1]->Uint32Value(env->context()).FromJust());
2204
  }
2205
2206
340555
  Parse(env, args.This(),
2207
170278
        *input, input.length(),
2208
        state_override,
2209
        args[2],
2210
        args[3],
2211
340555
        args[4].As<Function>(),
2212
170278
        args[5]);
2213
170277
}
2214
2215
22
void EncodeAuthSet(const FunctionCallbackInfo<Value>& args) {
2216
22
  Environment* env = Environment::GetCurrent(args);
2217
22
  CHECK_GE(args.Length(), 1);
2218
66
  CHECK(args[0]->IsString());
2219
44
  Utf8Value value(env->isolate(), args[0]);
2220
44
  std::string output;
2221
22
  size_t len = value.length();
2222
22
  output.reserve(len);
2223
233
  for (size_t n = 0; n < len; n++) {
2224
211
    const char ch = (*value)[n];
2225
211
    AppendOrEscape(&output, ch, USERINFO_ENCODE_SET);
2226
  }
2227
44
  args.GetReturnValue().Set(
2228
44
      String::NewFromUtf8(env->isolate(),
2229
                          output.c_str(),
2230
22
                          NewStringType::kNormal).ToLocalChecked());
2231
22
}
2232
2233
11
void ToUSVString(const FunctionCallbackInfo<Value>& args) {
2234
11
  Environment* env = Environment::GetCurrent(args);
2235
11
  CHECK_GE(args.Length(), 2);
2236
33
  CHECK(args[0]->IsString());
2237
22
  CHECK(args[1]->IsNumber());
2238
2239
22
  TwoByteValue value(env->isolate(), args[0]);
2240
2241
44
  int64_t start = args[1]->IntegerValue(env->context()).FromJust();
2242
11
  CHECK_GE(start, 0);
2243
2244
32
  for (size_t i = start; i < value.length(); i++) {
2245
21
    char16_t c = value[i];
2246
21
    if (!IsUnicodeSurrogate(c)) {
2247
8
      continue;
2248

13
    } else if (IsUnicodeSurrogateTrail(c) || i == value.length() - 1) {
2249
12
      value[i] = kUnicodeReplacementCharacter;
2250
    } else {
2251
1
      char16_t d = value[i + 1];
2252
1
      if (IsUnicodeTrail(d)) {
2253
        i++;
2254
      } else {
2255
1
        value[i] = kUnicodeReplacementCharacter;
2256
      }
2257
    }
2258
  }
2259
2260
22
  args.GetReturnValue().Set(
2261
22
      String::NewFromTwoByte(env->isolate(),
2262
11
                             *value,
2263
                             NewStringType::kNormal,
2264
22
                             value.length()).ToLocalChecked());
2265
11
}
2266
2267
222
void DomainToASCII(const FunctionCallbackInfo<Value>& args) {
2268
222
  Environment* env = Environment::GetCurrent(args);
2269
222
  CHECK_GE(args.Length(), 1);
2270
666
  CHECK(args[0]->IsString());
2271
435
  Utf8Value value(env->isolate(), args[0]);
2272
2273
435
  URLHost host;
2274
  // Assuming the host is used for a special scheme.
2275
222
  host.ParseHost(*value, value.length(), true);
2276
222
  if (host.ParsingFailed()) {
2277
27
    args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING(env->isolate(), ""));
2278
9
    return;
2279
  }
2280
426
  std::string out = host.ToStringMove();
2281
426
  args.GetReturnValue().Set(
2282
426
      String::NewFromUtf8(env->isolate(),
2283
                          out.c_str(),
2284
213
                          NewStringType::kNormal).ToLocalChecked());
2285
}
2286
2287
202
void DomainToUnicode(const FunctionCallbackInfo<Value>& args) {
2288
202
  Environment* env = Environment::GetCurrent(args);
2289
202
  CHECK_GE(args.Length(), 1);
2290
606
  CHECK(args[0]->IsString());
2291
395
  Utf8Value value(env->isolate(), args[0]);
2292
2293
395
  URLHost host;
2294
  // Assuming the host is used for a special scheme.
2295
202
  host.ParseHost(*value, value.length(), true, true);
2296
202
  if (host.ParsingFailed()) {
2297
27
    args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING(env->isolate(), ""));
2298
9
    return;
2299
  }
2300
386
  std::string out = host.ToStringMove();
2301
386
  args.GetReturnValue().Set(
2302
386
      String::NewFromUtf8(env->isolate(),
2303
                          out.c_str(),
2304
193
                          NewStringType::kNormal).ToLocalChecked());
2305
}
2306
2307
4703
void SetURLConstructor(const FunctionCallbackInfo<Value>& args) {
2308
4703
  Environment* env = Environment::GetCurrent(args);
2309
4703
  CHECK_EQ(args.Length(), 1);
2310
9406
  CHECK(args[0]->IsFunction());
2311
9406
  env->set_url_constructor_function(args[0].As<Function>());
2312
4703
}
2313
2314
4703
void Initialize(Local<Object> target,
2315
                Local<Value> unused,
2316
                Local<Context> context,
2317
                void* priv) {
2318
4703
  Environment* env = Environment::GetCurrent(context);
2319
4703
  env->SetMethod(target, "parse", Parse);
2320
4703
  env->SetMethodNoSideEffect(target, "encodeAuth", EncodeAuthSet);
2321
4703
  env->SetMethodNoSideEffect(target, "toUSVString", ToUSVString);
2322
4703
  env->SetMethodNoSideEffect(target, "domainToASCII", DomainToASCII);
2323
4703
  env->SetMethodNoSideEffect(target, "domainToUnicode", DomainToUnicode);
2324
4703
  env->SetMethod(target, "setURLConstructor", SetURLConstructor);
2325
2326
#define XX(name, _) NODE_DEFINE_CONSTANT(target, name);
2327
244556
  FLAGS(XX)
2328
#undef XX
2329
2330
#define XX(name) NODE_DEFINE_CONSTANT(target, name);
2331
395052
  PARSESTATES(XX)
2332
#undef XX
2333
4703
}
2334
}  // namespace
2335
2336
8
std::string URL::ToFilePath() const {
2337
8
  if (context_.scheme != "file:") {
2338
1
    return "";
2339
  }
2340
2341
#ifdef _WIN32
2342
  const char* slash = "\\";
2343
  auto is_slash = [] (char ch) {
2344
    return ch == '/' || ch == '\\';
2345
  };
2346
#else
2347
7
  const char* slash = "/";
2348
46
  auto is_slash = [] (char ch) {
2349
    return ch == '/';
2350
46
  };
2351

14
  if ((context_.flags & URL_FLAGS_HAS_HOST) &&
2352
7
      context_.host.length() > 0) {
2353
1
    return "";
2354
  }
2355
#endif
2356
12
  std::string decoded_path;
2357
18
  for (const std::string& part : context_.path) {
2358
25
    std::string decoded = PercentDecode(part.c_str(), part.length());
2359
58
    for (char& ch : decoded) {
2360
46
      if (is_slash(ch)) {
2361
1
        return "";
2362
      }
2363
    }
2364
12
    decoded_path += slash + decoded;
2365
  }
2366
2367
#ifdef _WIN32
2368
  // TODO(TimothyGu): Use "\\?\" long paths on Windows.
2369
2370
  // If hostname is set, then we have a UNC path. Pass the hostname through
2371
  // ToUnicode just in case it is an IDN using punycode encoding. We do not
2372
  // need to worry about percent encoding because the URL parser will have
2373
  // already taken care of that for us. Note that this only causes IDNs with an
2374
  // appropriate `xn--` prefix to be decoded.
2375
  if ((context_.flags & URL_FLAGS_HAS_HOST) &&
2376
      context_.host.length() > 0) {
2377
    std::string unicode_host;
2378
    if (!ToUnicode(context_.host, &unicode_host)) {
2379
      return "";
2380
    }
2381
    return "\\\\" + unicode_host + decoded_path;
2382
  }
2383
  // Otherwise, it's a local path that requires a drive letter.
2384
  if (decoded_path.length() < 3) {
2385
    return "";
2386
  }
2387
  if (decoded_path[2] != ':' ||
2388
      !IsASCIIAlpha(decoded_path[1])) {
2389
    return "";
2390
  }
2391
  // Strip out the leading '\'.
2392
  return decoded_path.substr(1);
2393
#else
2394
5
  return decoded_path;
2395
#endif
2396
}
2397
2398
25463
URL URL::FromFilePath(const std::string& file_path) {
2399
25463
  URL url("file://");
2400
50926
  std::string escaped_file_path;
2401
3088055
  for (size_t i = 0; i < file_path.length(); ++i) {
2402
3062592
    escaped_file_path += file_path[i];
2403
3062592
    if (file_path[i] == '%')
2404
8
      escaped_file_path += "25";
2405
  }
2406
25463
  URL::Parse(escaped_file_path.c_str(), escaped_file_path.length(), kPathStart,
2407
25463
             &url.context_, true, nullptr, false);
2408
50926
  return url;
2409
}
2410
2411
// This function works by calling out to a JS function that creates and
2412
// returns the JS URL object. Be mindful of the JS<->Native boundary
2413
// crossing that is required.
2414
MaybeLocal<Value> URL::ToObject(Environment* env) const {
2415
  Isolate* isolate = env->isolate();
2416
  Local<Context> context = env->context();
2417
  Context::Scope context_scope(context);
2418
2419
  const Local<Value> undef = Undefined(isolate);
2420
  const Local<Value> null = Null(isolate);
2421
2422
  if (context_.flags & URL_FLAGS_FAILED)
2423
    return Local<Value>();
2424
2425
  Local<Value> argv[] = {
2426
    undef,
2427
    undef,
2428
    undef,
2429
    undef,
2430
    null,  // host defaults to null
2431
    null,  // port defaults to null
2432
    undef,
2433
    null,  // query defaults to null
2434
    null,  // fragment defaults to null
2435
  };
2436
  SetArgs(env, argv, context_);
2437
2438
  MaybeLocal<Value> ret;
2439
  {
2440
    TryCatchScope try_catch(env, TryCatchScope::CatchMode::kFatal);
2441
2442
    // The SetURLConstructor method must have been called already to
2443
    // set the constructor function used below. SetURLConstructor is
2444
    // called automatically when the internal/url.js module is loaded
2445
    // during the internal/bootstrap/node.js processing.
2446
    ret = env->url_constructor_function()
2447
        ->Call(env->context(), undef, arraysize(argv), argv);
2448
  }
2449
2450
  return ret;
2451
}
2452
2453
}  // namespace url
2454
}  // namespace node
2455
2456
4398
NODE_MODULE_CONTEXT_AWARE_INTERNAL(url, node::url::Initialize)