8#include <botan/internal/uri.h>
10#include <botan/assert.h>
11#include <botan/exceptn.h>
12#include <botan/internal/fmt.h>
13#include <botan/internal/parsing.h>
14#include <botan/internal/target_info.h>
16#if defined(BOTAN_TARGET_OS_HAS_SOCKETS)
17 #include <arpa/inet.h>
18 #include <netinet/in.h>
19 #include <sys/socket.h>
20#elif defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
24#if defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
30bool is_domain_name(std::string_view domain) {
39bool is_ipv4(std::string_view ip) {
43bool is_ipv6(std::string_view ip) {
44 std::string ip_str(ip);
45 sockaddr_storage in6addr{};
49 return !!inet_pton(AF_INET6, ip_str.c_str(), &in6addr);
52uint16_t parse_port_number(
const char* func_name, std::string_view uri,
size_t pos) {
53 if(pos == std::string::npos || uri.empty()) {
61 for(
char c : uri.substr(pos + 1)) {
62 size_t digit = c -
'0';
66 port = port * 10 + (c -
'0');
72 return static_cast<uint16_t
>(port);
81 const auto port_pos = uri.find(
':');
82 if(port_pos != std::string::npos) {
83 port = parse_port_number(
"from_domain", uri, port_pos);
85 const auto domain = uri.substr(0, port_pos);
87 throw Invalid_Argument(
"URI::from_domain domain name should not be IP address");
89 if(!is_domain_name(domain)) {
90 throw Invalid_Argument(
fmt(
"URI::from_domain domain name '{}' not valid", domain));
99 const auto port_pos = uri.find(
':');
100 const uint16_t
port = parse_port_number(
"from_ipv4", uri, port_pos);
101 const auto ip = uri.substr(0, port_pos);
103 throw Invalid_Argument(
"URI::from_ipv4: Invalid IPv4 specifier");
111 const auto port_pos = uri.find(
']');
112 const bool with_braces = (port_pos != std::string::npos);
113 if((uri[0] ==
'[') != with_braces) {
114 throw Invalid_Argument(
"URI::from_ipv6 Invalid IPv6 address with mismatch braces");
118 if(with_braces && (uri.size() > port_pos + 1)) {
119 if(uri[port_pos + 1] !=
':') {
120 throw Invalid_Argument(
"URI::from_ipv6 Invalid IPv6 address");
123 port = parse_port_number(
"from_ipv6", uri, port_pos + 1);
125 const auto ip = with_braces ? uri.substr(1, port_pos - 1) : uri.substr(0, port_pos);
128 throw Invalid_Argument(
"URI::from_ipv6 URI has invalid IPv6 address");
138 }
catch(Invalid_Argument&) {}
142 }
catch(Invalid_Argument&) {}
150 return "[" + m_host +
"]:" + std::to_string(m_port);
152 return m_host +
":" + std::to_string(m_port);
#define BOTAN_ARG_CHECK(expr, msg)
static URI from_ipv4(std::string_view uri)
static URI from_domain(std::string_view uri)
static URI from_ipv6(std::string_view uri)
URI(Type type, std::string_view host, uint16_t port)
static URI from_any(std::string_view uri)
std::string to_string() const
std::string fmt(std::string_view format, const T &... args)
std::string check_and_canonicalize_dns_name(std::string_view name)
std::optional< uint32_t > string_to_ipv4(std::string_view str)