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: 1175 1216 96.6 %
Date: 2020-11-20 19:51:53 Branches: 1057 1181 89.5 %

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

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

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

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


976
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


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

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








83651
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


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


866
TWO_CHAR_STRING_TEST(8, IsNormalizedWindowsDriveLetter,
219
                     (IsASCIIAlpha(ch1) && ch2 == ':'))
220
221
// If a UTF-16 character is a low/trailing surrogate.
222
3
CHAR_TEST(16, IsUnicodeTrail, (ch & 0xFC00) == 0xDC00)
223
224
// If a UTF-16 character is a surrogate.
225
31
CHAR_TEST(16, IsUnicodeSurrogate, (ch & 0xF800) == 0xD800)
226
227
// If a UTF-16 surrogate is a low/trailing one.
228
18
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
10914510
bool BitAt(const uint8_t a[], const uint8_t i) {
673
10914510
  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
10914490
void AppendOrEscape(std::string* str,
679
                           const unsigned char ch,
680
                           const uint8_t encode_set[]) {
681
10914490
  if (BitAt(encode_set, ch))
682
1039
    *str += hex[ch];
683
  else
684
10913465
    *str += ch;
685
10914519
}
686
687
template <typename T>
688
642
unsigned hex2bin(const T ch) {
689

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

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

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


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



277865
  SPECIALS(V);
738
#undef V
739
5235
  return false;
740
}
741
742
110343
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



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









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

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

33
    if (length < 2 || pointer[1] != ':')
814
3
      return;
815
30
    pointer += 2;
816
30
    ch = pointer < end ? pointer[0] : kEOL;
817
30
    piece_pointer++;
818
30
    compress_pointer = piece_pointer;
819
  }
820
413
  while (ch != kEOL) {
821
223
    if (piece_pointer >= buffer_end)
822
3
      return;
823
220
    if (ch == ':') {
824
18
      if (compress_pointer != nullptr)
825
3
        return;
826
15
      pointer++;
827
15
      ch = pointer < end ? pointer[0] : kEOL;
828
15
      piece_pointer++;
829
15
      compress_pointer = piece_pointer;
830
15
      continue;
831
    }
832
202
    value = 0;
833
202
    len = 0;
834

642
    while (len < 4 && IsASCIIHexDigit(ch)) {
835
220
      value = value * 0x10 + hex2bin(ch);
836
220
      pointer++;
837
220
      ch = pointer < end ? pointer[0] : kEOL;
838
220
      len++;
839
    }
840

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

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

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

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

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

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

3242
  } else if (R == 10 && end - start > 1 && start[0] == '0') {
925
32
    start++;
926
32
    R = 8;
927
  }
928
3242
  const char* p = start;
929
930
4732
  while (p < end) {
931
3775
    const char ch = p[0];
932

3775
    switch (R) {
933
      case 8:
934

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

29665
    if (ch == '.' || ch == kEOL) {
968
3254
      if (++parts > static_cast<int>(arraysize(numbers)))
969
2
        return;
970
3252
      if (pointer == mark)
971
6
        return;
972
3246
      int64_t n = ParseNumber(mark, pointer);
973
3246
      if (n < 0)
974
3030
        return;
975
976
216
      if (n > 255) {
977
69
        tooBigNumbers++;
978
      }
979
216
      numbers[parts - 1] = n;
980
216
      mark = pointer + 1;
981

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

143
  if (tooBigNumbers > 1 ||
993

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

1491
    if (ch != '%' && IsForbiddenHostCodePoint(ch)) {
1015
35
      return;
1016
    } else {
1017
1456
      AppendOrEscape(&output, ch, C0_CONTROL_ENCODE_SET);
1018
    }
1019
  }
1020
1021
288
  SetOpaque(std::move(output));
1022
}
1023
1024
3690
void URLHost::ParseHost(const char* input,
1025
                        size_t length,
1026
                        bool is_special,
1027
                        bool unicode) {
1028
3690
  CHECK_EQ(type_, HostType::H_FAILED);
1029
3690
  const char* pointer = input;
1030
1031
3690
  if (length == 0)
1032
652
    return;
1033
1034
3690
  if (pointer[0] == '[') {
1035
98
    if (pointer[length - 1] != ']')
1036
6
      return;
1037
92
    return ParseIPv6Host(++pointer, length - 2);
1038
  }
1039
1040
3592
  if (!is_special)
1041
323
    return ParseOpaqueHost(input, length);
1042
1043
  // First, we have to percent decode
1044
6307
  std::string decoded = PercentDecode(input, length);
1045
1046
  // Then we have to punycode toASCII
1047
3269
  if (!ToASCII(decoded, &decoded))
1048
93
    return;
1049
1050
  // If any of the following characters are still present, we have to fail
1051
85285
  for (size_t n = 0; n < decoded.size(); n++) {
1052
82174
    const char ch = decoded[n];
1053
82174
    if (IsForbiddenHostCodePoint(ch)) {
1054
65
      return;
1055
    }
1056
  }
1057
1058
  // Check to see if it's an IPv4 IP address
1059
  bool is_ipv4;
1060
3111
  ParseIPv4Host(decoded.c_str(), decoded.length(), &is_ipv4);
1061
3111
  if (is_ipv4)
1062
73
    return;
1063
1064
  // If the unicode flag is set, run the result through punycode ToUnicode
1065

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

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

200
        if (ignore0 && *piece == 0)
1148
255
          continue;
1149
84
        else if (ignore0)
1150
20
          ignore0 = false;
1151
84
        if (compress_pointer == piece) {
1152
23
          dest += n == 0 ? "::" : ":";
1153
23
          ignore0 = true;
1154
23
          continue;
1155
        }
1156
        char buf[5];
1157
61
        snprintf(buf, sizeof(buf), "%x", *piece);
1158
61
        dest += buf;
1159
61
        if (n < 7)
1160
39
          dest += ':';
1161
      }
1162
25
      dest += ']';
1163
25
      break;
1164
    }
1165
    case HostType::H_FAILED:
1166
      break;
1167
  }
1168
77
  return dest;
1169
}
1170
1171
3299
bool ParseHost(const std::string& input,
1172
               std::string* output,
1173
               bool is_special,
1174
               bool unicode = false) {
1175
3299
  if (input.empty()) {
1176
45
    output->clear();
1177
45
    return true;
1178
  }
1179
6508
  URLHost host;
1180
3254
  host.ParseHost(input.c_str(), input.length(), is_special, unicode);
1181
3254
  if (host.ParsingFailed())
1182
263
    return false;
1183
2991
  *output = host.ToStringMove();
1184
2991
  return true;
1185
}
1186
1187
3982
std::vector<std::string> FromJSStringArray(Environment* env,
1188
                                           Local<Array> array) {
1189
3982
  std::vector<std::string> vec;
1190
3982
  if (array->Length() > 0)
1191
3974
    vec.reserve(array->Length());
1192
58700
  for (size_t n = 0; n < array->Length(); n++) {
1193
76104
    Local<Value> val = array->Get(env->context(), n).ToLocalChecked();
1194
50736
    if (val->IsString()) {
1195
50736
      Utf8Value value(env->isolate(), val.As<String>());
1196
25368
      vec.emplace_back(*value, value.length());
1197
    }
1198
  }
1199
3982
  return vec;
1200
}
1201
1202
3982
url_data HarvestBase(Environment* env, Local<Object> base_obj) {
1203
3982
  url_data base;
1204
3982
  Local<Context> context = env->context();
1205
1206
  Local<Value> flags =
1207
15928
      base_obj->Get(env->context(), env->flags_string()).ToLocalChecked();
1208
3982
  if (flags->IsInt32())
1209
7964
    base.flags = flags->Int32Value(context).FromJust();
1210
1211
  Local<Value> port =
1212
15928
      base_obj->Get(env->context(), env->port_string()).ToLocalChecked();
1213
3982
  if (port->IsInt32())
1214
8
    base.port = port->Int32Value(context).FromJust();
1215
1216
  Local<Value> scheme =
1217
15928
      base_obj->Get(env->context(), env->scheme_string()).ToLocalChecked();
1218
3982
  base.scheme = Utf8Value(env->isolate(), scheme).out();
1219
1220
  auto GetStr = [&](std::string url_data::*member,
1221
                    int flag,
1222
                    Local<String> name,
1223
19910
                    bool empty_as_present) {
1224
71125
    Local<Value> value = base_obj->Get(env->context(), name).ToLocalChecked();
1225
39820
    if (value->IsString()) {
1226
22790
      Utf8Value utf8value(env->isolate(), value.As<String>());
1227
14838
      (base.*member).assign(*utf8value, utf8value.length());
1228

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

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

1212410
  switch (str.size()) {
1325
    case 2:
1326
2188
      return str == "..";
1327
    case 4:
1328

290865
      if (str[0] != '.' && str[0] != '%')
1329
290853
        return false;
1330
21
      return ((str[0] == '.' &&
1331
11
               str[1] == '%' &&
1332
4
               str[2] == '2' &&
1333

29
               ASCIILowercase(str[3]) == 'e') ||
1334
13
              (str[0] == '%' &&
1335
6
               str[1] == '2' &&
1336
6
               ASCIILowercase(str[2]) == 'e' &&
1337
15
               str[3] == '.'));
1338
    case 6:
1339
59768
      return (str[0] == '%' &&
1340
14
              str[1] == '2' &&
1341
9
              ASCIILowercase(str[2]) == 'e' &&
1342
4
              str[3] == '%' &&
1343

59765
              str[4] == '2' &&
1344
59763
              ASCIILowercase(str[5]) == 'e');
1345
    default:
1346
859599
      return false;
1347
  }
1348
}
1349
1350
4855
void ShortenUrlPath(struct url_data* url) {
1351
4855
  if (url->path.empty()) return;
1352


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

179653
  if (state < kSchemeStart || state > kFragment) {
1424
    url->flags |= URL_FLAGS_INVALID_PARSE_STATE;
1425
    return;
1426
  }
1427
1428

26826107
  while (p <= end) {
1429
13325402
    const char ch = p < end ? p[0] : kEOL;
1430
13325402
    bool special = (url->flags & URL_FLAGS_SPECIAL);
1431
    bool cannot_be_base;
1432

13325402
    const bool special_back_slash = (special && ch == '\\');
1433
1434





13325402
    switch (state) {
1435
      case kSchemeStart:
1436
112635
        if (IsASCIIAlpha(ch)) {
1437
108783
          buffer += ASCIILowercase(ch);
1438
108558
          state = kScheme;
1439
3840
        } else if (!has_state_override) {
1440
3833
          state = kNoScheme;
1441
3833
          continue;
1442
        } else {
1443
7
          url->flags |= URL_FLAGS_FAILED;
1444
7
          return;
1445
        }
1446
108558
        break;
1447
      case kScheme:
1448


441354
        if (IsASCIIAlphanumeric(ch) || ch == '+' || ch == '-' || ch == '.') {
1449
332571
          buffer += ASCIILowercase(ch);
1450

108783
        } else if (ch == ':' || (has_state_override && ch == kEOL)) {
1451

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

62
            if ((special != new_is_special) ||
1461
29
                ((buffer == "file:") &&
1462
4
                 ((url->flags & URL_FLAGS_HAS_USERNAME) ||
1463
2
                  (url->flags & URL_FLAGS_HAS_PASSWORD) ||
1464

76
                  (url->port != -1))) ||
1465
26
                  (url->scheme == "file:" && url->host.empty())) {
1466
16
              url->flags |= URL_FLAGS_TERMINATED;
1467
16
              return;
1468
            }
1469
          }
1470
1471
108058
          url->scheme = std::move(buffer);
1472
108058
          url->port = NormalizePort(url->scheme, url->port);
1473
108057
          if (new_is_special) {
1474
103231
            url->flags |= URL_FLAGS_SPECIAL;
1475
103231
            special = true;
1476
          } else {
1477
4826
            url->flags &= ~URL_FLAGS_SPECIAL;
1478
4826
            special = false;
1479
          }
1480
108057
          buffer.clear();
1481
108057
          if (has_state_override)
1482
20
            return;
1483
108037
          if (url->scheme == "file:") {
1484
100478
            state = kFile;
1485

10303
          } else if (special &&
1486

8076
                     has_base &&
1487
517
                     url->scheme == base->scheme) {
1488
178
            state = kSpecialRelativeOrAuthority;
1489
7381
          } else if (special) {
1490
2566
            state = kSpecialAuthoritySlashes;
1491

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

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

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

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

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

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

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


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

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

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

413
          if (blen > 0 && buffer[0] != ':') {
1720
355
            url->flags |= URL_FLAGS_HAS_USERNAME;
1721
          }
1722
5421
          for (size_t n = 0; n < blen; n++) {
1723
5008
            const char bch = buffer[n];
1724
5008
            if (bch == ':') {
1725
349
              url->flags |= URL_FLAGS_HAS_PASSWORD;
1726
349
              if (!password_token_seen_flag) {
1727
347
                password_token_seen_flag = true;
1728
347
                continue;
1729
              }
1730
            }
1731
4661
            if (password_token_seen_flag) {
1732
2281
              AppendOrEscape(&url->password, bch, USERINFO_ENCODE_SET);
1733
            } else {
1734
2380
              AppendOrEscape(&url->username, bch, USERINFO_ENCODE_SET);
1735
            }
1736
          }
1737
413
          buffer.clear();
1738

80638
        } else if (ch == kEOL ||
1739
77607
                   ch == '/' ||
1740
77589
                   ch == '?' ||
1741
77579
                   ch == '#' ||
1742
                   special_back_slash) {
1743

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

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

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

73625
        } else if (ch == kEOL ||
1775
71290
                   ch == '/' ||
1776
71268
                   ch == '?' ||
1777
71254
                   ch == '#' ||
1778
                   special_back_slash) {
1779
2381
          p--;
1780

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

2560
          if (has_state_override &&
1785

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

53
              ((url->username.size() > 0 || url->password.size() > 0) ||
1787
17
               url->port != -1)) {
1788
4
            url->flags |= URL_FLAGS_TERMINATED;
1789
4
            return;
1790
          }
1791
2365
          url->flags |= URL_FLAGS_HAS_HOST;
1792
2365
          if (!ParseHost(buffer, &url->host, special)) {
1793
237
            url->flags |= URL_FLAGS_FAILED;
1794
237
            return;
1795
          }
1796
2128
          buffer.clear();
1797
2128
          state = kPathStart;
1798
4123
          if (has_state_override) {
1799
133
            return;
1800
          }
1801
        } else {
1802
71244
          if (ch == '[')
1803
94
            square_bracket_flag = true;
1804
71244
          if (ch == ']')
1805
91
            square_bracket_flag = false;
1806
71244
          buffer += ch;
1807
        }
1808
74076
        break;
1809
      case kPort:
1810
4747
        if (IsASCIIDigit(ch)) {
1811
3863
          buffer += ch;
1812

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

4549
            for (size_t i = 0; port <= 0xffff && i < buffer.size(); i++)
1822
3701
              port = port * 10 + buffer[i] - '0';
1823
848
            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
830
            url->port = NormalizePort(url->scheme, static_cast<int>(port));
1836
830
            if (url->port == -1)
1837
28
              url->flags |= URL_FLAGS_IS_DEFAULT_SCHEME_PORT;
1838
830
            buffer.clear();
1839
9
          } else if (has_state_override) {
1840
            // TODO(TimothyGu): Similar case as above.
1841
5
            if (state_override == kHost)
1842
1
              url->port = -1;
1843
            else
1844
4
              url->flags |= URL_FLAGS_TERMINATED;
1845
5
            return;
1846
          }
1847
834
          state = kPathStart;
1848
834
          continue;
1849
        } else {
1850
27
          url->flags |= URL_FLAGS_FAILED;
1851
27
          return;
1852
        }
1853
3863
        break;
1854
      case kFile:
1855
103400
        url->scheme = "file:";
1856
103401
        url->host.clear();
1857
103401
        url->flags |= URL_FLAGS_HAS_HOST;
1858

103401
        if (ch == '/' || ch == '\\') {
1859
100583
          state = kFileSlash;
1860

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

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

100583
        if (ch == '/' || ch == '\\') {
1927
100476
          state = kFileHost;
1928
        } else {
1929

107
          if (has_base && base->scheme == "file:") {
1930
103
            url->flags |= URL_FLAGS_HAS_HOST;
1931
103
            url->host = base->host;
1932

201
            if (!StartsWithWindowsDriveLetter(p, end) &&
1933
98
                IsNormalizedWindowsDriveLetter(base->path[0])) {
1934
2
              url->flags |= URL_FLAGS_HAS_PATH;
1935
2
              url->path.push_back(base->path[0]);
1936
            }
1937
          }
1938
107
          state = kPath;
1939
107
          continue;
1940
        }
1941
100476
        break;
1942
      case kFileHost:
1943

101041
        if (ch == kEOL ||
1944
564
            ch == '/' ||
1945
559
            ch == '\\' ||
1946
559
            ch == '?' ||
1947
            ch == '#') {
1948

301440
          if (!has_state_override &&
1949

100492
              buffer.size() == 2 &&
1950
10
              IsWindowsDriveLetter(buffer)) {
1951
4
            state = kPath;
1952
100478
          } else if (buffer.size() == 0) {
1953
100386
            url->flags |= URL_FLAGS_HAS_HOST;
1954
100386
            url->host.clear();
1955
100386
            if (has_state_override)
1956
2
              return;
1957
100384
            state = kPathStart;
1958
          } else {
1959
159
            std::string host;
1960
92
            if (!ParseHost(buffer, &host, special)) {
1961
23
              url->flags |= URL_FLAGS_FAILED;
1962
23
              return;
1963
            }
1964
69
            if (host == "localhost")
1965
22
              host.clear();
1966
69
            url->flags |= URL_FLAGS_HAS_HOST;
1967
69
            url->host = host;
1968
69
            if (has_state_override)
1969
2
              return;
1970
67
            buffer.clear();
1971
67
            state = kPathStart;
1972
          }
1973
100455
          continue;
1974
        } else {
1975
559
          buffer += ch;
1976
        }
1977
559
        break;
1978
      case kPathStart:
1979
169493
        if (IsSpecial(url->scheme)) {
1980
169164
          state = kPath;
1981

169164
          if (ch != '/' && ch != '\\') {
1982
66746
            continue;
1983
          }
1984

330
        } else if (!has_state_override && ch == '?') {
1985
3
          url->flags |= URL_FLAGS_HAS_QUERY;
1986
3
          url->query.clear();
1987
3
          state = kQuery;
1988

327
        } else if (!has_state_override && ch == '#') {
1989
3
          url->flags |= URL_FLAGS_HAS_FRAGMENT;
1990
3
          url->fragment.clear();
1991
3
          state = kFragment;
1992
324
        } else if (ch != kEOL) {
1993
282
          state = kPath;
1994
282
          if (ch != '/') {
1995
26
            continue;
1996
          }
1997
        }
1998
102722
        break;
1999
      case kPath:
2000

12083087
        if (ch == kEOL ||
2001
10871129
            ch == '/' ||
2002
10871096
            special_back_slash ||
2003

14586561
            (!has_state_override && (ch == '?' || ch == '#'))) {
2004
1212379
          if (IsDoubleDotSegment(buffer)) {
2005
1911
            ShortenUrlPath(url);
2006

1911
            if (ch != '/' && !special_back_slash) {
2007
171
              url->flags |= URL_FLAGS_HAS_PATH;
2008
171
              url->path.emplace_back("");
2009
            }
2010

2422076
          } else if (IsSingleDotSegment(buffer) &&
2011

1210809
                     ch != '/' && !special_back_slash) {
2012
310
            url->flags |= URL_FLAGS_HAS_PATH;
2013
310
            url->path.emplace_back("");
2014
1210188
          } else if (!IsSingleDotSegment(buffer)) {
2015

3624672
            if (url->scheme == "file:" &&
2016
1341689
                url->path.empty() &&
2017

1345311
                buffer.size() == 2 &&
2018
45
                IsWindowsDriveLetter(buffer)) {
2019
44
              buffer[1] = ':';
2020
            }
2021
1209416
            url->flags |= URL_FLAGS_HAS_PATH;
2022
1209416
            url->path.emplace_back(std::move(buffer));
2023
          }
2024
1212410
          buffer.clear();
2025
2424820
          if (ch == '?') {
2026
376
            url->flags |= URL_FLAGS_HAS_QUERY;
2027
376
            url->query.clear();
2028
376
            state = kQuery;
2029
1212034
          } else if (ch == '#') {
2030
12
            url->flags |= URL_FLAGS_HAS_FRAGMENT;
2031
12
            url->fragment.clear();
2032
12
            state = kFragment;
2033
          }
2034
        } else {
2035
10870708
          AppendOrEscape(&buffer, ch, PATH_ENCODE_SET);
2036
        }
2037
12083108
        break;
2038
      case kCannotBeBase:
2039
34188
        switch (ch) {
2040
          case '?':
2041
2
            state = kQuery;
2042
2
            break;
2043
          case '#':
2044
5
            state = kFragment;
2045
5
            break;
2046
          default:
2047
34181
            if (url->path.empty())
2048
              url->path.emplace_back("");
2049
34181
            else if (ch != kEOL)
2050
29782
              AppendOrEscape(&url->path[0], ch, C0_CONTROL_ENCODE_SET);
2051
        }
2052
34188
        break;
2053
      case kQuery:
2054

4795
        if (ch == kEOL || (!has_state_override && ch == '#')) {
2055
552
          url->flags |= URL_FLAGS_HAS_QUERY;
2056
552
          url->query = std::move(buffer);
2057
552
          buffer.clear();
2058
1104
          if (ch == '#')
2059
318
            state = kFragment;
2060
        } else {
2061
4243
          AppendOrEscape(&buffer, ch, special ? QUERY_ENCODE_SET_SPECIAL :
2062
4243
                                                QUERY_ENCODE_SET_NONSPECIAL);
2063
        }
2064
4795
        break;
2065
      case kFragment:
2066
3772
        switch (ch) {
2067
          case kEOL:
2068
550
            url->flags |= URL_FLAGS_HAS_FRAGMENT;
2069
550
            url->fragment = std::move(buffer);
2070
550
            break;
2071
          default:
2072
3222
            AppendOrEscape(&buffer, ch, FRAGMENT_ENCODE_SET);
2073
        }
2074
3772
        break;
2075
      default:
2076
        url->flags |= URL_FLAGS_INVALID_PARSE_STATE;
2077
        return;
2078
    }
2079
2080
13141458
    p++;
2081
  }
2082
}  // NOLINT(readability/fn_size)
2083
2084
namespace {
2085
115307
void SetArgs(Environment* env,
2086
             Local<Value> argv[ARG_COUNT],
2087
             const struct url_data& url) {
2088
115307
  Isolate* isolate = env->isolate();
2089
230615
  argv[ARG_FLAGS] = Integer::NewFromUnsigned(isolate, url.flags);
2090
115308
  argv[ARG_PROTOCOL] =
2091
115308
      url.flags & URL_FLAGS_SPECIAL ?
2092
110343
          GetSpecial(env, url.scheme) :
2093
456267
          OneByteString(isolate, url.scheme.c_str());
2094
115308
  if (url.flags & URL_FLAGS_HAS_USERNAME)
2095
1040
    argv[ARG_USERNAME] = Utf8String(isolate, url.username);
2096
115308
  if (url.flags & URL_FLAGS_HAS_PASSWORD)
2097
1028
    argv[ARG_PASSWORD] = Utf8String(isolate, url.password);
2098
115308
  if (url.flags & URL_FLAGS_HAS_HOST)
2099
221554
    argv[ARG_HOST] = Utf8String(isolate, url.host);
2100
115308
  if (url.flags & URL_FLAGS_HAS_QUERY)
2101
1108
    argv[ARG_QUERY] = Utf8String(isolate, url.query);
2102
115308
  if (url.flags & URL_FLAGS_HAS_FRAGMENT)
2103
1092
    argv[ARG_FRAGMENT] = Utf8String(isolate, url.fragment);
2104
115308
  if (url.port > -1)
2105
1926
    argv[ARG_PORT] = Integer::New(isolate, url.port);
2106
115308
  if (url.flags & URL_FLAGS_HAS_PATH)
2107
229554
    argv[ARG_PATH] = ToV8Value(env->context(), url.path).ToLocalChecked();
2108
115308
}
2109
2110
117103
void Parse(Environment* env,
2111
           Local<Value> recv,
2112
           const char* input,
2113
           size_t len,
2114
           enum url_parse_state state_override,
2115
           Local<Value> base_obj,
2116
           Local<Value> context_obj,
2117
           Local<Function> cb,
2118
           Local<Value> error_cb) {
2119
117103
  Isolate* isolate = env->isolate();
2120
117103
  Local<Context> context = env->context();
2121
234183
  HandleScope handle_scope(isolate);
2122
117080
  Context::Scope context_scope(context);
2123
2124
117103
  const bool has_context = context_obj->IsObject();
2125
117103
  const bool has_base = base_obj->IsObject();
2126
2127
234182
  url_data base;
2128
234182
  url_data url;
2129
117103
  if (has_context)
2130
35695
    url = HarvestContext(env, context_obj.As<Object>());
2131
117103
  if (has_base)
2132
3982
    base = HarvestBase(env, base_obj.As<Object>());
2133
2134
117103
  URL::Parse(input, len, state_override, &url, has_context, &base, has_base);
2135

117103
  if ((url.flags & URL_FLAGS_INVALID_PARSE_STATE) ||
2136
35695
      ((state_override != kUnknownState) &&
2137
35695
       (url.flags & URL_FLAGS_TERMINATED)))
2138
24
    return;
2139
2140
  // Define the return value placeholders
2141
  const Local<Value> undef = Undefined(isolate);
2142
  const Local<Value> null = Null(isolate);
2143
117079
  if (!(url.flags & URL_FLAGS_FAILED)) {
2144
    Local<Value> argv[] = {
2145
      undef,
2146
      undef,
2147
      undef,
2148
      undef,
2149
      null,  // host defaults to null
2150
      null,  // port defaults to null
2151
      undef,
2152
      null,  // query defaults to null
2153
      null,  // fragment defaults to null
2154
115307
    };
2155
115307
    SetArgs(env, argv, url);
2156
345924
    cb->Call(context, recv, arraysize(argv), argv).FromMaybe(Local<Value>());
2157
1772
  } else if (error_cb->IsFunction()) {
2158
1699
    Local<Value> argv[2] = { undef, undef };
2159
3398
    argv[ERR_ARG_FLAGS] = Integer::NewFromUnsigned(isolate, url.flags);
2160
1699
    argv[ERR_ARG_INPUT] =
2161
3398
      String::NewFromUtf8(env->isolate(), input).ToLocalChecked();
2162
6796
    error_cb.As<Function>()->Call(context, recv, arraysize(argv), argv)
2163
1699
        .FromMaybe(Local<Value>());
2164
  }
2165
}
2166
2167
117104
void Parse(const FunctionCallbackInfo<Value>& args) {
2168
117104
  Environment* env = Environment::GetCurrent(args);
2169
117104
  CHECK_GE(args.Length(), 5);
2170
351312
  CHECK(args[0]->IsString());  // input
2171


478307
  CHECK(args[2]->IsUndefined() ||  // base context
2172
        args[2]->IsNull() ||
2173
        args[2]->IsObject());
2174


529787
  CHECK(args[3]->IsUndefined() ||  // context
2175
        args[3]->IsNull() ||
2176
        args[3]->IsObject());
2177
234208
  CHECK(args[4]->IsFunction());  // complete callback
2178

514130
  CHECK(args[5]->IsUndefined() || args[5]->IsFunction());  // error callback
2179
2180
234208
  Utf8Value input(env->isolate(), args[0]);
2181
117104
  enum url_parse_state state_override = kUnknownState;
2182
234208
  if (args[1]->IsNumber()) {
2183
117104
    state_override = static_cast<enum url_parse_state>(
2184
585520
        args[1]->Uint32Value(env->context()).FromJust());
2185
  }
2186
2187
234207
  Parse(env, args.This(),
2188
117103
        *input, input.length(),
2189
        state_override,
2190
        args[2],
2191
        args[3],
2192
234207
        args[4].As<Function>(),
2193
117103
        args[5]);
2194
117103
}
2195
2196
82
void EncodeAuthSet(const FunctionCallbackInfo<Value>& args) {
2197
82
  Environment* env = Environment::GetCurrent(args);
2198
82
  CHECK_GE(args.Length(), 1);
2199
246
  CHECK(args[0]->IsString());
2200
164
  Utf8Value value(env->isolate(), args[0]);
2201
164
  std::string output;
2202
82
  size_t len = value.length();
2203
82
  output.reserve(len);
2204
593
  for (size_t n = 0; n < len; n++) {
2205
511
    const char ch = (*value)[n];
2206
511
    AppendOrEscape(&output, ch, USERINFO_ENCODE_SET);
2207
  }
2208
164
  args.GetReturnValue().Set(
2209
164
      String::NewFromUtf8(env->isolate(), output.c_str()).ToLocalChecked());
2210
82
}
2211
2212
16
void ToUSVString(const FunctionCallbackInfo<Value>& args) {
2213
16
  Environment* env = Environment::GetCurrent(args);
2214
16
  CHECK_GE(args.Length(), 2);
2215
48
  CHECK(args[0]->IsString());
2216
32
  CHECK(args[1]->IsNumber());
2217
2218
32
  TwoByteValue value(env->isolate(), args[0]);
2219
2220
64
  int64_t start = args[1]->IntegerValue(env->context()).FromJust();
2221
16
  CHECK_GE(start, 0);
2222
2223
47
  for (size_t i = start; i < value.length(); i++) {
2224
31
    char16_t c = value[i];
2225
31
    if (!IsUnicodeSurrogate(c)) {
2226
13
      continue;
2227

18
    } else if (IsUnicodeSurrogateTrail(c) || i == value.length() - 1) {
2228
15
      value[i] = kUnicodeReplacementCharacter;
2229
    } else {
2230
3
      char16_t d = value[i + 1];
2231
3
      if (IsUnicodeTrail(d)) {
2232
        i++;
2233
      } else {
2234
3
        value[i] = kUnicodeReplacementCharacter;
2235
      }
2236
    }
2237
  }
2238
2239
32
  args.GetReturnValue().Set(
2240
32
      String::NewFromTwoByte(env->isolate(),
2241
16
                             *value,
2242
                             NewStringType::kNormal,
2243
32
                             value.length()).ToLocalChecked());
2244
16
}
2245
2246
229
void DomainToASCII(const FunctionCallbackInfo<Value>& args) {
2247
229
  Environment* env = Environment::GetCurrent(args);
2248
229
  CHECK_GE(args.Length(), 1);
2249
687
  CHECK(args[0]->IsString());
2250
446
  Utf8Value value(env->isolate(), args[0]);
2251
2252
446
  URLHost host;
2253
  // Assuming the host is used for a special scheme.
2254
229
  host.ParseHost(*value, value.length(), true);
2255
229
  if (host.ParsingFailed()) {
2256
36
    args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING(env->isolate(), ""));
2257
12
    return;
2258
  }
2259
434
  std::string out = host.ToStringMove();
2260
434
  args.GetReturnValue().Set(
2261
434
      String::NewFromUtf8(env->isolate(), out.c_str()).ToLocalChecked());
2262
}
2263
2264
207
void DomainToUnicode(const FunctionCallbackInfo<Value>& args) {
2265
207
  Environment* env = Environment::GetCurrent(args);
2266
207
  CHECK_GE(args.Length(), 1);
2267
621
  CHECK(args[0]->IsString());
2268
402
  Utf8Value value(env->isolate(), args[0]);
2269
2270
402
  URLHost host;
2271
  // Assuming the host is used for a special scheme.
2272
207
  host.ParseHost(*value, value.length(), true, true);
2273
207
  if (host.ParsingFailed()) {
2274
36
    args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING(env->isolate(), ""));
2275
12
    return;
2276
  }
2277
390
  std::string out = host.ToStringMove();
2278
390
  args.GetReturnValue().Set(
2279
390
      String::NewFromUtf8(env->isolate(), out.c_str()).ToLocalChecked());
2280
}
2281
2282
438
void SetURLConstructor(const FunctionCallbackInfo<Value>& args) {
2283
438
  Environment* env = Environment::GetCurrent(args);
2284
438
  CHECK_EQ(args.Length(), 1);
2285
876
  CHECK(args[0]->IsFunction());
2286
876
  env->set_url_constructor_function(args[0].As<Function>());
2287
438
}
2288
2289
438
void Initialize(Local<Object> target,
2290
                Local<Value> unused,
2291
                Local<Context> context,
2292
                void* priv) {
2293
438
  Environment* env = Environment::GetCurrent(context);
2294
438
  env->SetMethod(target, "parse", Parse);
2295
438
  env->SetMethodNoSideEffect(target, "encodeAuth", EncodeAuthSet);
2296
438
  env->SetMethodNoSideEffect(target, "toUSVString", ToUSVString);
2297
438
  env->SetMethodNoSideEffect(target, "domainToASCII", DomainToASCII);
2298
438
  env->SetMethodNoSideEffect(target, "domainToUnicode", DomainToUnicode);
2299
438
  env->SetMethod(target, "setURLConstructor", SetURLConstructor);
2300
2301
#define XX(name, _) NODE_DEFINE_CONSTANT(target, name);
2302
13140
  FLAGS(XX)
2303
#undef XX
2304
2305
#define XX(name) NODE_DEFINE_CONSTANT(target, name);
2306
26280
  PARSESTATES(XX)
2307
1752
#undef XX
2308
1314
}
2309
1752
}  // namespace
2310
2628
2311
5915
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
2312
5915
  registry->Register(Parse);
2313
5477
  registry->Register(EncodeAuthSet);
2314
6353
  registry->Register(ToUSVString);
2315
5915
  registry->Register(DomainToASCII);
2316
5915
  registry->Register(DomainToUnicode);
2317
5915
  registry->Register(SetURLConstructor);
2318
6353
}
2319
2628
2320
2198
std::string URL::ToFilePath() const {
2321
1322
  if (context_.scheme != "file:") {
2322
877
    return "";
2323
1752
  }
2324
1752
2325
1314
#ifdef _WIN32
2326
1752
  const char* slash = "\\";
2327
2190
  auto is_slash = [] (char ch) {
2328
1752
    return ch == '/' || ch == '\\';
2329
1752
  };
2330
876
#else
2331
1321
  const char* slash = "/";
2332
1798
  auto is_slash = [] (char ch) {
2333
1752
    return ch == '/';
2334
922
  };
2335

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

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