url.c++ 15.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
// Copyright (c) 2017 Cloudflare, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#include "url.h"
#include <kj/encoding.h>
#include <kj/parse/char.h>
#include <kj/debug.h>
#include <stdlib.h>

namespace kj {

namespace {

constexpr auto ALPHAS = parse::charRange('a', 'z').orRange('A', 'Z');
constexpr auto DIGITS = parse::charRange('0', '9');
34

35
constexpr auto END_AUTHORITY = parse::anyOfChars("/?#");
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67

// Authority, path, and query components can typically be terminated by the start of a fragment.
// However, fragments are disallowed in HTTP_REQUEST and HTTP_PROXY_REQUEST contexts. As a quirk, we
// allow the fragment start character ('#') to live unescaped in path and query components. We do
// not currently allow it in the authority component, because our parser would reject it as a host
// character anyway.

const parse::CharGroup_& getEndPathPart(Url::Context context) {
  static constexpr auto END_PATH_PART_HREF = parse::anyOfChars("/?#");
  static constexpr auto END_PATH_PART_REQUEST = parse::anyOfChars("/?");

  switch (context) {
    case Url::REMOTE_HREF:        return END_PATH_PART_HREF;
    case Url::HTTP_PROXY_REQUEST: return END_PATH_PART_REQUEST;
    case Url::HTTP_REQUEST:       return END_PATH_PART_REQUEST;
  }

  KJ_UNREACHABLE;
}

const parse::CharGroup_& getEndQueryPart(Url::Context context) {
  static constexpr auto END_QUERY_PART_HREF = parse::anyOfChars("&#");
  static constexpr auto END_QUERY_PART_REQUEST = parse::anyOfChars("&");

  switch (context) {
    case Url::REMOTE_HREF:        return END_QUERY_PART_HREF;
    case Url::HTTP_PROXY_REQUEST: return END_QUERY_PART_REQUEST;
    case Url::HTTP_REQUEST:       return END_QUERY_PART_REQUEST;
  }

  KJ_UNREACHABLE;
}
68 69 70 71

constexpr auto SCHEME_CHARS = ALPHAS.orGroup(DIGITS).orAny("+-.");
constexpr auto NOT_SCHEME_CHARS = SCHEME_CHARS.invert();

72 73 74
constexpr auto HOST_CHARS = ALPHAS.orGroup(DIGITS).orAny(".-:[]_");
// [] is for ipv6 literals.
// _ is not allowed in domain names, but the WHATWG URL spec allows it in hostnames, so we do, too.
75 76
// TODO(someday): The URL spec actually allows a lot more than just '_', and requires nameprepping
//   to Punycode. We'll have to decide how we want to deal with all that.
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

void toLower(String& text) {
  for (char& c: text) {
    if ('A' <= c && c <= 'Z') {
      c += 'a' - 'A';
    }
  }
}

Maybe<ArrayPtr<const char>> trySplit(StringPtr& text, char c) {
  KJ_IF_MAYBE(pos, text.findFirst(c)) {
    ArrayPtr<const char> result = text.slice(0, *pos);
    text = text.slice(*pos + 1);
    return result;
  } else {
    return nullptr;
  }
}

Maybe<ArrayPtr<const char>> trySplit(ArrayPtr<const char>& text, char c) {
  for (auto i: kj::indices(text)) {
    if (text[i] == c) {
      ArrayPtr<const char> result = text.slice(0, i);
      text = text.slice(i + 1, text.size());
      return result;
    }
  }
  return nullptr;
}

ArrayPtr<const char> split(StringPtr& text, const parse::CharGroup_& chars) {
  for (auto i: kj::indices(text)) {
    if (chars.contains(text[i])) {
      ArrayPtr<const char> result = text.slice(0, i);
      text = text.slice(i);
      return result;
    }
  }
  auto result = text.asArray();
  text = "";
  return result;
}

120 121 122 123 124 125 126
String percentDecode(ArrayPtr<const char> text, bool& hadErrors, const Url::Options& options) {
  if (options.percentDecode) {
    auto result = decodeUriComponent(text);
    if (result.hadErrors) hadErrors = true;
    return kj::mv(result);
  }
  return kj::str(text);
127 128
}

129 130 131 132 133 134 135
String percentDecodeQuery(ArrayPtr<const char> text, bool& hadErrors, const Url::Options& options) {
  if (options.percentDecode) {
    auto result = decodeWwwForm(text);
    if (result.hadErrors) hadErrors = true;
    return kj::mv(result);
  }
  return kj::str(text);
136 137
}

138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
}  // namespace

Url::~Url() noexcept(false) {}

Url Url::clone() const {
  return {
    kj::str(scheme),
    userInfo.map([](const UserInfo& ui) -> UserInfo {
      return {
        kj::str(ui.username),
        ui.password.map([](const String& s) { return kj::str(s); })
      };
    }),
    kj::str(host),
    KJ_MAP(part, path) { return kj::str(part); },
    hasTrailingSlash,
    KJ_MAP(param, query) -> QueryParam {
155 156 157
      // Preserve the "allocated-ness" of `param.value` with this careful copy.
      return { kj::str(param.name), param.value.begin() == nullptr ? kj::String()
                                                                   : kj::str(param.value) };
158
    },
159 160
    fragment.map([](const String& s) { return kj::str(s); }),
    options
161 162 163
  };
}

164 165
Url Url::parse(StringPtr url, Context context, Options options) {
  return KJ_REQUIRE_NONNULL(tryParse(url, context, options), "invalid URL", url);
166 167
}

168
Maybe<Url> Url::tryParse(StringPtr text, Context context, Options options) {
169
  Url result;
170
  result.options = options;
171 172
  bool err = false;  // tracks percent-decoding errors

173 174 175
  auto& END_PATH_PART = getEndPathPart(context);
  auto& END_QUERY_PART = getEndQueryPart(context);

176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
  if (context == HTTP_REQUEST) {
    if (!text.startsWith("/")) {
      return nullptr;
    }
  } else {
    KJ_IF_MAYBE(scheme, trySplit(text, ':')) {
      result.scheme = kj::str(*scheme);
    } else {
      // missing scheme
      return nullptr;
    }
    toLower(result.scheme);
    if (result.scheme.size() == 0 ||
        !ALPHAS.contains(result.scheme[0]) ||
        !SCHEME_CHARS.containsAll(result.scheme.slice(1))) {
      // bad scheme
      return nullptr;
    }

    if (!text.startsWith("//")) {
      // We require an authority (hostname) part.
      return nullptr;
    }
    text = text.slice(2);

    {
      auto authority = split(text, END_AUTHORITY);

      KJ_IF_MAYBE(userpass, trySplit(authority, '@')) {
205
        if (context != REMOTE_HREF) {
206 207 208 209 210
          // No user/pass allowed here.
          return nullptr;
        }
        KJ_IF_MAYBE(username, trySplit(*userpass, ':')) {
          result.userInfo = UserInfo {
211 212
            percentDecode(*username, err, options),
            percentDecode(*userpass, err, options)
213 214 215
          };
        } else {
          result.userInfo = UserInfo {
216
            percentDecode(*userpass, err, options),
217 218 219 220 221
            nullptr
          };
        }
      }

222
      result.host = percentDecode(authority, err, options);
223 224 225 226 227
      if (!HOST_CHARS.containsAll(result.host)) return nullptr;
      toLower(result.host);
    }
  }

228 229 230 231 232 233
  while (text.startsWith("/")) {
    text = text.slice(1);
    auto part = split(text, END_PATH_PART);
    if (part.size() == 2 && part[0] == '.' && part[1] == '.') {
      if (result.path.size() != 0) {
        result.path.removeLast();
234
      }
235 236 237 238 239
      result.hasTrailingSlash = true;
    } else if (part.size() == 0 || (part.size() == 1 && part[0] == '.')) {
      // Collapse consecutive slashes and "/./".
      result.hasTrailingSlash = true;
    } else {
240
      result.path.add(percentDecode(part, err, options));
241
      result.hasTrailingSlash = false;
242 243 244 245 246 247 248 249 250 251
    }
  }

  if (text.startsWith("?")) {
    do {
      text = text.slice(1);
      auto part = split(text, END_QUERY_PART);

      if (part.size() > 0) {
        KJ_IF_MAYBE(key, trySplit(part, '=')) {
252 253
          result.query.add(QueryParam { percentDecodeQuery(*key, err, options),
                                        percentDecodeQuery(part, err, options) });
254
        } else {
255
          result.query.add(QueryParam { percentDecodeQuery(part, err, options), nullptr });
256 257 258 259 260 261
        }
      }
    } while (text.startsWith("&"));
  }

  if (text.startsWith("#")) {
262
    if (context != REMOTE_HREF) {
263 264 265
      // No fragment allowed here.
      return nullptr;
    }
266
    result.fragment = percentDecode(text.slice(1), err, options);
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
  } else {
    // We should have consumed everything.
    KJ_ASSERT(text.size() == 0);
  }

  if (err) return nullptr;

  return kj::mv(result);
}

Url Url::parseRelative(StringPtr url) const {
  return KJ_REQUIRE_NONNULL(tryParseRelative(url), "invalid relative URL", url);
}

Maybe<Url> Url::tryParseRelative(StringPtr text) const {
  if (text.size() == 0) return clone();

  Url result;
285
  result.options = options;
286 287
  bool err = false;  // tracks percent-decoding errors

288 289 290
  auto& END_PATH_PART = getEndPathPart(Url::REMOTE_HREF);
  auto& END_QUERY_PART = getEndQueryPart(Url::REMOTE_HREF);

291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
  // scheme
  {
    bool gotScheme = false;
    for (auto i: kj::indices(text)) {
      if (text[i] == ':') {
        // found valid scheme
        result.scheme = kj::str(text.slice(0, i));
        text = text.slice(i + 1);
        gotScheme = true;
        break;
      } else if (NOT_SCHEME_CHARS.contains(text[i])) {
        // no scheme
        break;
      }
    }
    if (!gotScheme) {
      // copy scheme
      result.scheme = kj::str(this->scheme);
    }
  }

  // authority
  bool hadNewAuthority = text.startsWith("//");
  if (hadNewAuthority) {
    text = text.slice(2);

    auto authority = split(text, END_AUTHORITY);

    KJ_IF_MAYBE(userpass, trySplit(authority, '@')) {
      KJ_IF_MAYBE(username, trySplit(*userpass, ':')) {
        result.userInfo = UserInfo {
322 323
          percentDecode(*username, err, options),
          percentDecode(*userpass, err, options)
324 325 326
        };
      } else {
        result.userInfo = UserInfo {
327
          percentDecode(*userpass, err, options),
328 329 330 331 332
          nullptr
        };
      }
    }

333
    result.host = percentDecode(authority, err, options);
334 335
    if (!HOST_CHARS.containsAll(result.host)) return nullptr;
    toLower(result.host);
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
  } else {
    // copy authority
    result.host = kj::str(this->host);
    result.userInfo = this->userInfo.map([](const UserInfo& userInfo) {
      return UserInfo {
        kj::str(userInfo.username),
        userInfo.password.map([](const String& password) { return kj::str(password); }),
      };
    });
  }

  // path
  bool hadNewPath = text.size() > 0 && text[0] != '?' && text[0] != '#';
  if (hadNewPath) {
    // There's a new path.

    if (text[0] == '/') {
      // New path is absolute, so don't copy the old path.
      text = text.slice(1);
      result.hasTrailingSlash = true;
    } else if (this->path.size() > 0) {
      // New path is relative, so start from the old path, dropping everything after the last
      // slash.
      auto slice = this->path.slice(0, this->path.size() - (this->hasTrailingSlash ? 0 : 1));
360
      result.path = KJ_MAP(part, slice) { return kj::str(part); };
361 362 363 364 365 366
      result.hasTrailingSlash = true;
    }

    for (;;) {
      auto part = split(text, END_PATH_PART);
      if (part.size() == 2 && part[0] == '.' && part[1] == '.') {
367
        if (result.path.size() != 0) {
368
          result.path.removeLast();
369 370 371 372 373 374
        }
        result.hasTrailingSlash = true;
      } else if (part.size() == 0 || (part.size() == 1 && part[0] == '.')) {
        // Collapse consecutive slashes and "/./".
        result.hasTrailingSlash = true;
      } else {
375
        result.path.add(percentDecode(part, err, options));
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
        result.hasTrailingSlash = false;
      }

      if (!text.startsWith("/")) break;
      text = text.slice(1);
    }
  } else if (!hadNewAuthority) {
    // copy path
    result.path = KJ_MAP(part, this->path) { return kj::str(part); };
    result.hasTrailingSlash = this->hasTrailingSlash;
  }

  if (text.startsWith("?")) {
    do {
      text = text.slice(1);
      auto part = split(text, END_QUERY_PART);

      if (part.size() > 0) {
        KJ_IF_MAYBE(key, trySplit(part, '=')) {
395 396
          result.query.add(QueryParam { percentDecodeQuery(*key, err, options),
                                        percentDecodeQuery(part, err, options) });
397
        } else {
398 399
          result.query.add(QueryParam { percentDecodeQuery(part, err, options),
                                        nullptr });
400 401 402 403 404
        }
      }
    } while (text.startsWith("&"));
  } else if (!hadNewAuthority && !hadNewPath) {
    // copy query
405 406 407 408
    result.query = KJ_MAP(param, this->query) -> QueryParam {
      // Preserve the "allocated-ness" of `param.value` with this careful copy.
      return { kj::str(param.name), param.value.begin() == nullptr ? kj::String()
                                                                   : kj::str(param.value) };
409 410 411 412
    };
  }

  if (text.startsWith("#")) {
413
    result.fragment = percentDecode(text.slice(1), err, options);
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
  } else {
    // We should have consumed everything.
    KJ_ASSERT(text.size() == 0);
  }

  if (err) return nullptr;

  return kj::mv(result);
}

String Url::toString(Context context) const {
  Vector<char> chars(128);

  if (context != HTTP_REQUEST) {
    chars.addAll(scheme);
    chars.addAll(StringPtr("://"));

431
    if (context == REMOTE_HREF) {
432
      KJ_IF_MAYBE(user, userInfo) {
433 434
        chars.addAll(options.percentDecode ? encodeUriUserInfo(user->username)
                                          : kj::str(user->username));
435 436
        KJ_IF_MAYBE(pass, user->password) {
          chars.add(':');
437
          chars.addAll(options.percentDecode ? encodeUriUserInfo(*pass) : kj::str(*pass));
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
        }
        chars.add('@');
      }
    }

    // RFC3986 specifies that hosts can contain percent-encoding escapes while suggesting that
    // they should only be used for UTF-8 sequences. However, the DNS standard specifies a
    // different way to encode Unicode into domain names and doesn't permit any characters which
    // would need to be escaped. Meanwhile, encodeUriComponent() here would incorrectly try to
    // escape colons and brackets (e.g. around ipv6 literal addresses). So, instead, we throw if
    // the host is invalid.
    if (HOST_CHARS.containsAll(host)) {
      chars.addAll(host);
    } else {
      KJ_FAIL_REQUIRE("invalid hostname when stringifying URL", host) {
        chars.addAll(StringPtr("invalid-host"));
        break;
      }
    }
  }

  for (auto& pathPart: path) {
460 461 462 463 464
    // Protect against path injection.
    KJ_REQUIRE(pathPart != "" && pathPart != "." && pathPart != "..",
               "invalid name in URL path", *this) {
      continue;
    }
465
    chars.add('/');
466
    chars.addAll(options.percentDecode ? encodeUriPath(pathPart) : kj::str(pathPart));
467 468 469 470 471 472 473 474 475
  }
  if (hasTrailingSlash || (path.size() == 0 && context == HTTP_REQUEST)) {
    chars.add('/');
  }

  bool first = true;
  for (auto& param: query) {
    chars.add(first ? '?' : '&');
    first = false;
476
    chars.addAll(options.percentDecode ? encodeWwwForm(param.name) : kj::str(param.name));
477
    if (param.value.begin() != nullptr) {
478
      chars.add('=');
479
      chars.addAll(options.percentDecode ? encodeWwwForm(param.value) : kj::str(param.value));
480 481 482
    }
  }

483
  if (context == REMOTE_HREF) {
484 485
    KJ_IF_MAYBE(f, fragment) {
      chars.add('#');
486
      chars.addAll(options.percentDecode ? encodeUriFragment(*f) : kj::str(*f));
487 488 489 490 491 492 493 494
    }
  }

  chars.add('\0');
  return String(chars.releaseAsArray());
}

} // namespace kj