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-09-03 22:13:26 Branches: 1073 1198 89.6 %

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
117743
Local<String> Utf8String(Isolate* isolate, const std::string& str) {
35
235486
  return String::NewFromUtf8(isolate,
36
                             str.data(),
37
                             NewStringType::kNormal,
38
235487
                             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
2488
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
2488
  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
2488
    ~Value() {}
84
2488
    Value() : ipv4(0) {}
85
  };
86
87
  Value value_;
88
  HostType type_ = HostType::H_FAILED;
89
90
6886
  void Reset() {
91
    using string = std::string;
92
6886
    switch (type_) {
93
      case HostType::H_DOMAIN:
94
      case HostType::H_OPAQUE:
95
2161
        value_.domain_or_opaque.~string();
96
2161
        break;
97
      default:
98
4725
        break;
99
    }
100
6886
    type_ = HostType::H_FAILED;
101
6886
  }
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
2022
  void SetDomain(std::string&& string) {
118
2022
    Reset();
119
2022
    type_ = HostType::H_DOMAIN;
120
2022
    new(&value_.domain_or_opaque) std::string(std::move(string));
121
2022
  }
122
};
123
124
4976
URLHost::~URLHost() {
125
2488
  Reset();
126
2488
}
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

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

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

480336
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


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

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








67710
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


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


628
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
11930930
bool BitAt(const uint8_t a[], const uint8_t i) {
673
11930930
  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
11930941
void AppendOrEscape(std::string* str,
679
                           const unsigned char ch,
680
                           const uint8_t encode_set[]) {
681
11930941
  if (BitAt(encode_set, ch))
682
806
    *str += hex[ch];
683
  else
684
11930133
    *str += ch;
685
11930941
}
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
2236
std::string PercentDecode(const char* input, size_t len) {
699
2236
  std::string dest;
700
2236
  if (len == 0)
701
2
    return dest;
702
2234
  dest.reserve(len);
703
2234
  const char* pointer = input;
704
2234
  const char* end = input + len;
705
706
136576
  while (pointer < end) {
707
67171
    const char ch = pointer[0];
708
67171
    size_t remaining = end - pointer - 1;
709


134159
    if (ch != '%' || remaining < 2 ||
710
192
        (ch == '%' &&
711
381
         (!IsASCIIHexDigit(pointer[1]) ||
712
189
          !IsASCIIHexDigit(pointer[2])))) {
713
66988
      dest += ch;
714
66988
      pointer++;
715
66988
      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
2234
  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
284680
bool IsSpecial(const std::string& scheme) {
736
#define V(_, __, name) if (scheme == name) return true;
737



284680
  SPECIALS(V);
738
#undef V
739
4904
  return false;
740
}
741
742
117011
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



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









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

1971
    IsWindowsDriveLetter(p[0], p[1]) &&
762
14
    (length == 2 ||
763
21
      p[2] == '/' ||
764
10
      p[2] == '\\' ||
765
5
      p[2] == '?' ||
766
1944
      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
2223
bool ToASCII(const std::string& input, std::string* output) {
779
4446
  MaybeStackBuffer<char> buf;
780
2223
  if (i18n::ToASCII(&buf, input.c_str(), input.length()) < 0)
781
69
    return false;
782
2154
  output->assign(*buf, buf.length());
783
2154
  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
2230
int64_t ParseNumber(const char* start, const char* end) {
915
2230
  unsigned R = 10;
916

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

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

2759
    switch (R) {
931
      case 8:
932

173
        if (ch < '0' || ch > '7')
933
19
          return -1;
934
154
        break;
935
      case 10:
936
2464
        if (!IsASCIIDigit(ch))
937
1993
          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
2095
void URLHost::ParseIPv4Host(const char* input, size_t length, bool* is_ipv4) {
950
2095
  CHECK_EQ(type_, HostType::H_FAILED);
951
2095
  *is_ipv4 = false;
952
2095
  const char* pointer = input;
953
2095
  const char* mark = input;
954
2095
  const char* end = pointer + length;
955
2095
  int parts = 0;
956
2095
  uint32_t val = 0;
957
  uint64_t numbers[4];
958
2095
  int tooBigNumbers = 0;
959
2095
  if (length == 0)
960
2043
    return;
961
962
40519
  while (pointer <= end) {
963
21236
    const char ch = pointer < end ? pointer[0] : kEOL;
964
21236
    int remaining = end - pointer - 1;
965

21236
    if (ch == '.' || ch == kEOL) {
966
2238
      if (++parts > static_cast<int>(arraysize(numbers)))
967
2
        return;
968
2236
      if (pointer == mark)
969
6
        return;
970
2230
      int64_t n = ParseNumber(mark, pointer);
971
2230
      if (n < 0)
972
2014
        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
19212
    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
2488
void URLHost::ParseHost(const char* input,
1023
                        size_t length,
1024
                        bool is_special,
1025
                        bool unicode) {
1026
2488
  CHECK_EQ(type_, HostType::H_FAILED);
1027
2488
  const char* pointer = input;
1028
1029
2488
  if (length == 0)
1030
466
    return;
1031
1032
2488
  if (pointer[0] == '[') {
1033
97
    if (pointer[length - 1] != ']')
1034
6
      return;
1035
91
    return ParseIPv6Host(++pointer, length - 2);
1036
  }
1037
1038
2391
  if (!is_special)
1039
168
    return ParseOpaqueHost(input, length);
1040
1041
  // First, we have to percent decode
1042
4245
  std::string decoded = PercentDecode(input, length);
1043
1044
  // Then we have to punycode toASCII
1045
2223
  if (!ToASCII(decoded, &decoded))
1046
69
    return;
1047
1048
  // If any of the following characters are still present, we have to fail
1049
68900
  for (size_t n = 0; n < decoded.size(); n++) {
1050
66805
    const char ch = decoded[n];
1051
66805
    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
2095
  ParseIPv4Host(decoded.c_str(), decoded.length(), &is_ipv4);
1059
2095
  if (is_ipv4)
1060
73
    return;
1061
1062
  // If the unicode flag is set, run the result through punycode ToUnicode
1063

2022
  if (unicode && !ToUnicode(decoded, &decoded))
1064
    return;
1065
1066
  // It's not an IPv4 or IPv6 address, it must be a domain
1067
2022
  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
2237
std::string URLHost::ToStringMove() {
1102
2237
  std::string return_value;
1103
2237
  switch (type_) {
1104
    case HostType::H_DOMAIN:
1105
    case HostType::H_OPAQUE:
1106
2161
      return_value = std::move(value_.domain_or_opaque);
1107
2161
      break;
1108
    default:
1109
76
      return_value = ToString();
1110
76
      break;
1111
  }
1112
2237
  Reset();
1113
2237
  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
2106
bool ParseHost(const std::string& input,
1170
               std::string* output,
1171
               bool is_special,
1172
               bool unicode = false) {
1173
2106
  if (input.empty()) {
1174
42
    output->clear();
1175
42
    return true;
1176
  }
1177
4128
  URLHost host;
1178
2064
  host.ParseHost(input.c_str(), input.length(), is_special, unicode);
1179
2064
  if (host.ParsingFailed())
1180
233
    return false;
1181
1831
  *output = host.ToStringMove();
1182
1831
  return true;
1183
}
1184
1185
2888
std::vector<std::string> FromJSStringArray(Environment* env,
1186
                                           Local<Array> array) {
1187
2888
  std::vector<std::string> vec;
1188
2888
  if (array->Length() > 0)
1189
2880
    vec.reserve(array->Length());
1190
39604
  for (size_t n = 0; n < array->Length(); n++) {
1191
50742
    Local<Value> val = array->Get(env->context(), n).ToLocalChecked();
1192
33828
    if (val->IsString()) {
1193
33828
      Utf8Value value(env->isolate(), val.As<String>());
1194
16914
      vec.emplace_back(*value, value.length());
1195
    }
1196
  }
1197
2888
  return vec;
1198
}
1199
1200
2888
url_data HarvestBase(Environment* env, Local<Object> base_obj) {
1201
2888
  url_data base;
1202
2888
  Local<Context> context = env->context();
1203
1204
  Local<Value> flags =
1205
11552
      base_obj->Get(env->context(), env->flags_string()).ToLocalChecked();
1206
2888
  if (flags->IsInt32())
1207
5776
    base.flags = flags->Int32Value(context).FromJust();
1208
1209
  Local<Value> port =
1210
11552
      base_obj->Get(env->context(), env->port_string()).ToLocalChecked();
1211
2888
  if (port->IsInt32())
1212
8
    base.port = port->Int32Value(context).FromJust();
1213
1214
  Local<Value> scheme =
1215
11552
      base_obj->Get(env->context(), env->scheme_string()).ToLocalChecked();
1216
2888
  base.scheme = Utf8Value(env->isolate(), scheme).out();
1217
1218
  auto GetStr = [&](std::string url_data::*member,
1219
                    int flag,
1220
                    Local<String> name,
1221
14440
                    bool empty_as_present) {
1222
51478
    Local<Value> value = base_obj->Get(env->context(), name).ToLocalChecked();
1223
28880
    if (value->IsString()) {
1224
16316
      Utf8Value utf8value(env->isolate(), value.As<String>());
1225
10552
      (base.*member).assign(*utf8value, utf8value.length());
1226

19710
      if (empty_as_present || value.As<String>()->Length() != 0) {
1227
2394
        base.flags |= flag;
1228
      }
1229
    }
1230
17328
  };
1231
2888
  GetStr(&url_data::username,
1232
         URL_FLAGS_HAS_USERNAME,
1233
         env->username_string(),
1234
2888
         false);
1235
2888
  GetStr(&url_data::password,
1236
         URL_FLAGS_HAS_PASSWORD,
1237
         env->password_string(),
1238
2888
         false);
1239
2888
  GetStr(&url_data::host, URL_FLAGS_HAS_HOST, env->host_string(), true);
1240
2888
  GetStr(&url_data::query, URL_FLAGS_HAS_QUERY, env->query_string(), true);
1241
2888
  GetStr(&url_data::fragment,
1242
         URL_FLAGS_HAS_FRAGMENT,
1243
         env->fragment_string(),
1244
2888
         true);
1245
1246
  Local<Value>
1247
11552
      path = base_obj->Get(env->context(), env->path_string()).ToLocalChecked();
1248
2888
  if (path->IsArray()) {
1249
2888
    base.flags |= URL_FLAGS_HAS_PATH;
1250
2888
    base.path = FromJSStringArray(env, path.As<Array>());
1251
  }
1252
2888
  return base;
1253
}
1254
1255
30196
url_data HarvestContext(Environment* env, Local<Object> context_obj) {
1256
30196
  url_data context;
1257
  Local<Value> flags =
1258
120786
      context_obj->Get(env->context(), env->flags_string()).ToLocalChecked();
1259
30197
  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
60392
    context.flags |= flags.As<Int32>()->Value() & kCopyFlagsMask;
1267
  }
1268
  Local<Value> scheme =
1269
120789
      context_obj->Get(env->context(), env->scheme_string()).ToLocalChecked();
1270
60394
  if (scheme->IsString()) {
1271
60394
    Utf8Value value(env->isolate(), scheme);
1272
30197
    context.scheme.assign(*value, value.length());
1273
  }
1274
  Local<Value> port =
1275
120788
      context_obj->Get(env->context(), env->port_string()).ToLocalChecked();
1276
30197
  if (port->IsInt32())
1277
44
    context.port = port.As<Int32>()->Value();
1278
30197
  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
30197
  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
60394
      context_obj->Get(env->context(),
1296
150985
                       env->host_string()).ToLocalChecked();
1297
60394
  if (host->IsString()) {
1298
60373
    Utf8Value value(env->isolate(), host);
1299
30187
    context.host.assign(*value, value.length());
1300
  }
1301
30197
  return context;
1302
}
1303
1304
// Single dot segment can be ".", "%2e", or "%2E"
1305
2592215
bool IsSingleDotSegment(const std::string& str) {
1306
2592215
  switch (str.size()) {
1307
    case 1:
1308
1773
      return str == ".";
1309
    case 3:
1310
118404
      return str[0] == '%' &&
1311

118400
             str[1] == '2' &&
1312
118400
             ASCIILowercase(str[2]) == 'e';
1313
    default:
1314
2472069
      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
1297569
bool IsDoubleDotSegment(const std::string& str) {
1322

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

317898
      if (str[0] != '.' && str[0] != '%')
1327
317885
        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
53966
      return (str[0] == '%' &&
1338
16
              str[1] == '2' &&
1339
10
              ASCIILowercase(str[2]) == 'e' &&
1340
4
              str[3] == '%' &&
1341

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


3421
  if (url->path.size() == 1 && url->scheme == "file:" &&
1351
261
      IsNormalizedWindowsDriveLetter(url->path[0])) return;
1352
3160
  url->path.pop_back();
1353
}
1354
1355
}  // anonymous namespace
1356
1357
177566
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
177566
  const char* p = input;
1365
177566
  const char* end = input + len;
1366
1367
177566
  if (!has_url) {
1368
120820
    for (const char* ptr = p; ptr < end; ptr++) {
1369
120379
      if (IsC0ControlOrSpace(*ptr))
1370
28
        p++;
1371
      else
1372
120350
        break;
1373
    }
1374
120960
    for (const char* ptr = end - 1; ptr >= p; ptr--) {
1375
120518
      if (IsC0ControlOrSpace(*ptr))
1376
169
        end--;
1377
      else
1378
120350
        break;
1379
    }
1380
120792
    input = p;
1381
120792
    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
352362
  std::string whitespace_stripped;
1388
14257680
  for (const char* ptr = p; ptr < end; ptr++) {
1389
14080129
    if (!IsASCIITabOrNewline(*ptr))
1390
14080113
      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
177573
  bool atflag = false;  // Set when @ has been seen.
1411
177573
  bool square_bracket_flag = false;  // Set inside of [...]
1412
177573
  bool password_token_seen_flag = false;  // Set after a : after an username.
1413
1414
352370
  std::string buffer;
1415
1416
  // Set the initial parse state.
1417
177587
  const bool has_state_override = state_override != kUnknownState;
1418
177587
  enum url_parse_state state = has_state_override ? state_override :
1419
177587
                                                    kSchemeStart;
1420
1421

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

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

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





14453531
    switch (state) {
1433
      case kSchemeStart:
1434
120819
        if (IsASCIIAlpha(ch)) {
1435
117335
          buffer += ASCIILowercase(ch);
1436
117327
          state = kScheme;
1437
3484
        } else if (!has_state_override) {
1438
3481
          state = kNoScheme;
1439
3481
          continue;
1440
        } else {
1441
3
          url->flags |= URL_FLAGS_FAILED;
1442
3
          return;
1443
        }
1444
117327
        break;
1445
      case kScheme:
1446


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

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

116385
          if (has_state_override && buffer.size() == 0) {
1450
            url->flags |= URL_FLAGS_TERMINATED;
1451
            return;
1452
          }
1453
116385
          buffer += ':';
1454
1455
116386
          bool new_is_special = IsSpecial(buffer);
1456
1457
116386
          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
116373
          url->scheme = std::move(buffer);
1472
116372
          url->port = NormalizePort(url->scheme, url->port);
1473
116372
          if (new_is_special) {
1474
111710
            url->flags |= URL_FLAGS_SPECIAL;
1475
111710
            special = true;
1476
          } else {
1477
4662
            url->flags &= ~URL_FLAGS_SPECIAL;
1478
4662
            special = false;
1479
          }
1480
116372
          buffer.clear();
1481
116371
          if (has_state_override)
1482
8
            return;
1483
116363
          if (url->scheme == "file:") {
1484
109940
            state = kFile;
1485

8191
          } else if (special &&
1486

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

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

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

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

2120
        } 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

4212
        } else if (has_base &&
1539
2106
                   base->scheme != "file:") {
1540
152
          state = kRelative;
1541
152
          continue;
1542
        } else {
1543
1954
          url->scheme = "file:";
1544
1954
          url->flags |= URL_FLAGS_SPECIAL;
1545
1954
          special = true;
1546
1954
          state = kFile;
1547
1954
          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
262
        if (ch == '/') {
1561
202
          state = kAuthority;
1562
        } else {
1563
60
          state = kPath;
1564
60
          continue;
1565
        }
1566
202
        break;
1567
      case kRelative:
1568
168
        url->scheme = base->scheme;
1569
168
        if (IsSpecial(url->scheme)) {
1570
125
          url->flags |= URL_FLAGS_SPECIAL;
1571
125
          special = true;
1572
        } else {
1573
43
          url->flags &= ~URL_FLAGS_SPECIAL;
1574
43
          special = false;
1575
        }
1576

168
        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
83
            if (special_back_slash) {
1649
4
              state = kRelativeSlash;
1650
            } else {
1651
79
              if (base->flags & URL_FLAGS_HAS_USERNAME) {
1652
1
                url->flags |= URL_FLAGS_HAS_USERNAME;
1653
1
                url->username = base->username;
1654
              }
1655
79
              if (base->flags & URL_FLAGS_HAS_PASSWORD) {
1656
1
                url->flags |= URL_FLAGS_HAS_PASSWORD;
1657
1
                url->password = base->password;
1658
              }
1659
79
              if (base->flags & URL_FLAGS_HAS_HOST) {
1660
73
                url->flags |= URL_FLAGS_HAS_HOST;
1661
73
                url->host = base->host;
1662
              }
1663
79
              if (base->flags & URL_FLAGS_HAS_PATH) {
1664
79
                url->flags |= URL_FLAGS_HAS_PATH;
1665
79
                url->path = base->path;
1666
79
                ShortenUrlPath(url);
1667
              }
1668
79
              url->port = base->port;
1669
79
              state = kPath;
1670
79
              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
1589
        state = kSpecialAuthorityIgnoreSlashes;
1699

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

1802
        if (ch != '/' && ch != '\\') {
1707
1759
          state = kAuthority;
1708
1759
          continue;
1709
        }
1710
43
        break;
1711
      case kAuthority:
1712
58200
        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

58043
        } else if (ch == kEOL ||
1739
56115
                   ch == '/' ||
1740
56097
                   ch == '?' ||
1741
56087
                   ch == '#' ||
1742
                   special_back_slash) {
1743

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

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

57306
        } 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

56721
        } else if (ch == kEOL ||
1775
55286
                   ch == '/' ||
1776
55264
                   ch == '?' ||
1777
55250
                   ch == '#' ||
1778
                   special_back_slash) {
1779
1481
          p--;
1780

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

1588
          if (has_state_override &&
1785

1491
              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
1465
          url->flags |= URL_FLAGS_HAS_HOST;
1792
1465
          if (!ParseHost(buffer, &url->host, special)) {
1793
216
            url->flags |= URL_FLAGS_FAILED;
1794
216
            return;
1795
          }
1796
1249
          buffer.clear();
1797
1249
          state = kPathStart;
1798
2419
          if (has_state_override) {
1799
79
            return;
1800
          }
1801
        } else {
1802
55240
          if (ch == '[')
1803
93
            square_bracket_flag = true;
1804
55240
          if (ch == ']')
1805
90
            square_bracket_flag = false;
1806
55240
          buffer += ch;
1807
        }
1808
56971
        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
111895
        url->scheme = "file:";
1856

111893
        if (ch == '/' || ch == '\\') {
1857
110017
          state = kFileSlash;
1858

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

1869
          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
1863
              if (!StartsWithWindowsDriveLetter(p, end)) {
1906
1854
                if (base->flags & URL_FLAGS_HAS_HOST) {
1907
1854
                  url->flags |= URL_FLAGS_HAS_HOST;
1908
1854
                  url->host = base->host;
1909
                }
1910
1854
                if (base->flags & URL_FLAGS_HAS_PATH) {
1911
1854
                  url->flags |= URL_FLAGS_HAS_PATH;
1912
1854
                  url->path = base->path;
1913
                }
1914
1854
                ShortenUrlPath(url);
1915
              }
1916
1863
              state = kPath;
1917
1863
              continue;
1918
          }
1919
        } else {
1920
7
          state = kPath;
1921
7
          continue;
1922
        }
1923
110023
        break;
1924
      case kFileSlash:
1925

110018
        if (ch == '/' || ch == '\\') {
1926
109936
          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
109936
        break;
1948
      case kFileHost:
1949

110424
        if (ch == kEOL ||
1950
489
            ch == '/' ||
1951
484
            ch == '\\' ||
1952
484
            ch == '?' ||
1953
            ch == '#') {
1954

329816
          if (!has_state_override &&
1955

109947
              buffer.size() == 2 &&
1956
7
              IsWindowsDriveLetter(buffer)) {
1957
3
            state = kPath;
1958
109937
          } else if (buffer.size() == 0) {
1959
109862
            url->flags |= URL_FLAGS_HAS_HOST;
1960
109862
            url->host.clear();
1961
109863
            if (has_state_override)
1962
2
              return;
1963
109861
            state = kPathStart;
1964
          } else {
1965
134
            std::string host;
1966
75
            if (!ParseHost(buffer, &host, special)) {
1967
14
              url->flags |= URL_FLAGS_FAILED;
1968
14
              return;
1969
            }
1970
61
            if (host == "localhost")
1971
20
              host.clear();
1972
61
            url->flags |= URL_FLAGS_HAS_HOST;
1973
61
            url->host = host;
1974
61
            if (has_state_override)
1975
2
              return;
1976
59
            buffer.clear();
1977
59
            state = kPathStart;
1978
          }
1979
109923
          continue;
1980
        } else {
1981
484
          buffer += ch;
1982
        }
1983
484
        break;
1984
      case kPathStart:
1985
168075
        if (IsSpecial(url->scheme)) {
1986
167900
          state = kPath;
1987

167900
          if (ch != '/' && ch != '\\') {
1988
56968
            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
111098
        break;
2005
      case kPath:
2006

13193576
        if (ch == kEOL ||
2007
11896164
            ch == '/' ||
2008
11896132
            special_back_slash ||
2009

17705694
            (!has_state_override && (ch == '?' || ch == '#'))) {
2010
1297564
          if (IsDoubleDotSegment(buffer)) {
2011
1391
            ShortenUrlPath(url);
2012

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

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

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

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

1435610
                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
1295527
            url->flags |= URL_FLAGS_HAS_PATH;
2033
1295527
            url->path.emplace_back(std::move(buffer));
2034
          }
2035
1297569
          buffer.clear();
2036

1465882
          if (url->scheme == "file:" &&
2037
1126896
              (ch == kEOL ||
2038
1126883
               ch == '?' ||
2039
               ch == '#')) {
2040

221544
            while (url->path.size() > 1 && url->path[0].empty()) {
2041
26615
              url->path.erase(url->path.begin());
2042
            }
2043
          }
2044
2595138
          if (ch == '?') {
2045
109
            url->flags |= URL_FLAGS_HAS_QUERY;
2046
109
            state = kQuery;
2047
1297460
          } else if (ch == '#') {
2048
11
            state = kFragment;
2049
          }
2050
        } else {
2051
11896012
          AppendOrEscape(&buffer, ch, PATH_ENCODE_SET);
2052
        }
2053
13193570
        break;
2054
      case kCannotBeBase:
2055
34572
        switch (ch) {
2056
          case '?':
2057
2
            state = kQuery;
2058
2
            break;
2059
          case '#':
2060
5
            state = kFragment;
2061
5
            break;
2062
          default:
2063
34565
            if (url->path.empty())
2064
              url->path.emplace_back("");
2065
34565
            else if (ch != kEOL)
2066
30177
              AppendOrEscape(&url->path[0], ch, C0_CONTROL_ENCODE_SET);
2067
        }
2068
34572
        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
14272793
    p++;
2099
  }
2100
}  // NOLINT(readability/fn_size)
2101
2102
namespace {
2103
121716
void SetArgs(Environment* env,
2104
             Local<Value> argv[ARG_COUNT],
2105
             const struct url_data& url) {
2106
121716
  Isolate* isolate = env->isolate();
2107
243432
  argv[ARG_FLAGS] = Integer::NewFromUnsigned(isolate, url.flags);
2108
121717
  argv[ARG_PROTOCOL] =
2109
121716
      url.flags & URL_FLAGS_SPECIAL ?
2110
117011
          GetSpecial(env, url.scheme) :
2111
482160
          OneByteString(isolate, url.scheme.c_str());
2112
121717
  if (url.flags & URL_FLAGS_HAS_USERNAME)
2113
176
    argv[ARG_USERNAME] = Utf8String(isolate, url.username);
2114
121717
  if (url.flags & URL_FLAGS_HAS_PASSWORD)
2115
152
    argv[ARG_PASSWORD] = Utf8String(isolate, url.password);
2116
121717
  if (url.flags & URL_FLAGS_HAS_HOST)
2117
234401
    argv[ARG_HOST] = Utf8String(isolate, url.host);
2118
121718
  if (url.flags & URL_FLAGS_HAS_QUERY)
2119
514
    argv[ARG_QUERY] = Utf8String(isolate, url.query);
2120
121718
  if (url.flags & URL_FLAGS_HAS_FRAGMENT)
2121
244
    argv[ARG_FRAGMENT] = Utf8String(isolate, url.fragment);
2122
121718
  if (url.port > -1)
2123
1022
    argv[ARG_PORT] = Integer::New(isolate, url.port);
2124
121718
  if (url.flags & URL_FLAGS_HAS_PATH)
2125
242882
    argv[ARG_PATH] = ToV8Value(env->context(), url.path).ToLocalChecked();
2126
121718
}
2127
2128
124389
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
124389
  Isolate* isolate = env->isolate();
2138
124390
  Local<Context> context = env->context();
2139
248764
  HandleScope handle_scope(isolate);
2140
124373
  Context::Scope context_scope(context);
2141
2142
124390
  const bool has_context = context_obj->IsObject();
2143
124391
  const bool has_base = base_obj->IsObject();
2144
2145
248765
  url_data base;
2146
248765
  url_data url;
2147
124391
  if (has_context)
2148
30197
    url = HarvestContext(env, context_obj.As<Object>());
2149
124391
  if (has_base)
2150
2888
    base = HarvestBase(env, base_obj.As<Object>());
2151
2152
124391
  URL::Parse(input, len, state_override, &url, has_context, &base, has_base);
2153

124391
  if ((url.flags & URL_FLAGS_INVALID_PARSE_STATE) ||
2154
30197
      ((state_override != kUnknownState) &&
2155
30197
       (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
124374
  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
121717
    };
2173
121717
    SetArgs(env, argv, url);
2174
365147
    cb->Call(context, recv, arraysize(argv), argv).FromMaybe(Local<Value>());
2175
2657
  } else if (error_cb->IsFunction()) {
2176
2610
    Local<Value> argv[2] = { undef, undef };
2177
5220
    argv[ERR_ARG_FLAGS] = Integer::NewFromUnsigned(isolate, url.flags);
2178
2610
    argv[ERR_ARG_INPUT] =
2179
5220
      String::NewFromUtf8(env->isolate(), input).ToLocalChecked();
2180
10440
    error_cb.As<Function>()->Call(context, recv, arraysize(argv), argv)
2181
2610
        .FromMaybe(Local<Value>());
2182
  }
2183
}
2184
2185
124390
void Parse(const FunctionCallbackInfo<Value>& args) {
2186
124390
  Environment* env = Environment::GetCurrent(args);
2187
124390
  CHECK_GE(args.Length(), 5);
2188
373170
  CHECK(args[0]->IsString());  // input
2189


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


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

561556
  CHECK(args[5]->IsUndefined() || args[5]->IsFunction());  // error callback
2197
2198
248781
  Utf8Value input(env->isolate(), args[0]);
2199
124391
  enum url_parse_state state_override = kUnknownState;
2200
248782
  if (args[1]->IsNumber()) {
2201
124390
    state_override = static_cast<enum url_parse_state>(
2202
621952
        args[1]->Uint32Value(env->context()).FromJust());
2203
  }
2204
2205
248781
  Parse(env, args.This(),
2206
124389
        *input, input.length(),
2207
        state_override,
2208
        args[2],
2209
        args[3],
2210
248781
        args[4].As<Function>(),
2211
124390
        args[5]);
2212
124391
}
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
452
void SetURLConstructor(const FunctionCallbackInfo<Value>& args) {
2301
452
  Environment* env = Environment::GetCurrent(args);
2302
452
  CHECK_EQ(args.Length(), 1);
2303
904
  CHECK(args[0]->IsFunction());
2304
904
  env->set_url_constructor_function(args[0].As<Function>());
2305
452
}
2306
2307
452
void Initialize(Local<Object> target,
2308
                Local<Value> unused,
2309
                Local<Context> context,
2310
                void* priv) {
2311
452
  Environment* env = Environment::GetCurrent(context);
2312
452
  env->SetMethod(target, "parse", Parse);
2313
452
  env->SetMethodNoSideEffect(target, "encodeAuth", EncodeAuthSet);
2314
452
  env->SetMethodNoSideEffect(target, "toUSVString", ToUSVString);
2315
452
  env->SetMethodNoSideEffect(target, "domainToASCII", DomainToASCII);
2316
452
  env->SetMethodNoSideEffect(target, "domainToUnicode", DomainToUnicode);
2317
452
  env->SetMethod(target, "setURLConstructor", SetURLConstructor);
2318
2319
#define XX(name, _) NODE_DEFINE_CONSTANT(target, name);
2320
23504
  FLAGS(XX)
2321
#undef XX
2322
2323
#define XX(name) NODE_DEFINE_CONSTANT(target, name);
2324
37968
  PARSESTATES(XX)
2325
#undef XX
2326
452
}
2327
}  // namespace
2328
2329
4402
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
2330
4402
  registry->Register(Parse);
2331
4402
  registry->Register(EncodeAuthSet);
2332
4402
  registry->Register(ToUSVString);
2333
4402
  registry->Register(DomainToASCII);
2334
4402
  registry->Register(DomainToUnicode);
2335
4402
  registry->Register(SetURLConstructor);
2336
4402
}
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
26579
URL URL::FromFilePath(const std::string& file_path) {
2401
26579
  URL url("file://");
2402
53158
  std::string escaped_file_path;
2403
3236126
  for (size_t i = 0; i < file_path.length(); ++i) {
2404
3209546
    escaped_file_path += file_path[i];
2405
3209547
    if (file_path[i] == '%')
2406
8
      escaped_file_path += "25";
2407
  }
2408
26579
  URL::Parse(escaped_file_path.c_str(), escaped_file_path.length(), kPathStart,
2409
26579
             &url.context_, true, nullptr, false);
2410
53158
  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
4471
NODE_MODULE_CONTEXT_AWARE_INTERNAL(url, node::url::Initialize)
2459

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