lokinet/llarp/quic/address.hpp

128 lines
2.4 KiB
C++
Raw Normal View History

2021-03-10 15:11:42 +00:00
#pragma once
#include <array>
#include <cassert>
#include <cstring>
#include <memory>
2021-03-10 15:11:42 +00:00
#include <string>
#include <iosfwd>
#include <ngtcp2/ngtcp2.h>
#include <llarp/net/sock_addr.hpp>
#include <llarp/service/convotag.hpp>
2021-03-10 15:11:42 +00:00
namespace llarp::quic
{
union sockaddr_any
{
sockaddr_storage storage;
sockaddr sa;
sockaddr_in6 in6;
sockaddr_in in;
};
class Address
{
sockaddr_in6 saddr{};
ngtcp2_addr a{0, reinterpret_cast<sockaddr*>(&saddr), nullptr};
2021-03-10 15:11:42 +00:00
public:
Address() = default;
Address(service::ConvoTag tag);
Address(const Address& other)
2021-03-10 15:11:42 +00:00
{
*this = other;
2021-03-10 15:11:42 +00:00
}
service::ConvoTag
Tag() const;
2021-03-10 15:11:42 +00:00
Address&
operator=(const Address&);
2021-03-10 15:11:42 +00:00
operator sockaddr*()
{
return reinterpret_cast<sockaddr*>(&saddr);
2021-03-10 15:11:42 +00:00
}
2021-03-10 15:11:42 +00:00
operator const sockaddr*() const
{
return reinterpret_cast<const sockaddr*>(&saddr);
2021-03-10 15:11:42 +00:00
}
2021-03-10 15:11:42 +00:00
operator ngtcp2_addr&()
{
return a;
}
2021-03-10 15:11:42 +00:00
operator const ngtcp2_addr&() const
{
return a;
}
size_t
sockaddr_size() const
{
return sizeof(sockaddr_in6);
}
2021-03-10 15:11:42 +00:00
std::string
to_string() const;
};
// Wraps an ngtcp2_path (which is basically just and address pair) with remote/local components.
// Implicitly convertable to a ngtcp2_path* so that this can be passed wherever a ngtcp2_path* is
// taken in the ngtcp2 API.
struct Path
{
private:
Address local_, remote_;
2021-03-10 15:11:42 +00:00
public:
ngtcp2_path path{
{local_.sockaddr_size(), local_, nullptr}, {remote_.sockaddr_size(), remote_, nullptr}};
// Public accessors are const:
const Address& local = local_;
const Address& remote = remote_;
Path() = default;
Path(const Address& laddr, const Address& raddr) : local_{laddr}, remote_{raddr}
2021-03-10 15:11:42 +00:00
{}
Path(const Path& p) : Path{p.local, p.remote}
2021-03-10 15:11:42 +00:00
{}
Path&
operator=(const Path& p)
{
local_ = p.local_;
remote_ = p.remote_;
return *this;
}
// Equivalent to `&obj.path`, but slightly more convenient for passing into ngtcp2 functions
// taking a ngtcp2_path pointer.
operator ngtcp2_path*()
{
return &path;
}
operator const ngtcp2_path*() const
{
return &path;
}
std::string
to_string() const;
};
std::ostream&
operator<<(std::ostream& o, const Address& a);
2021-03-10 15:11:42 +00:00
std::ostream&
operator<<(std::ostream& o, const Path& p);
} // namespace llarp::quic