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-07-19 22:14:24 Branches: 1074 1202 89.4 %

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
183852
Local<String> Utf8String(Isolate* isolate, const std::string& str) {
35
367704
  return String::NewFromUtf8(isolate,
36
                             str.data(),
37
                             NewStringType::kNormal,
38
367704
                             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
5165
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
5165
  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
5165
    ~Value() {}
84
5165
    Value() : ipv4(0) {}
85
  };
86
87
  Value value_;
88
  HostType type_ = HostType::H_FAILED;
89
90
14747
  void Reset() {
91
    using string = std::string;
92
14747
    switch (type_) {
93
      case HostType::H_DOMAIN:
94
      case HostType::H_OPAQUE:
95
4669
        value_.domain_or_opaque.~string();
96
4669
        break;
97
      default:
98
10078
        break;
99
    }
100
14747
    type_ = HostType::H_FAILED;
101
14747
  }
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
285
  void SetOpaque(std::string&& string) {
112
285
    Reset();
113
285
    type_ = HostType::H_OPAQUE;
114
285
    new(&value_.domain_or_opaque) std::string(std::move(string));
115
285
  }
116
117
4384
  void SetDomain(std::string&& string) {
118
4384
    Reset();
119
4384
    type_ = HostType::H_DOMAIN;
120
4384
    new(&value_.domain_or_opaque) std::string(std::move(string));
121
4384
  }
122
};
123
124
10330
URLHost::~URLHost() {
125
5165
  Reset();
126
5165
}
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

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

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

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


1468
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


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

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








91407
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


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


2602
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
15437277
bool BitAt(const uint8_t a[], const uint8_t i) {
673
15437277
  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
15437277
void AppendOrEscape(std::string* str,
679
                           const unsigned char ch,
680
                           const uint8_t encode_set[]) {
681
15437277
  if (BitAt(encode_set, ch))
682
1021
    *str += hex[ch];
683
  else
684
15436256
    *str += ch;
685
15437277
}
686
687
template <typename T>
688
898
unsigned hex2bin(const T ch) {
689

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

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

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


179883
    if (ch != '%' || remaining < 2 ||
710
242
        (ch == '%' &&
711
481
         (!IsASCIIHexDigit(pointer[1]) ||
712
239
          !IsASCIIHexDigit(pointer[2])))) {
713
89825
      dest += ch;
714
89825
      pointer++;
715
89825
      continue;
716
    } else {
717
233
      unsigned a = hex2bin(pointer[1]);
718
233
      unsigned b = hex2bin(pointer[2]);
719
233
      char c = static_cast<char>(a * 16 + b);
720
233
      dest += c;
721
233
      pointer += 3;
722
    }
723
  }
724
4722
  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
382196
bool IsSpecial(const std::string& scheme) {
736
#define V(_, __, name) if (scheme == name) return true;
737



382196
  SPECIALS(V);
738
#undef V
739
2329
  return false;
740
}
741
742
181950
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



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









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

2898
    IsWindowsDriveLetter(p[0], p[1]) &&
762
42
    (length == 2 ||
763
63
      p[2] == '/' ||
764
30
      p[2] == '\\' ||
765
15
      p[2] == '?' ||
766
2817
      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
4711
bool ToASCII(const std::string& input, std::string* output) {
779
9422
  MaybeStackBuffer<char> buf;
780
4711
  if (i18n::ToASCII(&buf, input.c_str(), input.length()) < 0)
781
69
    return false;
782
4642
  output->assign(*buf, buf.length());
783
4642
  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
133
void URLHost::ParseIPv6Host(const char* input, size_t length) {
799
133
  CHECK_EQ(type_, HostType::H_FAILED);
800
133
  unsigned size = arraysize(value_.ipv6);
801
1197
  for (unsigned n = 0; n < size; n++)
802
1064
    value_.ipv6[n] = 0;
803
133
  uint16_t* piece_pointer = &value_.ipv6[0];
804
133
  uint16_t* const buffer_end = piece_pointer + size;
805
133
  uint16_t* compress_pointer = nullptr;
806
133
  const char* pointer = input;
807
133
  const char* end = pointer + length;
808
  unsigned value, len, numbers_seen;
809
133
  char ch = pointer < end ? pointer[0] : kEOL;
810
133
  if (ch == ':') {
811

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

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

373
    switch (ch) {
839
      case '.':
840
47
        if (len == 0)
841
3
          return;
842
44
        pointer -= len;
843
44
        ch = pointer < end ? pointer[0] : kEOL;
844
44
        if (piece_pointer > buffer_end - 2)
845
3
          return;
846
41
        numbers_seen = 0;
847
259
        while (ch != kEOL) {
848
139
          value = 0xffffffff;
849
139
          if (numbers_seen > 0) {
850

98
            if (ch == '.' && numbers_seen < 4) {
851
90
              pointer++;
852
90
              ch = pointer < end ? pointer[0] : kEOL;
853
            } else {
854
8
              return;
855
            }
856
          }
857
131
          if (!IsASCIIDigit(ch))
858
16
            return;
859
407
          while (IsASCIIDigit(ch)) {
860
152
            unsigned number = ch - '0';
861
152
            if (value == 0xffffffff) {
862
115
              value = number;
863
37
            } else if (value == 0) {
864
3
              return;
865
            } else {
866
34
              value = value * 10 + number;
867
            }
868
149
            if (value > 255)
869
3
              return;
870
146
            pointer++;
871
146
            ch = pointer < end ? pointer[0] : kEOL;
872
          }
873
109
          *piece_pointer = *piece_pointer * 0x100 + value;
874
109
          numbers_seen++;
875

109
          if (numbers_seen == 2 || numbers_seen == 4)
876
45
            piece_pointer++;
877
        }
878
11
        if (numbers_seen != 4)
879
3
          return;
880
8
        continue;
881
      case ':':
882
263
        pointer++;
883
263
        ch = pointer < end ? pointer[0] : kEOL;
884
263
        if (ch == kEOL)
885
3
          return;
886
260
        break;
887
      case kEOL:
888
50
        break;
889
      default:
890
13
        return;
891
    }
892
310
    *piece_pointer = value;
893
310
    piece_pointer++;
894
  }
895
896
69
  if (compress_pointer != nullptr) {
897
46
    unsigned swaps = piece_pointer - compress_pointer;
898
46
    piece_pointer = buffer_end - 1;
899

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

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

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

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

6165
    switch (R) {
931
      case 8:
932

217
        if (ch < '0' || ch > '7')
933
23
          return -1;
934
194
        break;
935
      case 10:
936
5750
        if (!IsASCIIDigit(ch))
937
4327
          return -1;
938
1423
        break;
939
      case 16:
940
198
        if (!IsASCIIHexDigit(ch))
941
10
          return -1;
942
188
        break;
943
    }
944
1805
    p++;
945
  }
946
754
  return strtoll(start, nullptr, R);
947
}
948
949
4583
void URLHost::ParseIPv4Host(const char* input, size_t length, bool* is_ipv4) {
950
4583
  CHECK_EQ(type_, HostType::H_FAILED);
951
4583
  *is_ipv4 = false;
952
4583
  const char* pointer = input;
953
4583
  const char* mark = input;
954
4583
  const char* end = pointer + length;
955
4583
  int parts = 0;
956
4583
  uint32_t val = 0;
957
  uint64_t numbers[4];
958
4583
  int tooBigNumbers = 0;
959
4583
  if (length == 0)
960
4405
    return;
961
962
79161
  while (pointer <= end) {
963
41677
    const char ch = pointer < end ? pointer[0] : kEOL;
964
41677
    int remaining = end - pointer - 1;
965

41677
    if (ch == '.' || ch == kEOL) {
966
5146
      if (++parts > static_cast<int>(arraysize(numbers)))
967
6
        return;
968
5140
      if (pointer == mark)
969
18
        return;
970
5122
      int64_t n = ParseNumber(mark, pointer);
971
5122
      if (n < 0)
972
4360
        return;
973
974
762
      if (n > 255) {
975
113
        tooBigNumbers++;
976
      }
977
762
      numbers[parts - 1] = n;
978
762
      mark = pointer + 1;
979

762
      if (ch == '.' && remaining == 0)
980
4
        break;
981
    }
982
37289
    pointer++;
983
  }
984
199
  CHECK_GT(parts, 0);
985
199
  *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

395
  if (tooBigNumbers > 1 ||
991

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

1820
    if (ch != '%' && IsForbiddenHostCodePoint(ch)) {
1013
29
      return;
1014
    } else {
1015
1791
      AppendOrEscape(&output, ch, C0_CONTROL_ENCODE_SET);
1016
    }
1017
  }
1018
1019
285
  SetOpaque(std::move(output));
1020
}
1021
1022
5165
void URLHost::ParseHost(const char* input,
1023
                        size_t length,
1024
                        bool is_special,
1025
                        bool unicode) {
1026
5165
  CHECK_EQ(type_, HostType::H_FAILED);
1027
5165
  const char* pointer = input;
1028
1029
5165
  if (length == 0)
1030
782
    return;
1031
1032
5164
  if (pointer[0] == '[') {
1033
139
    if (pointer[length - 1] != ']')
1034
6
      return;
1035
133
    return ParseIPv6Host(++pointer, length - 2);
1036
  }
1037
1038
5025
  if (!is_special)
1039
314
    return ParseOpaqueHost(input, length);
1040
1041
  // First, we have to percent decode
1042
9095
  std::string decoded = PercentDecode(input, length);
1043
1044
  // Then we have to punycode toASCII
1045
4711
  if (!ToASCII(decoded, &decoded))
1046
69
    return;
1047
1048
  // If any of the following characters are still present, we have to fail
1049
94229
  for (size_t n = 0; n < decoded.size(); n++) {
1050
89646
    const char ch = decoded[n];
1051
89646
    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
4583
  ParseIPv4Host(decoded.c_str(), decoded.length(), &is_ipv4);
1059
4583
  if (is_ipv4)
1060
199
    return;
1061
1062
  // If the unicode flag is set, run the result through punycode ToUnicode
1063

4384
  if (unicode && !ToUnicode(decoded, &decoded))
1064
    return;
1065
1066
  // It's not an IPv4 or IPv6 address, it must be a domain
1067
4384
  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
66
T* FindLongestZeroSequence(T* values, size_t len) {
1074
66
  T* start = values;
1075
66
  T* end = start + len;
1076
66
  T* result = nullptr;
1077
1078
66
  T* current = nullptr;
1079
66
  unsigned counter = 0, longest = 1;
1080
1081
1122
  while (start < end) {
1082
528
    if (*start == 0) {
1083
372
      if (current == nullptr)
1084
101
        current = start;
1085
372
      counter++;
1086
    } else {
1087
156
      if (counter > longest) {
1088
50
        longest = counter;
1089
50
        result = current;
1090
      }
1091
156
      counter = 0;
1092
156
      current = nullptr;
1093
    }
1094
528
    start++;
1095
  }
1096
66
  if (counter > longest)
1097
11
    result = current;
1098
66
  return result;
1099
}
1100
1101
4913
std::string URLHost::ToStringMove() {
1102
4913
  std::string return_value;
1103
4913
  switch (type_) {
1104
    case HostType::H_DOMAIN:
1105
    case HostType::H_OPAQUE:
1106
4669
      return_value = std::move(value_.domain_or_opaque);
1107
4669
      break;
1108
    default:
1109
244
      return_value = ToString();
1110
244
      break;
1111
  }
1112
4913
  Reset();
1113
4913
  return return_value;
1114
}
1115
1116
244
std::string URLHost::ToString() const {
1117
488
  std::string dest;
1118

244
  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
178
      dest.reserve(15);
1125
178
      uint32_t value = value_.ipv4;
1126
890
      for (int n = 0; n < 4; n++) {
1127
        char buf[4];
1128
712
        snprintf(buf, sizeof(buf), "%d", value % 256);
1129
712
        dest.insert(0, buf);
1130
712
        if (n < 3)
1131
534
          dest.insert(0, 1, '.');
1132
712
        value /= 256;
1133
      }
1134
178
      break;
1135
    }
1136
    case HostType::H_IPV6: {
1137
66
      dest.reserve(41);
1138
66
      dest += '[';
1139
66
      const uint16_t* start = &value_.ipv6[0];
1140
      const uint16_t* compress_pointer =
1141
66
          FindLongestZeroSequence(start, 8);
1142
66
      bool ignore0 = false;
1143
594
      for (int n = 0; n <= 7; n++) {
1144
528
        const uint16_t* piece = &value_.ipv6[n];
1145

528
        if (ignore0 && *piece == 0)
1146
588
          continue;
1147
262
        else if (ignore0)
1148
45
          ignore0 = false;
1149
262
        if (compress_pointer == piece) {
1150
56
          dest += n == 0 ? "::" : ":";
1151
56
          ignore0 = true;
1152
56
          continue;
1153
        }
1154
        char buf[5];
1155
206
        snprintf(buf, sizeof(buf), "%x", *piece);
1156
206
        dest += buf;
1157
206
        if (n < 7)
1158
151
          dest += ':';
1159
      }
1160
66
      dest += ']';
1161
66
      break;
1162
    }
1163
    case HostType::H_FAILED:
1164
      break;
1165
  }
1166
244
  return dest;
1167
}
1168
1169
4842
bool ParseHost(const std::string& input,
1170
               std::string* output,
1171
               bool is_special,
1172
               bool unicode = false) {
1173
4842
  if (input.length() == 0) {
1174
102
    output->clear();
1175
102
    return true;
1176
  }
1177
9480
  URLHost host;
1178
4740
  host.ParseHost(input.c_str(), input.length(), is_special, unicode);
1179
4740
  if (host.ParsingFailed())
1180
233
    return false;
1181
4507
  *output = host.ToStringMove();
1182
4507
  return true;
1183
}
1184
1185
4569
std::vector<std::string> FromJSStringArray(Environment* env,
1186
                                           Local<Array> array) {
1187
4569
  std::vector<std::string> vec;
1188
4569
  if (array->Length() > 0)
1189
4551
    vec.reserve(array->Length());
1190
45770
  for (size_t n = 0; n < array->Length(); n++) {
1191
54948
    Local<Value> val = array->Get(env->context(), n).ToLocalChecked();
1192
36632
    if (val->IsString()) {
1193
36632
      Utf8Value value(env->isolate(), val.As<String>());
1194
18316
      vec.emplace_back(*value, value.length());
1195
    }
1196
  }
1197
4569
  return vec;
1198
}
1199
1200
4569
url_data HarvestBase(Environment* env, Local<Object> base_obj) {
1201
4569
  url_data base;
1202
4569
  Local<Context> context = env->context();
1203
1204
  Local<Value> flags =
1205
18276
      base_obj->Get(env->context(), env->flags_string()).ToLocalChecked();
1206
4569
  if (flags->IsInt32())
1207
9138
    base.flags = flags->Int32Value(context).FromJust();
1208
1209
  Local<Value> port =
1210
18276
      base_obj->Get(env->context(), env->port_string()).ToLocalChecked();
1211
4569
  if (port->IsInt32())
1212
12
    base.port = port->Int32Value(context).FromJust();
1213
1214
  Local<Value> scheme =
1215
18276
      base_obj->Get(env->context(), env->scheme_string()).ToLocalChecked();
1216
4569
  base.scheme = Utf8Value(env->isolate(), scheme).out();
1217
1218
  auto GetStr = [&](std::string url_data::*member,
1219
                    int flag,
1220
                    Local<String> name,
1221
22845
                    bool empty_as_present) {
1222
81336
    Local<Value> value = base_obj->Get(env->context(), name).ToLocalChecked();
1223
45690
    if (value->IsString()) {
1224
25602
      Utf8Value utf8value(env->isolate(), value.As<String>());
1225
16482
      (base.*member).assign(*utf8value, utf8value.length());
1226

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

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

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

405518
      if (str[0] != '.' && str[0] != '%')
1327
405496
        return false;
1328
39
      return ((str[0] == '.' &&
1329
21
               str[1] == '%' &&
1330
8
               str[2] == '2' &&
1331

53
               ASCIILowercase(str[3]) == 'e') ||
1332
23
              (str[0] == '%' &&
1333
10
               str[1] == '2' &&
1334
10
               ASCIILowercase(str[2]) == 'e' &&
1335
27
               str[3] == '.'));
1336
    case 6:
1337
64818
      return (str[0] == '%' &&
1338
30
              str[1] == '2' &&
1339
19
              ASCIILowercase(str[2]) == 'e' &&
1340
8
              str[3] == '%' &&
1341

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


5164
  if (url->path.size() == 1 && url->scheme == "file:" &&
1351
1213
      IsNormalizedWindowsDriveLetter(url->path[0])) return;
1352
3951
  url->path.pop_back();
1353
}
1354
1355
}  // anonymous namespace
1356
1357
240060
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
240060
  const char* p = input;
1365
240060
  const char* end = input + len;
1366
1367
240060
  if (!has_url) {
1368
152715
    for (const char* ptr = p; ptr < end; ptr++) {
1369
152690
      if (IsC0ControlOrSpace(*ptr))
1370
58
        p++;
1371
      else
1372
152632
        break;
1373
    }
1374
152704
    for (const char* ptr = end - 1; ptr >= p; ptr--) {
1375
152679
      if (IsC0ControlOrSpace(*ptr))
1376
47
        end--;
1377
      else
1378
152632
        break;
1379
    }
1380
152657
    input = p;
1381
152657
    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
478341
  std::string whitespace_stripped;
1388
18412211
  for (const char* ptr = p; ptr < end; ptr++) {
1389
18172187
    if (!IsASCIITabOrNewline(*ptr))
1390
18172151
      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
36
    whitespace_stripped.reserve(len - 1);
1394
36
    whitespace_stripped.assign(p, ptr - p);
1395
    // 'ptr + 1' skips the current char, which we know to be tab or newline.
1396
476
    for (ptr = ptr + 1; ptr < end; ptr++) {
1397
440
      if (!IsASCIITabOrNewline(*ptr))
1398
362
        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
36
    input = whitespace_stripped.c_str();
1404
36
    len = whitespace_stripped.size();
1405
36
    p = input;
1406
36
    end = input + len;
1407
36
    break;
1408
  }
1409
1410
240060
  bool atflag = false;  // Set when @ has been seen.
1411
240060
  bool square_bracket_flag = false;  // Set inside of [...]
1412
240060
  bool password_token_seen_flag = false;  // Set after a : after an username.
1413
1414
478342
  std::string buffer;
1415
1416
  // Set the initial parse state.
1417
240060
  const bool has_state_override = state_override != kUnknownState;
1418
240060
  enum url_parse_state state = has_state_override ? state_override :
1419
240060
                                                    kSchemeStart;
1420
1421

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

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

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





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


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

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

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

8184
          } else if (special &&
1486

5857
                     has_base &&
1487
871
                     url->scheme == base->scheme) {
1488
278
            state = kSpecialRelativeOrAuthority;
1489
4708
          } else if (special) {
1490
2920
            state = kSpecialAuthoritySlashes;
1491

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

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

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

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

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

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

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


81
        if (IsSpecial(url->scheme) && (ch == '/' || ch == '\\')) {
1676
16
          state = kSpecialAuthorityIgnoreSlashes;
1677
65
        } else if (ch == '/') {
1678
9
          state = kAuthority;
1679
        } else {
1680
56
          if (base->flags & URL_FLAGS_HAS_USERNAME) {
1681
8
            url->flags |= URL_FLAGS_HAS_USERNAME;
1682
8
            url->username = base->username;
1683
          }
1684
56
          if (base->flags & URL_FLAGS_HAS_PASSWORD) {
1685
4
            url->flags |= URL_FLAGS_HAS_PASSWORD;
1686
4
            url->password = base->password;
1687
          }
1688
56
          if (base->flags & URL_FLAGS_HAS_HOST) {
1689
52
            url->flags |= URL_FLAGS_HAS_HOST;
1690
52
            url->host = base->host;
1691
          }
1692
56
          url->port = base->port;
1693
56
          state = kPath;
1694
56
          continue;
1695
        }
1696
25
        break;
1697
      case kSpecialAuthoritySlashes:
1698
2920
        state = kSpecialAuthorityIgnoreSlashes;
1699

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

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

289
          if (blen > 0 && buffer[0] != ':') {
1720
197
            url->flags |= URL_FLAGS_HAS_USERNAME;
1721
          }
1722
1537
          for (size_t n = 0; n < blen; n++) {
1723
1248
            const char bch = buffer[n];
1724
1248
            if (bch == ':') {
1725
173
              url->flags |= URL_FLAGS_HAS_PASSWORD;
1726
173
              if (!password_token_seen_flag) {
1727
169
                password_token_seen_flag = true;
1728
169
                continue;
1729
              }
1730
            }
1731
1079
            if (password_token_seen_flag) {
1732
417
              AppendOrEscape(&url->password, bch, USERINFO_ENCODE_SET);
1733
            } else {
1734
662
              AppendOrEscape(&url->username, bch, USERINFO_ENCODE_SET);
1735
            }
1736
          }
1737
289
          buffer.clear();
1738

77388
        } else if (ch == kEOL ||
1739
73847
                   ch == '/' ||
1740
73819
                   ch == '?' ||
1741
73799
                   ch == '#' ||
1742
                   special_back_slash) {
1743

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

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

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

72566
        } else if (ch == kEOL ||
1775
70142
                   ch == '/' ||
1776
70110
                   ch == '?' ||
1777
70086
                   ch == '#' ||
1778
                   special_back_slash) {
1779
2498
          p--;
1780

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

2605
          if (has_state_override &&
1785

2508
              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
2482
          url->flags |= URL_FLAGS_HAS_HOST;
1792
2482
          if (!ParseHost(buffer, &url->host, special)) {
1793
216
            url->flags |= URL_FLAGS_FAILED;
1794
216
            return;
1795
          }
1796
2266
          buffer.clear();
1797
2266
          state = kPathStart;
1798
4453
          if (has_state_override) {
1799
79
            return;
1800
          }
1801
        } else {
1802
70068
          if (ch == '[')
1803
133
            square_bracket_flag = true;
1804
70068
          if (ch == ']')
1805
130
            square_bracket_flag = false;
1806
70068
          buffer += ch;
1807
        }
1808
73440
        break;
1809
      case kPort:
1810
5468
        if (IsASCIIDigit(ch)) {
1811
4266
          buffer += ch;
1812

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

5270
            for (size_t i = 0; port <= 0xffff && i < buffer.size(); i++)
1822
4104
              port = port * 10 + buffer[i] - '0';
1823
1166
            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
1148
            url->port = NormalizePort(url->scheme, static_cast<int>(port));
1836
1148
            if (url->port == -1)
1837
42
              url->flags |= URL_FLAGS_IS_DEFAULT_SCHEME_PORT;
1838
1148
            buffer.clear();
1839
9
          } 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
1156
          state = kPathStart;
1848
1156
          continue;
1849
        } else {
1850
27
          url->flags |= URL_FLAGS_FAILED;
1851
27
          return;
1852
        }
1853
4266
        break;
1854
      case kFile:
1855
146048
        url->scheme = "file:";
1856

146047
        if (ch == '/' || ch == '\\') {
1857
143304
          state = kFileSlash;
1858

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

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

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

250
          if (has_base &&
1929

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

153257
        if (ch == kEOL ||
1950
10086
            ch == '/' ||
1951
10071
            ch == '\\' ||
1952
10071
            ch == '?' ||
1953
            ch == '#') {
1954

429550
          if (!has_state_override &&
1955

143201
              buffer.size() == 2 &&
1956
15
              IsWindowsDriveLetter(buffer)) {
1957
12
            state = kPath;
1958
143173
          } else if (buffer.size() == 0) {
1959
142004
            url->flags |= URL_FLAGS_HAS_HOST;
1960
142004
            url->host.clear();
1961
142004
            if (has_state_override)
1962
2
              return;
1963
142002
            state = kPathStart;
1964
          } else {
1965
2324
            std::string host;
1966
1170
            if (!ParseHost(buffer, &host, special)) {
1967
14
              url->flags |= URL_FLAGS_FAILED;
1968
14
              return;
1969
            }
1970
1156
            if (host == "localhost")
1971
25
              host.clear();
1972
1156
            url->flags |= URL_FLAGS_HAS_HOST;
1973
1156
            url->host = host;
1974
1156
            if (has_state_override)
1975
2
              return;
1976
1154
            buffer.clear();
1977
1154
            state = kPathStart;
1978
          }
1979
143168
          continue;
1980
        } else {
1981
10071
          buffer += ch;
1982
        }
1983
10071
        break;
1984
      case kPathStart:
1985
233578
        if (IsSpecial(url->scheme)) {
1986
233188
          state = kPath;
1987

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

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

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

17032691
        if (ch == kEOL ||
2007
15352651
            ch == '/' ||
2008
15352580
            special_back_slash ||
2009

21301889
            (!has_state_override && (ch == '?' || ch == '#'))) {
2010
1680835
          if (IsDoubleDotSegment(buffer)) {
2011
1310
            ShortenUrlPath(url);
2012

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

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

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

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

1882398
                buffer.size() == 2 &&
2024
158
                IsWindowsDriveLetter(buffer)) {
2025

233
              if ((url->flags & URL_FLAGS_HAS_HOST) &&
2026
88
                  !url->host.empty()) {
2027
9
                url->host.clear();
2028
9
                url->flags |= URL_FLAGS_HAS_HOST;
2029
              }
2030
145
              buffer[1] = ':';
2031
            }
2032
1677908
            url->flags |= URL_FLAGS_HAS_PATH;
2033
1677908
            url->path.emplace_back(std::move(buffer));
2034
          }
2035
1680834
          buffer.clear();
2036

1913904
          if (url->scheme == "file:" &&
2037
1438589
              (ch == kEOL ||
2038
1438541
               ch == '?' ||
2039
               ch == '#')) {
2040

287761
            while (url->path.size() > 1 && url->path[0].length() == 0) {
2041
27346
              url->path.erase(url->path.begin());
2042
            }
2043
          }
2044
3361670
          if (ch == '?') {
2045
277
            url->flags |= URL_FLAGS_HAS_QUERY;
2046
277
            state = kQuery;
2047
1680558
          } else if (ch == '#') {
2048
447
            state = kFragment;
2049
          }
2050
        } else {
2051
15351856
          AppendOrEscape(&buffer, ch, PATH_ENCODE_SET);
2052
        }
2053
17032690
        break;
2054
      case kCannotBeBase:
2055
22727
        switch (ch) {
2056
          case '?':
2057
6
            state = kQuery;
2058
6
            break;
2059
          case '#':
2060
29
            state = kFragment;
2061
29
            break;
2062
          default:
2063
22692
            if (url->path.size() == 0)
2064
              url->path.emplace_back("");
2065

22692
            if (url->path.size() > 0 && ch != kEOL)
2066
21515
              AppendOrEscape(&url->path[0], ch, C0_CONTROL_ENCODE_SET);
2067
        }
2068
22727
        break;
2069
      case kQuery:
2070

3909
        if (ch == kEOL || (!has_state_override && ch == '#')) {
2071
455
          url->flags |= URL_FLAGS_HAS_QUERY;
2072
455
          url->query = std::move(buffer);
2073
455
          buffer.clear();
2074
910
          if (ch == '#')
2075
134
            state = kFragment;
2076
        } else {
2077
3454
          AppendOrEscape(&buffer, ch, special ? QUERY_ENCODE_SET_SPECIAL :
2078
3454
                                                QUERY_ENCODE_SET_NONSPECIAL);
2079
        }
2080
3909
        break;
2081
      case kFragment:
2082
58087
        switch (ch) {
2083
          case kEOL:
2084
712
            url->flags |= URL_FLAGS_HAS_FRAGMENT;
2085
712
            url->fragment = std::move(buffer);
2086
712
            break;
2087
          case 0:
2088
4
            break;
2089
          default:
2090
57371
            AppendOrEscape(&buffer, ch, FRAGMENT_ENCODE_SET);
2091
        }
2092
58087
        break;
2093
      default:
2094
        url->flags |= URL_FLAGS_INVALID_PARSE_STATE;
2095
        return;
2096
    }
2097
2098
18466407
    p++;
2099
  }
2100
}  // NOLINT(readability/fn_size)
2101
2102
namespace {
2103
183850
void SetArgs(Environment* env,
2104
             Local<Value> argv[ARG_COUNT],
2105
             const struct url_data& url) {
2106
183850
  Isolate* isolate = env->isolate();
2107
367700
  argv[ARG_FLAGS] = Integer::NewFromUnsigned(isolate, url.flags);
2108
183850
  argv[ARG_PROTOCOL] =
2109
183850
      url.flags & URL_FLAGS_SPECIAL ?
2110
181950
          GetSpecial(env, url.scheme) :
2111
733500
          OneByteString(isolate, url.scheme.c_str());
2112
183850
  if (url.flags & URL_FLAGS_HAS_USERNAME)
2113
372
    argv[ARG_USERNAME] = Utf8String(isolate, url.username);
2114
183850
  if (url.flags & URL_FLAGS_HAS_PASSWORD)
2115
324
    argv[ARG_PASSWORD] = Utf8String(isolate, url.password);
2116
183850
  if (url.flags & URL_FLAGS_HAS_HOST)
2117
364662
    argv[ARG_HOST] = Utf8String(isolate, url.host);
2118
183850
  if (url.flags & URL_FLAGS_HAS_QUERY)
2119
930
    argv[ARG_QUERY] = Utf8String(isolate, url.query);
2120
183850
  if (url.flags & URL_FLAGS_HAS_FRAGMENT)
2121
1416
    argv[ARG_FRAGMENT] = Utf8String(isolate, url.fragment);
2122
183850
  if (url.port > -1)
2123
2238
    argv[ARG_PORT] = Integer::New(isolate, url.port);
2124
183850
  if (url.flags & URL_FLAGS_HAS_PATH)
2125
367074
    argv[ARG_PATH] = ToV8Value(env->context(), url.path).ToLocalChecked();
2126
183850
}
2127
2128
185530
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
185530
  Isolate* isolate = env->isolate();
2138
185530
  Local<Context> context = env->context();
2139
371043
  HandleScope handle_scope(isolate);
2140
185513
  Context::Scope context_scope(context);
2141
2142
185530
  const bool has_context = context_obj->IsObject();
2143
185530
  const bool has_base = base_obj->IsObject();
2144
2145
371043
  url_data base;
2146
371043
  url_data url;
2147
185530
  if (has_context)
2148
60148
    url = HarvestContext(env, context_obj.As<Object>());
2149
185530
  if (has_base)
2150
4569
    base = HarvestBase(env, base_obj.As<Object>());
2151
2152
185530
  URL::Parse(input, len, state_override, &url, has_context, &base, has_base);
2153

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


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


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

807354
  CHECK(args[5]->IsUndefined() || args[5]->IsFunction());  // error callback
2197
2198
371060
  Utf8Value input(env->isolate(), args[0]);
2199
185530
  enum url_parse_state state_override = kUnknownState;
2200
371060
  if (args[1]->IsNumber()) {
2201
185530
    state_override = static_cast<enum url_parse_state>(
2202
927650
        args[1]->Uint32Value(env->context()).FromJust());
2203
  }
2204
2205
371060
  Parse(env, args.This(),
2206
185530
        *input, input.length(),
2207
        state_override,
2208
        args[2],
2209
        args[3],
2210
371060
        args[4].As<Function>(),
2211
185530
        args[5]);
2212
185530
}
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
223
void DomainToASCII(const FunctionCallbackInfo<Value>& args) {
2265
223
  Environment* env = Environment::GetCurrent(args);
2266
223
  CHECK_GE(args.Length(), 1);
2267
669
  CHECK(args[0]->IsString());
2268
436
  Utf8Value value(env->isolate(), args[0]);
2269
2270
436
  URLHost host;
2271
  // Assuming the host is used for a special scheme.
2272
223
  host.ParseHost(*value, value.length(), true);
2273
223
  if (host.ParsingFailed()) {
2274
30
    args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING(env->isolate(), ""));
2275
10
    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
384
void SetURLConstructor(const FunctionCallbackInfo<Value>& args) {
2301
384
  Environment* env = Environment::GetCurrent(args);
2302
384
  CHECK_EQ(args.Length(), 1);
2303
768
  CHECK(args[0]->IsFunction());
2304
768
  env->set_url_constructor_function(args[0].As<Function>());
2305
384
}
2306
2307
384
void Initialize(Local<Object> target,
2308
                Local<Value> unused,
2309
                Local<Context> context,
2310
                void* priv) {
2311
384
  Environment* env = Environment::GetCurrent(context);
2312
384
  env->SetMethod(target, "parse", Parse);
2313
384
  env->SetMethodNoSideEffect(target, "encodeAuth", EncodeAuthSet);
2314
384
  env->SetMethodNoSideEffect(target, "toUSVString", ToUSVString);
2315
384
  env->SetMethodNoSideEffect(target, "domainToASCII", DomainToASCII);
2316
384
  env->SetMethodNoSideEffect(target, "domainToUnicode", DomainToUnicode);
2317
384
  env->SetMethod(target, "setURLConstructor", SetURLConstructor);
2318
2319
#define XX(name, _) NODE_DEFINE_CONSTANT(target, name);
2320
19968
  FLAGS(XX)
2321
#undef XX
2322
2323
#define XX(name) NODE_DEFINE_CONSTANT(target, name);
2324
32256
  PARSESTATES(XX)
2325
#undef XX
2326
384
}
2327
}  // namespace
2328
2329
4920
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
2330
4920
  registry->Register(Parse);
2331
4920
  registry->Register(EncodeAuthSet);
2332
4920
  registry->Register(ToUSVString);
2333
4920
  registry->Register(DomainToASCII);
2334
4920
  registry->Register(DomainToUnicode);
2335
4920
  registry->Register(SetURLConstructor);
2336
4920
}
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
27255
URL URL::FromFilePath(const std::string& file_path) {
2401
27255
  URL url("file://");
2402
54510
  std::string escaped_file_path;
2403
3284268
  for (size_t i = 0; i < file_path.length(); ++i) {
2404
3257013
    escaped_file_path += file_path[i];
2405
3257013
    if (file_path[i] == '%')
2406
8
      escaped_file_path += "25";
2407
  }
2408
27255
  URL::Parse(escaped_file_path.c_str(), escaped_file_path.length(), kPathStart,
2409
27255
             &url.context_, true, nullptr, false);
2410
54510
  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
4989
NODE_MODULE_CONTEXT_AWARE_INTERNAL(url, node::url::Initialize)
2459

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