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) {
47uint16_t parse_port_number(
const char* func_name, std::string_view uri,
size_t pos) {
48 if(pos == std::string::npos || uri.empty()) {
56 for(
const char c : uri.substr(pos + 1)) {
57 const size_t digit = c -
'0';
61 port = port * 10 + (c -
'0');
67 return static_cast<uint16_t
>(port);
76 const auto port_pos = uri.find(
':');
77 if(port_pos != std::string::npos) {
78 port = parse_port_number(
"from_domain", uri, port_pos);
80 const auto domain = uri.substr(0, port_pos);
82 throw Invalid_Argument(
"URI::from_domain domain name should not be IP address");
84 if(!is_domain_name(domain)) {
85 throw Invalid_Argument(
fmt(
"URI::from_domain domain name '{}' not valid", domain));
94 const auto port_pos = uri.find(
':');
95 const uint16_t
port = parse_port_number(
"from_ipv4", uri, port_pos);
96 const auto ip = uri.substr(0, port_pos);
98 throw Invalid_Argument(
"URI::from_ipv4: Invalid IPv4 specifier");
106 const auto port_pos = uri.find(
']');
107 const bool with_braces = (port_pos != std::string::npos);
108 if((uri[0] ==
'[') != with_braces) {
109 throw Invalid_Argument(
"URI::from_ipv6 Invalid IPv6 address with mismatch braces");
113 if(with_braces && (uri.size() > port_pos + 1)) {
114 if(uri[port_pos + 1] !=
':') {
115 throw Invalid_Argument(
"URI::from_ipv6 Invalid IPv6 address");
118 port = parse_port_number(
"from_ipv6", uri, port_pos + 1);
120 const auto ip = with_braces ? uri.substr(1, port_pos - 1) : uri.substr(0, port_pos);
123 throw Invalid_Argument(
"URI::from_ipv6 URI has invalid IPv6 address");
133 }
catch(Invalid_Argument&) {}
137 }
catch(Invalid_Argument&) {}
145 return "[" + m_host +
"]:" + std::to_string(m_port);
147 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< std::array< uint8_t, 16 > > string_to_ipv6(std::string_view str)
std::optional< uint32_t > string_to_ipv4(std::string_view str)