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: 1165 1211 96.2 %
Date: 2020-08-22 22:13:06 Branches: 1069 1198 89.2 %

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

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

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

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


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


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

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








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


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


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

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

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

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


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



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



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









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

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

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

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

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

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

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

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

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

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

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

2706
    switch (R) {
931
      case 8:
932

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

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

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

143
  if (tooBigNumbers > 1 ||
991

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

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

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

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

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

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

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

1280424
  switch (str.size()) {
1323
    case 2:
1324
1710
      return str == "..";
1325
    case 4:
1326

315295
      if (str[0] != '.' && str[0] != '%')
1327
315282
        return false;
1328
23
      return ((str[0] == '.' &&
1329
12
               str[1] == '%' &&
1330
4
               str[2] == '2' &&
1331

31
               ASCIILowercase(str[3]) == 'e') ||
1332
14
              (str[0] == '%' &&
1333
6
               str[1] == '2' &&
1334
6
               ASCIILowercase(str[2]) == 'e' &&
1335
16
               str[3] == '.'));
1336
    case 6:
1337
52667
      return (str[0] == '%' &&
1338
16
              str[1] == '2' &&
1339
10
              ASCIILowercase(str[2]) == 'e' &&
1340
4
              str[3] == '%' &&
1341

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


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

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

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

14259314
    const bool special_back_slash = (special && ch == '\\');
1431
1432





14259314
    switch (state) {
1433
      case kSchemeStart:
1434
118239
        if (IsASCIIAlpha(ch)) {
1435
114902
          buffer += ASCIILowercase(ch);
1436
114890
          state = kScheme;
1437
3335
        } else if (!has_state_override) {
1438
3332
          state = kNoScheme;
1439
3332
          continue;
1440
        } else {
1441
3
          url->flags |= URL_FLAGS_FAILED;
1442
3
          return;
1443
        }
1444
114890
        break;
1445
      case kScheme:
1446


463630
        if (IsASCIIAlphanumeric(ch) || ch == '+' || ch == '-' || ch == '.') {
1447
348728
          buffer += ASCIILowercase(ch);
1448

114902
        } else if (ch == ':' || (has_state_override && ch == kEOL)) {
1449

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

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

6956
          } else if (special &&
1486

5742
                     has_base &&
1487
511
                     url->scheme == base->scheme) {
1488
178
            state = kSpecialRelativeOrAuthority;
1489
5053
          } else if (special) {
1490
1547
            state = kSpecialAuthoritySlashes;
1491

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

4279
        cannot_be_base = has_base && (base->flags & URL_FLAGS_CANNOT_BE_BASE);
1512

4279
        if (!has_base || (cannot_be_base && ch != '#')) {
1513
2305
          url->flags |= URL_FLAGS_FAILED;
1514
2305
          return;
1515

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

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

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

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


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

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

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

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

57539
        } else if (ch == kEOL ||
1739
55653
                   ch == '/' ||
1740
55635
                   ch == '?' ||
1741
55625
                   ch == '#' ||
1742
                   special_back_slash) {
1743

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

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

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

56217
        } else if (ch == kEOL ||
1775
54824
                   ch == '/' ||
1776
54802
                   ch == '?' ||
1777
54788
                   ch == '#' ||
1778
                   special_back_slash) {
1779
1439
          p--;
1780

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

1546
          if (has_state_override &&
1785

1449
              buffer.size() == 0 &&
1786

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

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

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

110516
        if (ch == '/' || ch == '\\') {
1857
108781
          state = kFileSlash;
1858

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

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

108781
        if (ch == '/' || ch == '\\') {
1926
108699
          state = kFileHost;
1927
        } else {
1928

164
          if (has_base &&
1929

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

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

326109
          if (!has_state_override &&
1955

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

166081
          if (ch != '/' && ch != '\\') {
1988
56456
            continue;
1989
          }
1990

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

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

13021774
        if (ch == kEOL ||
2007
11741520
            ch == '/' ||
2008
11741487
            special_back_slash ||
2009

17472261
            (!has_state_override && (ch == '?' || ch == '#'))) {
2010
1280407
          if (IsDoubleDotSegment(buffer)) {
2011
1245
            ShortenUrlPath(url);
2012

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

2559010
          } else if (IsSingleDotSegment(buffer) &&
2017

1279315
                     ch != '/' && !special_back_slash) {
2018
135
            url->flags |= URL_FLAGS_HAS_PATH;
2019
135
            url->path.emplace_back("");
2020
1279044
          } else if (!IsSingleDotSegment(buffer)) {
2021

3833342
            if (url->scheme == "file:" &&
2022
1414806
                url->path.empty() &&
2023

1417079
                buffer.size() == 2 &&
2024
36
                IsWindowsDriveLetter(buffer)) {
2025

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

1446817
          if (url->scheme == "file:" &&
2037
1111721
              (ch == kEOL ||
2038
1111709
               ch == '?' ||
2039
               ch == '#')) {
2040

219125
            while (url->path.size() > 1 && url->path[0].empty()) {
2041
26367
              url->path.erase(url->path.begin());
2042
            }
2043
          }
2044
2560852
          if (ch == '?') {
2045
109
            url->flags |= URL_FLAGS_HAS_QUERY;
2046
109
            state = kQuery;
2047
1280317
          } else if (ch == '#') {
2048
11
            state = kFragment;
2049
          }
2050
        } else {
2051
11741367
          AppendOrEscape(&buffer, ch, PATH_ENCODE_SET);
2052
        }
2053
13021781
        break;
2054
      case kCannotBeBase:
2055
31517
        switch (ch) {
2056
          case '?':
2057
2
            state = kQuery;
2058
2
            break;
2059
          case '#':
2060
5
            state = kFragment;
2061
5
            break;
2062
          default:
2063
31510
            if (url->path.empty())
2064
              url->path.emplace_back("");
2065
31510
            else if (ch != kEOL)
2066
28271
              AppendOrEscape(&url->path[0], ch, C0_CONTROL_ENCODE_SET);
2067
        }
2068
31517
        break;
2069
      case kQuery:
2070

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

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


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


514799
  CHECK(args[3]->IsUndefined() ||  // context
2193
        args[3]->IsNull() ||
2194
        args[3]->IsObject());
2195
243526
  CHECK(args[4]->IsFunction());  // complete callback
2196

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

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

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

17790
NODE_MODULE_EXTERNAL_REFERENCE(url, node::url::RegisterExternalReferences)