uri.cc 15.7 KB
Newer Older
1 2 3 4
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#include "src/strings/uri.h"
6

7 8
#include <vector>

9
#include "src/execution/isolate-inl.h"
10 11 12
#include "src/strings/char-predicates-inl.h"
#include "src/strings/string-search.h"
#include "src/strings/unicode-inl.h"
13 14 15 16

namespace v8 {
namespace internal {

17
namespace {  // anonymous namespace for DecodeURI helper functions
18
bool IsReservedPredicate(base::uc16 c) {
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
  switch (c) {
    case '#':
    case '$':
    case '&':
    case '+':
    case ',':
    case '/':
    case ':':
    case ';':
    case '=':
    case '?':
    case '@':
      return true;
    default:
      return false;
  }
}

bool IsReplacementCharacter(const uint8_t* octets, int length) {
  // The replacement character is at codepoint U+FFFD in the Unicode Specials
  // table. Its UTF-8 encoding is 0xEF 0xBF 0xBD.
40 41
  if (length != 3 || octets[0] != 0xEF || octets[1] != 0xBF ||
      octets[2] != 0xBD) {
42 43 44 45 46
    return false;
  }
  return true;
}

47
bool DecodeOctets(const uint8_t* octets, int length,
48
                  std::vector<base::uc16>* buffer) {
49
  size_t cursor = 0;
50
  base::uc32 value = unibrow::Utf8::ValueOf(octets, length, &cursor);
51 52 53 54 55
  if (value == unibrow::Utf8::kBadChar &&
      !IsReplacementCharacter(octets, length)) {
    return false;
  }

56 57
  if (value <=
      static_cast<base::uc32>(unibrow::Utf16::kMaxNonSurrogateCharCode)) {
58
    buffer->push_back(value);
59
  } else {
60 61
    buffer->push_back(unibrow::Utf16::LeadSurrogate(value));
    buffer->push_back(unibrow::Utf16::TrailSurrogate(value));
62 63 64 65
  }
  return true;
}

66
int TwoDigitHex(base::uc16 character1, base::uc16 character2) {
67
  if (character1 > 'f') return -1;
68
  int high = base::HexValue(character1);
69 70
  if (high == -1) return -1;
  if (character2 > 'f') return -1;
71
  int low = base::HexValue(character2);
72 73
  if (low == -1) return -1;
  return (high << 4) + low;
74 75 76
}

template <typename T>
77 78
void AddToBuffer(base::uc16 decoded, String::FlatContent* uri_content,
                 int index, bool is_uri, std::vector<T>* buffer) {
79
  if (is_uri && IsReservedPredicate(decoded)) {
80
    buffer->push_back('%');
81 82
    base::uc16 first = uri_content->Get(index + 1);
    base::uc16 second = uri_content->Get(index + 2);
83 84 85
    DCHECK_GT(std::numeric_limits<T>::max(), first);
    DCHECK_GT(std::numeric_limits<T>::max(), second);

86 87
    buffer->push_back(first);
    buffer->push_back(second);
88
  } else {
89
    buffer->push_back(decoded);
90 91 92 93
  }
}

bool IntoTwoByte(int index, bool is_uri, int uri_length,
94 95
                 String::FlatContent* uri_content,
                 std::vector<base::uc16>* buffer) {
96
  for (int k = index; k < uri_length; k++) {
97
    base::uc16 code = uri_content->Get(k);
98
    if (code == '%') {
99
      int two_digits;
100
      if (k + 2 >= uri_length ||
101 102
          (two_digits = TwoDigitHex(uri_content->Get(k + 1),
                                    uri_content->Get(k + 2))) < 0) {
103 104 105
        return false;
      }
      k += 2;
106
      base::uc16 decoded = static_cast<base::uc16>(two_digits);
107 108 109 110 111 112 113 114 115 116
      if (decoded > unibrow::Utf8::kMaxOneByteChar) {
        uint8_t octets[unibrow::Utf8::kMaxEncodedSize];
        octets[0] = decoded;

        int number_of_continuation_bytes = 0;
        while ((decoded << ++number_of_continuation_bytes) & 0x80) {
          if (number_of_continuation_bytes > 3 || k + 3 >= uri_length) {
            return false;
          }
          if (uri_content->Get(++k) != '%' ||
117 118
              (two_digits = TwoDigitHex(uri_content->Get(k + 1),
                                        uri_content->Get(k + 2))) < 0) {
119 120 121
            return false;
          }
          k += 2;
122
          base::uc16 continuation_byte = static_cast<base::uc16>(two_digits);
123 124 125 126 127 128 129 130 131 132
          octets[number_of_continuation_bytes] = continuation_byte;
        }

        if (!DecodeOctets(octets, number_of_continuation_bytes, buffer)) {
          return false;
        }
      } else {
        AddToBuffer(decoded, uri_content, k - 2, is_uri, buffer);
      }
    } else {
133
      buffer->push_back(code);
134 135 136 137 138 139
    }
  }
  return true;
}

bool IntoOneAndTwoByte(Handle<String> uri, bool is_uri,
140
                       std::vector<uint8_t>* one_byte_buffer,
141
                       std::vector<base::uc16>* two_byte_buffer) {
142
  DisallowGarbageCollection no_gc;
143
  String::FlatContent uri_content = uri->GetFlatContent(no_gc);
144 145 146

  int uri_length = uri->length();
  for (int k = 0; k < uri_length; k++) {
147
    base::uc16 code = uri_content.Get(k);
148
    if (code == '%') {
149
      int two_digits;
150
      if (k + 2 >= uri_length ||
151 152
          (two_digits = TwoDigitHex(uri_content.Get(k + 1),
                                    uri_content.Get(k + 2))) < 0) {
153 154 155
        return false;
      }

156
      base::uc16 decoded = static_cast<base::uc16>(two_digits);
157 158 159 160 161 162 163 164 165 166 167 168
      if (decoded > unibrow::Utf8::kMaxOneByteChar) {
        return IntoTwoByte(k, is_uri, uri_length, &uri_content,
                           two_byte_buffer);
      }

      AddToBuffer(decoded, &uri_content, k, is_uri, one_byte_buffer);
      k += 2;
    } else {
      if (code > unibrow::Utf8::kMaxOneByteChar) {
        return IntoTwoByte(k, is_uri, uri_length, &uri_content,
                           two_byte_buffer);
      }
169
      one_byte_buffer->push_back(code);
170 171 172 173 174 175 176 177 178
    }
  }
  return true;
}

}  // anonymous namespace

MaybeHandle<String> Uri::Decode(Isolate* isolate, Handle<String> uri,
                                bool is_uri) {
179
  uri = String::Flatten(isolate, uri);
180
  std::vector<uint8_t> one_byte_buffer;
181
  std::vector<base::uc16> two_byte_buffer;
182 183 184 185 186

  if (!IntoOneAndTwoByte(uri, is_uri, &one_byte_buffer, &two_byte_buffer)) {
    THROW_NEW_ERROR(isolate, NewURIError(), String);
  }

187
  if (two_byte_buffer.empty()) {
188
    return isolate->factory()->NewStringFromOneByte(base::Vector<const uint8_t>(
189
        one_byte_buffer.data(), static_cast<int>(one_byte_buffer.size())));
190 191 192
  }

  Handle<SeqTwoByteString> result;
193 194
  int result_length =
      static_cast<int>(one_byte_buffer.size() + two_byte_buffer.size());
195
  ASSIGN_RETURN_ON_EXCEPTION(
196
      isolate, result, isolate->factory()->NewRawTwoByteString(result_length),
197 198
      String);

199
  DisallowGarbageCollection no_gc;
200
  base::uc16* chars = result->GetChars(no_gc);
201 202 203 204 205 206 207
  if (!one_byte_buffer.empty()) {
    CopyChars(chars, one_byte_buffer.data(), one_byte_buffer.size());
    chars += one_byte_buffer.size();
  }
  if (!two_byte_buffer.empty()) {
    CopyChars(chars, two_byte_buffer.data(), two_byte_buffer.size());
  }
208 209 210 211

  return result;
}

212
namespace {  // anonymous namespace for EncodeURI helper functions
213
bool IsUnescapePredicateInUriComponent(base::uc16 c) {
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
  if (IsAlphaNumeric(c)) {
    return true;
  }

  switch (c) {
    case '!':
    case '\'':
    case '(':
    case ')':
    case '*':
    case '-':
    case '.':
    case '_':
    case '~':
      return true;
    default:
      return false;
  }
}

234
bool IsUriSeparator(base::uc16 c) {
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
  switch (c) {
    case '#':
    case ':':
    case ';':
    case '/':
    case '?':
    case '$':
    case '&':
    case '+':
    case ',':
    case '@':
    case '=':
      return true;
    default:
      return false;
  }
}

253 254
void AddEncodedOctetToBuffer(uint8_t octet, std::vector<uint8_t>* buffer) {
  buffer->push_back('%');
255 256
  buffer->push_back(base::HexCharOfValue(octet >> 4));
  buffer->push_back(base::HexCharOfValue(octet & 0x0F));
257 258
}

259
void EncodeSingle(base::uc16 c, std::vector<uint8_t>* buffer) {
260
  char s[4] = {};
261 262 263 264
  int number_of_bytes;
  number_of_bytes =
      unibrow::Utf8::Encode(s, c, unibrow::Utf16::kNoPreviousCharacter, false);
  for (int k = 0; k < number_of_bytes; k++) {
265
    AddEncodedOctetToBuffer(s[k], buffer);
266 267 268
  }
}

269
void EncodePair(base::uc16 cc1, base::uc16 cc2, std::vector<uint8_t>* buffer) {
270
  char s[4] = {};
271 272 273 274
  int number_of_bytes =
      unibrow::Utf8::Encode(s, unibrow::Utf16::CombineSurrogatePair(cc1, cc2),
                            unibrow::Utf16::kNoPreviousCharacter, false);
  for (int k = 0; k < number_of_bytes; k++) {
275
    AddEncodedOctetToBuffer(s[k], buffer);
276
  }
277 278 279 280
}

}  // anonymous namespace

281 282
MaybeHandle<String> Uri::Encode(Isolate* isolate, Handle<String> uri,
                                bool is_uri) {
283
  uri = String::Flatten(isolate, uri);
284
  int uri_length = uri->length();
285 286
  std::vector<uint8_t> buffer;
  buffer.reserve(uri_length);
287

288
  bool throw_error = false;
289
  {
290
    DisallowGarbageCollection no_gc;
291
    String::FlatContent uri_content = uri->GetFlatContent(no_gc);
292 293

    for (int k = 0; k < uri_length; k++) {
294
      base::uc16 cc1 = uri_content.Get(k);
295 296 297
      if (unibrow::Utf16::IsLeadSurrogate(cc1)) {
        k++;
        if (k < uri_length) {
298
          base::uc16 cc2 = uri->Get(k);
299 300 301 302 303 304 305 306
          if (unibrow::Utf16::IsTrailSurrogate(cc2)) {
            EncodePair(cc1, cc2, &buffer);
            continue;
          }
        }
      } else if (!unibrow::Utf16::IsTrailSurrogate(cc1)) {
        if (IsUnescapePredicateInUriComponent(cc1) ||
            (is_uri && IsUriSeparator(cc1))) {
307
          buffer.push_back(cc1);
308 309 310 311 312 313
        } else {
          EncodeSingle(cc1, &buffer);
        }
        continue;
      }

314 315 316 317 318
      // String::FlatContent DCHECKs its contents did not change during its
      // lifetime. Throwing the error inside the loop may cause GC and move the
      // string contents.
      throw_error = true;
      break;
319 320 321
    }
  }

322
  if (throw_error) THROW_NEW_ERROR(isolate, NewURIError(), String);
323
  return isolate->factory()->NewStringFromOneByte(base::VectorOf(buffer));
324 325
}

326 327 328
namespace {  // Anonymous namespace for Escape and Unescape

template <typename Char>
329 330
int UnescapeChar(base::Vector<const Char> vector, int i, int length,
                 int* step) {
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
  uint16_t character = vector[i];
  int32_t hi = 0;
  int32_t lo = 0;
  if (character == '%' && i <= length - 6 && vector[i + 1] == 'u' &&
      (hi = TwoDigitHex(vector[i + 2], vector[i + 3])) > -1 &&
      (lo = TwoDigitHex(vector[i + 4], vector[i + 5])) > -1) {
    *step = 6;
    return (hi << 8) + lo;
  } else if (character == '%' && i <= length - 3 &&
             (lo = TwoDigitHex(vector[i + 1], vector[i + 2])) > -1) {
    *step = 3;
    return lo;
  } else {
    *step = 1;
    return character;
  }
}

template <typename Char>
MaybeHandle<String> UnescapeSlow(Isolate* isolate, Handle<String> string,
                                 int start_index) {
  bool one_byte = true;
  int length = string->length();

  int unescaped_length = 0;
  {
357
    DisallowGarbageCollection no_gc;
358
    base::Vector<const Char> vector = string->GetCharVector<Char>(no_gc);
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
    for (int i = start_index; i < length; unescaped_length++) {
      int step;
      if (UnescapeChar(vector, i, length, &step) >
          String::kMaxOneByteCharCode) {
        one_byte = false;
      }
      i += step;
    }
  }

  DCHECK(start_index < length);
  Handle<String> first_part =
      isolate->factory()->NewProperSubString(string, 0, start_index);

  int dest_position = 0;
  Handle<String> second_part;
375
  DCHECK_LE(unescaped_length, String::kMaxLength);
376 377 378 379
  if (one_byte) {
    Handle<SeqOneByteString> dest = isolate->factory()
                                        ->NewRawOneByteString(unescaped_length)
                                        .ToHandleChecked();
380
    DisallowGarbageCollection no_gc;
381
    base::Vector<const Char> vector = string->GetCharVector<Char>(no_gc);
382 383 384 385 386 387 388 389 390 391 392
    for (int i = start_index; i < length; dest_position++) {
      int step;
      dest->SeqOneByteStringSet(dest_position,
                                UnescapeChar(vector, i, length, &step));
      i += step;
    }
    second_part = dest;
  } else {
    Handle<SeqTwoByteString> dest = isolate->factory()
                                        ->NewRawTwoByteString(unescaped_length)
                                        .ToHandleChecked();
393
    DisallowGarbageCollection no_gc;
394
    base::Vector<const Char> vector = string->GetCharVector<Char>(no_gc);
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
    for (int i = start_index; i < length; dest_position++) {
      int step;
      dest->SeqTwoByteStringSet(dest_position,
                                UnescapeChar(vector, i, length, &step));
      i += step;
    }
    second_part = dest;
  }
  return isolate->factory()->NewConsString(first_part, second_part);
}

bool IsNotEscaped(uint16_t c) {
  if (IsAlphaNumeric(c)) {
    return true;
  }
  //  @*_+-./
  switch (c) {
    case '@':
    case '*':
    case '_':
    case '+':
    case '-':
    case '.':
    case '/':
      return true;
    default:
      return false;
  }
}

template <typename Char>
static MaybeHandle<String> UnescapePrivate(Isolate* isolate,
                                           Handle<String> source) {
  int index;
  {
430
    DisallowGarbageCollection no_gc;
431
    StringSearch<uint8_t, Char> search(isolate, base::StaticOneByteVector("%"));
432
    index = search.Search(source->GetCharVector<Char>(no_gc), 0);
433 434 435 436 437 438 439 440 441 442 443 444 445
    if (index < 0) return source;
  }
  return UnescapeSlow<Char>(isolate, source, index);
}

template <typename Char>
static MaybeHandle<String> EscapePrivate(Isolate* isolate,
                                         Handle<String> string) {
  DCHECK(string->IsFlat());
  int escaped_length = 0;
  int length = string->length();

  {
446
    DisallowGarbageCollection no_gc;
447
    base::Vector<const Char> vector = string->GetCharVector<Char>(no_gc);
448 449 450 451 452 453 454 455 456 457 458
    for (int i = 0; i < length; i++) {
      uint16_t c = vector[i];
      if (c >= 256) {
        escaped_length += 6;
      } else if (IsNotEscaped(c)) {
        escaped_length++;
      } else {
        escaped_length += 3;
      }

      // We don't allow strings that are longer than a maximal length.
459
      DCHECK_LT(String::kMaxLength, 0x7FFFFFFF - 6);   // Cannot overflow.
460 461 462 463 464 465 466 467 468 469 470 471 472 473
      if (escaped_length > String::kMaxLength) break;  // Provoke exception.
    }
  }

  // No length change implies no change.  Return original string if no change.
  if (escaped_length == length) return string;

  Handle<SeqOneByteString> dest;
  ASSIGN_RETURN_ON_EXCEPTION(
      isolate, dest, isolate->factory()->NewRawOneByteString(escaped_length),
      String);
  int dest_position = 0;

  {
474
    DisallowGarbageCollection no_gc;
475
    base::Vector<const Char> vector = string->GetCharVector<Char>(no_gc);
476 477 478 479 480
    for (int i = 0; i < length; i++) {
      uint16_t c = vector[i];
      if (c >= 256) {
        dest->SeqOneByteStringSet(dest_position, '%');
        dest->SeqOneByteStringSet(dest_position + 1, 'u');
481 482
        dest->SeqOneByteStringSet(dest_position + 2,
                                  base::HexCharOfValue(c >> 12));
483
        dest->SeqOneByteStringSet(dest_position + 3,
484
                                  base::HexCharOfValue((c >> 8) & 0xF));
485
        dest->SeqOneByteStringSet(dest_position + 4,
486 487 488
                                  base::HexCharOfValue((c >> 4) & 0xF));
        dest->SeqOneByteStringSet(dest_position + 5,
                                  base::HexCharOfValue(c & 0xF));
489 490 491 492 493 494
        dest_position += 6;
      } else if (IsNotEscaped(c)) {
        dest->SeqOneByteStringSet(dest_position, c);
        dest_position++;
      } else {
        dest->SeqOneByteStringSet(dest_position, '%');
495 496 497 498
        dest->SeqOneByteStringSet(dest_position + 1,
                                  base::HexCharOfValue(c >> 4));
        dest->SeqOneByteStringSet(dest_position + 2,
                                  base::HexCharOfValue(c & 0xF));
499 500 501 502 503 504 505 506
        dest_position += 3;
      }
    }
  }

  return dest;
}

507
}  // anonymous namespace
508 509 510

MaybeHandle<String> Uri::Escape(Isolate* isolate, Handle<String> string) {
  Handle<String> result;
511
  string = String::Flatten(isolate, string);
512
  return String::IsOneByteRepresentationUnderneath(*string)
513
             ? EscapePrivate<uint8_t>(isolate, string)
514
             : EscapePrivate<base::uc16>(isolate, string);
515 516 517 518
}

MaybeHandle<String> Uri::Unescape(Isolate* isolate, Handle<String> string) {
  Handle<String> result;
519
  string = String::Flatten(isolate, string);
520
  return String::IsOneByteRepresentationUnderneath(*string)
521
             ? UnescapePrivate<uint8_t>(isolate, string)
522
             : UnescapePrivate<base::uc16>(isolate, string);
523 524
}

525 526
}  // namespace internal
}  // namespace v8