Files
moloapp/src/google/live/ws_url.cpp
T

69 lines
2.2 KiB
C++

#include "google/live/ws_url.h"
#include <cctype>
#include "google/live/caps.h"
#include "google/live/ws_error.h"
namespace molo::google::live {
WsUrl WsUrl::parse(const std::string& url) {
using K = WsError::Kind;
if (url.empty() || url.size() > LiveCaps::kMaxUrlChars)
throw WsError(K::Invalid, "url empty or too long");
for (unsigned char c : url)
if (c <= 0x20 || c == 0x7f)
throw WsError(K::Invalid, "url has control or space characters");
WsUrl out;
std::size_t pos;
if (url.rfind("wss://", 0) == 0) {
out.secure = true;
out.port = 443;
pos = 6;
} else if (url.rfind("ws://", 0) == 0) {
pos = 5;
} else {
throw WsError(K::Invalid, "url scheme must be ws or wss");
}
std::size_t end = url.find_first_of("/?#", pos);
std::string authority =
url.substr(pos, end == std::string::npos ? std::string::npos : end - pos);
if (authority.find('@') != std::string::npos)
throw WsError(K::Invalid, "url must not carry userinfo");
std::size_t colon = authority.rfind(':');
if (colon != std::string::npos) {
std::string p = authority.substr(colon + 1);
authority.resize(colon);
if (p.empty() || p.size() > 5) throw WsError(K::Invalid, "bad port");
int v = 0;
for (char c : p) {
if (!std::isdigit((unsigned char)c)) throw WsError(K::Invalid, "bad port");
v = v * 10 + (c - '0');
}
if (v < 1 || v > 65535) throw WsError(K::Invalid, "port out of range");
out.port = v;
}
if (authority.empty() || authority.size() > 253)
throw WsError(K::Invalid, "bad host");
for (unsigned char c : authority)
if (!(std::isalnum(c) || c == '.' || c == '-' || c == '_'))
throw WsError(K::Invalid, "bad host character");
out.host = authority;
if (end != std::string::npos) {
std::string rest = url.substr(end);
std::size_t hash = rest.find('#');
if (hash != std::string::npos) rest.resize(hash);
if (rest.empty() || rest[0] == '?') rest = "/" + rest;
out.target = rest;
}
return out;
}
std::string WsUrl::display() const {
std::string path = target.substr(0, target.find('?'));
return std::string(secure ? "wss://" : "ws://") + host + ":" +
std::to_string(port) + path;
}
} // namespace molo::google::live