8a00ed6071
* Add KKT cryptographic primitives Post-quantum Key Encapsulation Mechanism (KEM) Key Transfer protocol. Enables efficient distribution of post-quantum KEM public keys. Squashed from georgio/noise-psq branch. * Implement LP registration protocol with KKT/PSQ integration Initial implementation of the Lewes Protocol (LP) for gateway registration: - Add nym-lp crate with Noise protocol handshake - Add LP listener to gateway for handling registrations - Add LP client for registration flow - Integrate KKT for post-quantum KEM key exchange - Integrate PSQ for post-quantum PSK derivation - Add Ed25519 authentication throughout - Add docker/localnet support for testing Co-authored-by: Jędrzej Stuczyński <jedrzej.stuczynski@gmail.com> * Add LP telescoping with nested sessions and subsession support Extends LP protocol with telescoping architecture for nested sessions: - Add nested session support with KKpsk0 rekeying - Add subsession support with collision detection - Implement unified packet format with outer header - Refactor gateway handlers for single-packet forwarding - Add TTL-based state cleanup for stale sessions - Add outer AEAD encryption layer - Refactor registration client for packet-per-connection model * Add gateway-probe localnet mode with WireGuard tunnel support Adds localnet testing mode to gateway-probe for LP development: - Add TestMode enum for different probe configurations - Add --gateway-ip flag for direct gateway testing - Implement two-hop WireGuard tunnel for localnet - Add mock ecash support for testing without real credentials - Add netstack Go bindings for userspace networking - Restructure probe with mode and common modules - Update README with localnet mode documentation * Increase KCP fragment limit from u8 to u16 - Change frg field from u8 to u16 in packet header (25 bytes total) - Update encode/decode to use get_u16_le/put_u16_le - Update Segment struct frg field to u16 - Remove truncating cast in session.rs - Max message size now ~91MB (65,535 fragments × MTU) - Internal protocol only, no interop concerns Nym uses KCP for reliability and multiplexing, not standard real-time use cases. The u8 limit (255 fragments, ~355KB) was insufficient. Addresses: nym-yih9 * Zeroize Ed25519 key material in to_x25519 conversion Wrap hash and x25519_bytes in zeroize::Zeroizing to ensure private key material is cleared from memory after use. Closes: nym-k55g * Return Result from KCP session input() for error detection Change KcpSession::input() to return Result<(), KcpError> so callers can detect invalid packets instead of silently ignoring them. - Add ConvMismatch error variant for conversation ID mismatches - Update driver to propagate errors from session.input() - Update all test and example callers Closes: nym-n0kk * Fix Zeroizing deref in ed25519 to_x25519 conversion The from_bytes() function expects &[u8], need to deref the Zeroizing wrapper to get the inner array. * Add semaphore-based connection limiting for LP packet forwarding Limits concurrent outbound connections when forwarding LP packets to prevent file descriptor exhaustion under high load. Key changes: - Add max_concurrent_forwards config (default 1000) - Add forward_semaphore to LpHandlerState - Acquire semaphore permit before connecting in handle_forward_packet - Return "Gateway at forward capacity" error when at limit This provides load signaling so clients can choose another gateway when the current one is overloaded. Design note: Connection pooling was considered but provides minimal benefit since telescope setup is one-time and targets are distributed across many different gateways. See AIDEV-NOTE in LpHandlerState for full analysis. Closes: nym-xi3m * Return error on session unavailable in handle_subsession_packet Replace .session().ok() with proper error handling to fail fast when session is Closed or Processing after state machine processing. Previously, the code silently continued with outer_key = None, which could cause protocol errors downstream. Closes: nym-8de0 * Use explicit bincode Options helper in nested_session Add bincode_options() helper that returns DefaultOptions with explicit big_endian and varint_encoding configuration. This future-proofs against bincode 1.x/2.x default changes and makes serialization format explicit. Updated all 4 bincode usages in nested_session.rs to use the helper. * Deduplicate outer_key lookup pattern in nested_session.rs Extract common state_machine.session().ok().and_then(...) pattern into two helper methods: - get_send_key() for encryption (outer_aead_key_for_sending) - get_recv_key() for decryption (outer_aead_key) Updated 6 call sites to use the helpers, reducing verbosity. * Add LpConfig struct and AIDEV-NOTE documentation for KKT+PSQ - Create config.rs with LpConfig struct (kem_algorithm, psk_ttl, enable_kkt) - Export LpConfig from lib.rs - Add AIDEV-NOTE to psk.rs explaining: - Why PSQ is embedded in Noise (single round-trip, PSK binding) - KEM migration path (X25519 → MlKem768 → XWing) - Add AIDEV-NOTE to state_machine.rs explaining protocol flow: - KKTExchange → Handshaking → Transport state transitions - PSK derivation formula (ECDH || PSQ || salt) * Add forward_timeout to LP client config Add forward_timeout (30s default) to LpConfig and wrap send_forward_packet's connect_send_receive call with tokio::time::timeout, matching the pattern used by register() with registration_timeout. This prevents indefinite hangs when forwarding packets through entry gateway. * Add negotiated_version field to LpSession Add AtomicU8 field to store the protocol version from handshake packet headers. Includes getter and setter methods for future version negotiation and compatibility checks. - negotiated_version() returns current version (defaults to 1) - set_negotiated_version() allows setting during handshake - Subsessions inherit version 1 (can be enhanced to inherit parent's) * Change MessageType from u16 to u32 Breaking wire protocol change: MessageType field increased from 2 bytes to 4 bytes in LP packets. This future-proofs the message type space and aligns with other u32 fields. Changes: - message.rs: #[repr(u32)], from_u32(), to_u32() - error.rs: InvalidMessageType(u32) - codec.rs: All serialization/deserialization updated to 4-byte msg_type - Cleartext parsing: inner_bytes[4..8], content at [8..] - AEAD parsing: decrypted[4..8], content at [8..] - Serialization: 4 bytes for message type * Various smaller fixes * Refactor LP to stream-oriented TCP processing Gateway (handler.rs): - Add bound_receiver_idx field for session-affine connections - Convert handle() from single-packet to loop with EOF detection - Add validate_or_set_binding() for receiver_idx validation - Set binding in handle_client_hello after collision check - Centralize emit_lifecycle_metrics in main loop only - Add is_connection_closed() helper for graceful EOF Client (client.rs): - Add stream field for persistent TCP connection - Add ensure_connected(), send_packet(), receive_packet(), close() methods - Modify perform_handshake_inner() to use persistent stream - Modify register_with_credential() to use persistent stream - Modify send_forward_packet() to use persistent stream - Keep connect_send_receive() for reference (marked dead_code) This reduces handshake overhead from ~5 TCP connections to 1. Drive-by: Fix log::info! -> info! in wireguard peer_controller.rs * Add persistent exit stream for entry→exit forwarding Entry gateway now maintains a persistent TCP connection to the exit gateway per client session, reusing it for all forward requests from that client. This reduces TCP handshake overhead significantly. Key changes: - Add exit_stream: Option<(TcpStream, SocketAddr)> to LpConnectionHandler - Modify handle_forward_packet() to open on first forward, reuse after - Clear exit_stream on connection errors (auto-reconnect on next forward) - Semaphore only acquired for connection opens, not reuse (sequential access) * Fix code review issues for stream-oriented LP - Add 30s timeout to exit stream I/O operations (nym-df31) Prevents handler from hanging on unresponsive exit gateway - Return error on forward target address mismatch (nym-zegu) Previously warned and proceeded, which could mask bugs - Close client stream on handshake error paths (nym-scvm) Prevents state machine inconsistency on timeout or failure * Add LP registration idempotency and retry logic Make LP registration resilient to network failures that could waste credentials. When registration succeeds on the gateway but the response is lost (e.g., network drop), clients can retry with the same WG key and get the cached result instead of spending another credential. Gateway-side: - Add check_existing_registration() helper that looks up WG peer and returns cached GatewayData if already registered - Add idempotency check in process_registration() dVPN branch - Only return cached response if bandwidth > 0 (ensures registration was actually completed, not just peer created) - Track idempotent registrations with lp_registration_dvpn_idempotent metric Client-side: - Add register_with_retry() to LpRegistrationClient that acquires credential once and retries handshake+registration on failure - Add handshake_and_register_with_retry() to NestedLpSession for exit gateway registration via forwarding - Add exponential backoff with jitter between retry attempts - Verify outer session validity before nested session retry Both retry methods clear state machine before retry to ensure fresh handshake, and reuse the same credential across all attempts. * Add no-mix-acks feature flag to nym-sphinx-framing When enabled, mix nodes skip ack extraction and forwarding entirely. The full payload (including ack portion) is returned as the message. Closes: nym-3wrr * Create nym-lp-speedtest crate scaffold - Created tools/nym-lp-speedtest/ with Cargo.toml - Added main.rs with CLI argument parsing - Created stub modules: client.rs, speedtest.rs, topology.rs - Added to workspace members - Verified compilation with cargo check * Implement topology fetching for nym-lp-speedtest - Add topology.rs with NymTopology integration - Fetch mix nodes and gateways from nym-api - Build GatewayInfo with LP addresses (port 41264) - Provide random_route_to_gateway() for Sphinx routing - Add required Cargo.toml dependencies * Implement LP+Sphinx+KCP client with SURB support - Add send_data() and send_data_with_surbs() methods for mixnet data - Integrate KCP reliable delivery with Sphinx packet construction - Add x25519 encryption keypair for SURB reply mechanism - Wire up main.rs to test LP handshake and data path - Add NymRouteProvider support in topology for SURB construction - Refactor send_data() to delegate to send_data_with_surbs(0) (DRY) The client can now: - Perform LP handshake with gateways - Send data through the mixnet wrapped in KCP + Sphinx packets - Attach SURBs for bidirectional communication - Return encryption keys for decrypting replies * Rename nym-lp-speedtest to nym-lp-client and fix KCP bug - Rename crate from nym-lp-speedtest to nym-lp-client - Fix KCP bug: add driver.update() call before fetch_outgoing() Without update(), KCP never moves segments from snd_queue to snd_buf - Update CLI name, about string, and user agent to match new name * Add LP mixnet mode registration with nym address return - Extend RegistrationMode::Mixnet to include client_ed25519_pubkey and client_x25519_pubkey for nym address construction - Add LpGatewayData struct containing gateway_identity and gateway_sphinx_key for SURB reply routing - Add lp_gateway_data field to LpRegistrationResponse for mixnet mode - Implement success_mixnet() constructor for mixnet registrations - Update gateway registration to insert clients into ActiveClientsStore for SURB reply delivery, matching the websocket flow * Implement LP data handler on UDP:51264 - Add LpDataHandler for UDP data plane (port 51264) - Decrypt LP layer and forward Sphinx packets to mixnet - Add outbound_mix_sender to LpHandlerState - Integrate data handler spawn into LpListener::run() - Add metrics for data packets received/forwarded/errors Implements nym-yzzm * Fix replay protection vulnerability in LP data handler Use state machine process_input() instead of manual decryption to ensure proper replay protection: - Counter check against receiving window - Counter marking after successful decryption Also handle subsession actions gracefully (SendPacket ignored on UDP, clients should use TCP control plane for rekeying). Security fix for nym-yzzm implementation. * feat(ipr): add KcpSessionManager for LP client KCP handling - Add fetch_incoming() and recv() methods to KcpDriver for retrieving reassembled messages - Create KcpSessionManager in ip-packet-router that manages KCP sessions keyed by conv_id (first 4 bytes of KCP packet header) - Store ReplySurbs per session for sending anonymous replies - Implement session timeout (5 min) and max sessions limit (10000) - Add comprehensive tests for session lifecycle and KCP roundtrip * feat(ipr): integrate KcpSessionManager into MixnetListener - Add KcpSessionManager field to MixnetListener struct - Add is_kcp_message() helper to detect KCP-wrapped payloads - Add on_kcp_message() to process LP client KCP messages - Refactor on_reconstructed_message() to route KCP vs regular IPR - Add KCP tick timer (100ms) for session updates and cleanup - Initialize KcpSessionManager in IpPacketRouter::run_service_provider() KCP messages are detected by checking byte 4 for valid KCP commands (81-84), which doesn't conflict with IPR protocol version bytes (6-8) at position 0. Closes: nym-96zl * fix(ipr): prevent KCP detection false positives on IPR messages Add secondary check in is_kcp_message() to exclude messages that match IPR protocol header pattern (version 6-8 at byte 0, ServiceProviderType 0-2 at byte 1). This prevents false positives where IPR messages with byte 4 in range 81-84 would be incorrectly routed to KCP processing. Added 4 unit tests to validate the detection logic. Closes: nym-6f3x * fix(ipr): wrap KCP client responses in KCP before SURB reply - Modify on_kcp_message to handle responses directly instead of returning them - Add handle_kcp_response method that wraps response in KCP and sends via mixnet - Ensures KCP clients receive KCP-wrapped responses for proper reassembly Closes: nym-7oh2 * fix(ipr): send KCP protocol packets in tick instead of just logging - Add get_sender_tag() and fetch_outgoing_for_conv() to KcpSessionManager - Change handle_kcp_tick() to actually send ACKs/retransmissions via mixnet - Reduce KCP tick interval from 100ms to 10ms for better responsiveness This fixes the KCP reliability protocol which was broken because protocol packets (ACKs, retransmissions) were generated but never sent. * feat(lp-client): wrap payload in IpPacketRequest before KCP - Add nym-ip-packet-requests and bytes dependencies - Wrap payload in IpPacketRequest::new_data_request() before sending to KCP - Add LP_DATA_PORT constant (51264) and lp_data_address field to GatewayInfo This ensures IPR can properly parse incoming messages as DataRequest. LP framing (wrapping Sphinx in LP before sending) is a separate task. * feat(lp-client): add LP session management and UDP data plane support - Add wrap_data() and session_id() to LpRegistrationClient for LP packet creation after handshake - Add init_lp_session() and close_lp_session() to SpeedtestClient for managing LP sessions - Extract prepare_sphinx_fragments() helper to reduce code duplication between send_data_with_surbs() and send_data_via_lp() - Add send_data_via_lp() for sending Sphinx packets through LP's UDP data plane (port 51264) The LP session is kept alive after TCP handshake closes, allowing subsequent wrap_data() calls for UDP transmission without re-handshaking. * random formatting * replaced all instances of bincode::serialize and bincode::deserialize with explicit lp_bincode_serialiser() within the LP * additional formatting * removed source of possible panic from nym-kkt invalid KEM mapping will now return an Err rather than panicking * integration test for LP entry registration This includes creation of mocks of various gateway-related components, such as the PeerController * changed ClientHelloData serialisation the old variant using bincode did not produce constant-length output in some cases * Fixed generation of receiver index removes the possible clash with the boostrap id * Integration test for nested LP registration - move `LpTransport` trait definition to shared `nym-lp-transport` crate - make transport layer within `LpConnectionHandler` generic with respect to the forwarding target. it must, however, use the same type as the incoming client connection - extracted explicit `LpConnectionHandler::establish_exit_stream` to more easily modify it in the future to fully protect the channel and disallow using untrusted egress points - fix additional log-string interpolation nits * resolved clippy issues pointed out by clippy 1.91 * added LP discovery into self-described endpoint: - removed changes to the node bonding within the contract - introduced '/api/v1/lewes-protocol' route within nym-node http api - added 'lewes_protocol' field to 'NymNodeData' inside of NymNodeDescription - refactored LpConfig to allow separate bind and announce addresses and used more strict typing * chore: allow unwrap/expect within kkt benchmarking code * chore: downgraded sha2 dep for cosmwasm compatibility * clippy * marking simd calls as unsafe * fixed calls to '_mm_testz_si128' * additional clippy fixes --------- Co-authored-by: Georgio Nicolas <me@georgio.xyz> Co-authored-by: Jędrzej Stuczyński <jedrzej.stuczynski@gmail.com>
842 lines
25 KiB
Go
842 lines
25 KiB
Go
/* SPDX-License-Identifier: MIT
|
|
*
|
|
* Copyright (C) 2024 Nym Technologies SA <contact@nymtech.net>. All Rights Reserved.
|
|
*/
|
|
|
|
package main
|
|
|
|
// #include <stdlib.h>
|
|
import "C"
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"math"
|
|
"math/rand"
|
|
"net"
|
|
"net/http"
|
|
"net/netip"
|
|
netUrl "net/url"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
"unsafe"
|
|
|
|
"github.com/amnezia-vpn/amneziawg-go/conn"
|
|
"github.com/amnezia-vpn/amneziawg-go/device"
|
|
"github.com/amnezia-vpn/amneziawg-go/tun/netstack"
|
|
"golang.org/x/net/icmp"
|
|
"golang.org/x/net/ipv4"
|
|
"golang.org/x/net/ipv6"
|
|
)
|
|
|
|
var fileUrls = []string{
|
|
"https://proof.ovh.net/files/10Mb.dat",
|
|
"https://nym-bandwidth-monitoring.ops-d86.workers.dev/10mb.dat",
|
|
// "https://nym-bandwidth-monitoring.ops-d86.workers.dev/100mb.dat", to be introduced later
|
|
}
|
|
|
|
var fileUrlsV6 = []string{
|
|
"https://proof.ovh.net/files/10Mb.dat",
|
|
"https://nym-bandwidth-monitoring.ops-d86.workers.dev/10mb.dat",
|
|
// "https://nym-bandwidth-monitoring.ops-d86.workers.dev/100mb.dat", to be introduced later
|
|
}
|
|
|
|
type NetstackRequestGo struct {
|
|
WgIp string `json:"wg_ip"`
|
|
PrivateKey string `json:"private_key"`
|
|
PublicKey string `json:"public_key"`
|
|
Endpoint string `json:"endpoint"`
|
|
MetadataEndpoint string `json:"metadata_endpoint"`
|
|
Dns string `json:"dns"`
|
|
IpVersion uint8 `json:"ip_version"`
|
|
PingHosts []string `json:"ping_hosts"`
|
|
PingIps []string `json:"ping_ips"`
|
|
NumPing uint8 `json:"num_ping"`
|
|
SendTimeoutSec uint64 `json:"send_timeout_sec"`
|
|
RecvTimeoutSec uint64 `json:"recv_timeout_sec"`
|
|
DownloadTimeoutSec uint64 `json:"download_timeout_sec"`
|
|
MetadataTimeoutSec uint64 `json:"metadata_timeout_sec"`
|
|
AwgArgs string `json:"awg_args"`
|
|
}
|
|
|
|
type NetstackResponse struct {
|
|
CanHandshake bool `json:"can_handshake"`
|
|
CanQueryMetadata bool `json:"can_query_metadata"`
|
|
SentIps uint16 `json:"sent_ips"`
|
|
ReceivedIps uint16 `json:"received_ips"`
|
|
SentHosts uint16 `json:"sent_hosts"`
|
|
ReceivedHosts uint16 `json:"received_hosts"`
|
|
CanResolveDns bool `json:"can_resolve_dns"`
|
|
DownloadedFile string `json:"downloaded_file"`
|
|
DownloadedFileSizeBytes uint64 `json:"downloaded_file_size_bytes"`
|
|
DownloadDurationSec uint64 `json:"download_duration_sec"`
|
|
DownloadDurationMilliseconds uint64 `json:"download_duration_milliseconds"`
|
|
DownloadError string `json:"download_error"`
|
|
}
|
|
|
|
type SuccessResult = struct {
|
|
Response NetstackResponse `json:"response"`
|
|
}
|
|
|
|
type ErrorResult = struct {
|
|
Error string `json:"error"`
|
|
}
|
|
|
|
func jsonResponse(response NetstackResponse) *C.char {
|
|
bytes, serializeErr := json.Marshal(SuccessResult{
|
|
Response: response,
|
|
})
|
|
if serializeErr == nil {
|
|
return C.CString(string(bytes))
|
|
} else {
|
|
return C.CString("{\"error\":\"" + serializeErr.Error() + "\"}")
|
|
}
|
|
}
|
|
|
|
func jsonError(err error) *C.char {
|
|
jsonErr := ErrorResult{
|
|
Error: fmt.Sprintf("failed to parse request: %s", err.Error()),
|
|
}
|
|
bytes, serializeErr := json.Marshal(jsonErr)
|
|
if serializeErr == nil {
|
|
return C.CString(string(bytes))
|
|
} else {
|
|
return C.CString("{\"error\":\"" + serializeErr.Error() + "\"}")
|
|
}
|
|
}
|
|
|
|
//export wgPing
|
|
func wgPing(cReq *C.char) *C.char {
|
|
reqStr := C.GoString(cReq)
|
|
|
|
var req NetstackRequestGo
|
|
err := json.Unmarshal([]byte(reqStr), &req)
|
|
if err != nil {
|
|
log.Printf("Failed to parse request: %s", err)
|
|
return jsonError(err)
|
|
}
|
|
|
|
response, err := ping(req)
|
|
if err != nil {
|
|
log.Printf("Failed to ping: %s", err)
|
|
return jsonError(err)
|
|
}
|
|
|
|
return jsonResponse(response)
|
|
}
|
|
|
|
//export wgFreePtr
|
|
func wgFreePtr(ptr unsafe.Pointer) {
|
|
C.free(ptr)
|
|
}
|
|
|
|
// TwoHopNetstackRequest contains configuration for two-hop WireGuard tunneling.
|
|
// Traffic flows: Client -> Entry WG Tunnel -> UDP Forwarder -> Exit WG Tunnel -> Internet
|
|
type TwoHopNetstackRequest struct {
|
|
// Entry tunnel configuration (connects to entry gateway)
|
|
EntryWgIp string `json:"entry_wg_ip"`
|
|
EntryPrivateKey string `json:"entry_private_key"`
|
|
EntryPublicKey string `json:"entry_public_key"`
|
|
EntryEndpoint string `json:"entry_endpoint"`
|
|
EntryAwgArgs string `json:"entry_awg_args"`
|
|
|
|
// Exit tunnel configuration (connects via forwarder through entry)
|
|
ExitWgIp string `json:"exit_wg_ip"`
|
|
ExitPrivateKey string `json:"exit_private_key"`
|
|
ExitPublicKey string `json:"exit_public_key"`
|
|
ExitEndpoint string `json:"exit_endpoint"` // Actual exit gateway endpoint (forwarded via entry)
|
|
ExitAwgArgs string `json:"exit_awg_args"`
|
|
|
|
// Test parameters (same as single-hop)
|
|
Dns string `json:"dns"`
|
|
IpVersion uint8 `json:"ip_version"`
|
|
PingHosts []string `json:"ping_hosts"`
|
|
PingIps []string `json:"ping_ips"`
|
|
NumPing uint8 `json:"num_ping"`
|
|
SendTimeoutSec uint64 `json:"send_timeout_sec"`
|
|
RecvTimeoutSec uint64 `json:"recv_timeout_sec"`
|
|
DownloadTimeoutSec uint64 `json:"download_timeout_sec"`
|
|
}
|
|
|
|
// Default port that exit WG tunnel uses to send traffic to the forwarder.
|
|
// The forwarder only accepts packets from this port on loopback.
|
|
const DEFAULT_EXIT_WG_CLIENT_PORT uint16 = 54001
|
|
|
|
// Entry tunnel MTU (outer tunnel)
|
|
const ENTRY_MTU = 1420
|
|
|
|
// Exit tunnel MTU (must be smaller due to double encapsulation)
|
|
const EXIT_MTU = 1340
|
|
|
|
//export wgPingTwoHop
|
|
func wgPingTwoHop(cReq *C.char) *C.char {
|
|
reqStr := C.GoString(cReq)
|
|
|
|
var req TwoHopNetstackRequest
|
|
err := json.Unmarshal([]byte(reqStr), &req)
|
|
if err != nil {
|
|
log.Printf("Failed to parse two-hop request: %s", err)
|
|
return jsonError(err)
|
|
}
|
|
|
|
response, err := pingTwoHop(req)
|
|
if err != nil {
|
|
log.Printf("Failed to ping (two-hop): %s", err)
|
|
return jsonError(err)
|
|
}
|
|
|
|
return jsonResponse(response)
|
|
}
|
|
|
|
func pingTwoHop(req TwoHopNetstackRequest) (NetstackResponse, error) {
|
|
log.Printf("=== Two-Hop WireGuard Probe ===")
|
|
log.Printf("Entry endpoint: %s", req.EntryEndpoint)
|
|
log.Printf("Entry WG IP: %s", req.EntryWgIp)
|
|
log.Printf("Exit endpoint: %s (via entry forwarding)", req.ExitEndpoint)
|
|
log.Printf("Exit WG IP: %s", req.ExitWgIp)
|
|
log.Printf("IP version: %d", req.IpVersion)
|
|
|
|
response := NetstackResponse{false, false, 0, 0, 0, 0, false, "", 0, 0, 0, ""}
|
|
|
|
// Parse the exit endpoint to determine IP version for forwarder
|
|
exitEndpoint, err := netip.ParseAddrPort(req.ExitEndpoint)
|
|
if err != nil {
|
|
return response, fmt.Errorf("failed to parse exit endpoint: %w", err)
|
|
}
|
|
|
|
// ============================================
|
|
// STEP 1: Create entry tunnel (netstack)
|
|
// ============================================
|
|
log.Printf("Creating entry tunnel (MTU=%d)...", ENTRY_MTU)
|
|
|
|
entryTun, entryTnet, err := netstack.CreateNetTUN(
|
|
[]netip.Addr{netip.MustParseAddr(req.EntryWgIp)},
|
|
[]netip.Addr{netip.MustParseAddr(req.Dns)},
|
|
ENTRY_MTU)
|
|
if err != nil {
|
|
return response, fmt.Errorf("failed to create entry tunnel: %w", err)
|
|
}
|
|
|
|
entryLogger := device.NewLogger(device.LogLevelError, "entry: ")
|
|
entryDev := device.NewDevice(entryTun, conn.NewDefaultBind(), entryLogger)
|
|
defer entryDev.Close()
|
|
|
|
// Configure entry device
|
|
var entryIpc strings.Builder
|
|
entryIpc.WriteString("private_key=")
|
|
entryIpc.WriteString(req.EntryPrivateKey)
|
|
if req.EntryAwgArgs != "" {
|
|
awg := strings.ReplaceAll(req.EntryAwgArgs, "\\n", "\n")
|
|
entryIpc.WriteString(fmt.Sprintf("\n%s", awg))
|
|
}
|
|
entryIpc.WriteString("\npublic_key=")
|
|
entryIpc.WriteString(req.EntryPublicKey)
|
|
entryIpc.WriteString("\nendpoint=")
|
|
entryIpc.WriteString(req.EntryEndpoint)
|
|
// Entry tunnel routes all traffic (the exit endpoint IP goes through it)
|
|
entryIpc.WriteString("\nallowed_ip=0.0.0.0/0")
|
|
entryIpc.WriteString("\nallowed_ip=::/0\n")
|
|
|
|
if err := entryDev.IpcSet(entryIpc.String()); err != nil {
|
|
return response, fmt.Errorf("failed to configure entry device: %w", err)
|
|
}
|
|
|
|
if err := entryDev.Up(); err != nil {
|
|
return response, fmt.Errorf("failed to bring up entry device: %w", err)
|
|
}
|
|
log.Printf("Entry tunnel up")
|
|
|
|
// ============================================
|
|
// STEP 2: Create UDP forwarder
|
|
// ============================================
|
|
log.Printf("Creating UDP forwarder (exit endpoint: %s)...", exitEndpoint.String())
|
|
|
|
forwarderConfig := UDPForwarderConfig{
|
|
ListenPort: 0, // Dynamic port assignment
|
|
ClientPort: DEFAULT_EXIT_WG_CLIENT_PORT,
|
|
Endpoint: exitEndpoint,
|
|
}
|
|
|
|
forwarder, err := NewUDPForwarder(forwarderConfig, entryTnet, entryLogger)
|
|
if err != nil {
|
|
return response, fmt.Errorf("failed to create UDP forwarder: %w", err)
|
|
}
|
|
defer forwarder.Close()
|
|
|
|
forwarderAddr := forwarder.GetListenAddr()
|
|
log.Printf("UDP forwarder listening on: %s", forwarderAddr.String())
|
|
|
|
// ============================================
|
|
// STEP 3: Create exit tunnel (netstack)
|
|
// ============================================
|
|
log.Printf("Creating exit tunnel (MTU=%d)...", EXIT_MTU)
|
|
|
|
exitTun, exitTnet, err := netstack.CreateNetTUN(
|
|
[]netip.Addr{netip.MustParseAddr(req.ExitWgIp)},
|
|
[]netip.Addr{netip.MustParseAddr(req.Dns)},
|
|
EXIT_MTU)
|
|
if err != nil {
|
|
return response, fmt.Errorf("failed to create exit tunnel: %w", err)
|
|
}
|
|
|
|
exitLogger := device.NewLogger(device.LogLevelError, "exit: ")
|
|
exitDev := device.NewDevice(exitTun, conn.NewDefaultBind(), exitLogger)
|
|
defer exitDev.Close()
|
|
|
|
// Configure exit device - endpoint is the forwarder, NOT the actual exit gateway
|
|
var exitIpc strings.Builder
|
|
exitIpc.WriteString("private_key=")
|
|
exitIpc.WriteString(req.ExitPrivateKey)
|
|
// Set listen_port so the forwarder knows which port to accept packets from
|
|
exitIpc.WriteString(fmt.Sprintf("\nlisten_port=%d", DEFAULT_EXIT_WG_CLIENT_PORT))
|
|
if req.ExitAwgArgs != "" {
|
|
awg := strings.ReplaceAll(req.ExitAwgArgs, "\\n", "\n")
|
|
exitIpc.WriteString(fmt.Sprintf("\n%s", awg))
|
|
}
|
|
exitIpc.WriteString("\npublic_key=")
|
|
exitIpc.WriteString(req.ExitPublicKey)
|
|
// IMPORTANT: endpoint is the local forwarder, not the actual exit gateway!
|
|
exitIpc.WriteString("\nendpoint=")
|
|
exitIpc.WriteString(forwarderAddr.String())
|
|
if req.IpVersion == 4 {
|
|
exitIpc.WriteString("\nallowed_ip=0.0.0.0/0\n")
|
|
} else {
|
|
exitIpc.WriteString("\nallowed_ip=::/0\n")
|
|
}
|
|
|
|
if err := exitDev.IpcSet(exitIpc.String()); err != nil {
|
|
return response, fmt.Errorf("failed to configure exit device: %w", err)
|
|
}
|
|
|
|
if err := exitDev.Up(); err != nil {
|
|
return response, fmt.Errorf("failed to bring up exit device: %w", err)
|
|
}
|
|
log.Printf("Exit tunnel up (via forwarder)")
|
|
|
|
// If we got here, both tunnels and forwarder are set up
|
|
response.CanHandshake = true
|
|
log.Printf("Two-hop tunnel setup complete!")
|
|
|
|
// ============================================
|
|
// STEP 4: Run tests through exit tunnel
|
|
// ============================================
|
|
log.Printf("Running tests through exit tunnel...")
|
|
|
|
// Ping hosts (DNS resolution test)
|
|
for _, host := range req.PingHosts {
|
|
consecutiveFailures := 0
|
|
maxConsecutiveFailures := 3
|
|
|
|
for i := uint8(0); i < req.NumPing; i++ {
|
|
log.Printf("Pinging %s seq=%d (via two-hop)", host, i)
|
|
response.SentHosts += 1
|
|
rt, err := sendPing(host, i, req.SendTimeoutSec, req.RecvTimeoutSec, exitTnet, req.IpVersion)
|
|
if err != nil {
|
|
log.Printf("Failed to send ping: %v", err)
|
|
consecutiveFailures++
|
|
if consecutiveFailures >= maxConsecutiveFailures {
|
|
log.Printf("Too many consecutive failures (%d), stopping ping attempts for %s", consecutiveFailures, host)
|
|
break
|
|
}
|
|
continue
|
|
}
|
|
consecutiveFailures = 0
|
|
response.ReceivedHosts += 1
|
|
response.CanResolveDns = true
|
|
log.Printf("Ping latency: %v", rt)
|
|
}
|
|
}
|
|
|
|
// Ping IPs (direct connectivity test)
|
|
for _, ip := range req.PingIps {
|
|
consecutiveFailures := 0
|
|
maxConsecutiveFailures := 3
|
|
|
|
for i := uint8(0); i < req.NumPing; i++ {
|
|
log.Printf("Pinging %s seq=%d (via two-hop)", ip, i)
|
|
response.SentIps += 1
|
|
rt, err := sendPing(ip, i, req.SendTimeoutSec, req.RecvTimeoutSec, exitTnet, req.IpVersion)
|
|
if err != nil {
|
|
log.Printf("Failed to send ping: %v", err)
|
|
consecutiveFailures++
|
|
if consecutiveFailures >= maxConsecutiveFailures {
|
|
log.Printf("Too many consecutive failures (%d), stopping ping attempts for %s", consecutiveFailures, ip)
|
|
break
|
|
}
|
|
} else {
|
|
consecutiveFailures = 0
|
|
response.ReceivedIps += 1
|
|
log.Printf("Ping latency: %v", rt)
|
|
}
|
|
|
|
if i < req.NumPing-1 {
|
|
time.Sleep(5 * time.Second)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Download test
|
|
var urlsToTry []string
|
|
if req.IpVersion == 4 {
|
|
urlsToTry = fileUrls
|
|
} else {
|
|
urlsToTry = fileUrlsV6
|
|
}
|
|
|
|
fileContent, downloadDuration, usedURL, err := downloadFileWithRetry(urlsToTry, req.DownloadTimeoutSec, exitTnet)
|
|
if err != nil {
|
|
log.Printf("Failed to download file from any URL: %v", err)
|
|
response.DownloadError = err.Error()
|
|
} else {
|
|
log.Printf("Downloaded file content length: %.2f MB", float64(len(fileContent))/1024/1024)
|
|
log.Printf("Download duration: %v", downloadDuration)
|
|
response.DownloadedFileSizeBytes = uint64(len(fileContent))
|
|
}
|
|
|
|
response.DownloadDurationSec = uint64(downloadDuration.Seconds())
|
|
response.DownloadDurationMilliseconds = uint64(downloadDuration.Milliseconds())
|
|
response.DownloadedFile = usedURL
|
|
|
|
log.Printf("=== Two-Hop Probe Complete ===")
|
|
return response, nil
|
|
}
|
|
|
|
func ping(req NetstackRequestGo) (NetstackResponse, error) {
|
|
fmt.Printf("Endpoint: %s\n", req.Endpoint)
|
|
fmt.Printf("WireGuard IP: %s\n", req.WgIp)
|
|
fmt.Printf("IP version: %d\n", req.IpVersion)
|
|
|
|
tun, tnet, err := netstack.CreateNetTUN(
|
|
[]netip.Addr{netip.MustParseAddr(req.WgIp)},
|
|
[]netip.Addr{netip.MustParseAddr(req.Dns)},
|
|
1280)
|
|
|
|
if err != nil {
|
|
return NetstackResponse{}, err
|
|
}
|
|
dev := device.NewDevice(tun, conn.NewDefaultBind(), device.NewLogger(device.LogLevelError, ""))
|
|
|
|
var ipc strings.Builder
|
|
|
|
ipc.WriteString("private_key=")
|
|
ipc.WriteString(req.PrivateKey)
|
|
if req.AwgArgs != "" {
|
|
awg := strings.ReplaceAll(req.AwgArgs, "\\n", "\n")
|
|
ipc.WriteString(fmt.Sprintf("\n%s", awg))
|
|
}
|
|
ipc.WriteString("\npublic_key=")
|
|
ipc.WriteString(req.PublicKey)
|
|
ipc.WriteString("\nendpoint=")
|
|
ipc.WriteString(req.Endpoint)
|
|
if req.IpVersion == 4 {
|
|
ipc.WriteString("\nallowed_ip=0.0.0.0/0\n")
|
|
} else {
|
|
ipc.WriteString("\nallowed_ip=::/0\n")
|
|
}
|
|
|
|
response := NetstackResponse{false, false, 0, 0, 0, 0, false, "", 0, 0, 0, ""}
|
|
|
|
err = dev.IpcSet(ipc.String())
|
|
if err != nil {
|
|
return NetstackResponse{}, err
|
|
}
|
|
|
|
config, err := dev.IpcGet()
|
|
if err != nil {
|
|
return NetstackResponse{}, err
|
|
}
|
|
|
|
// do not print the config by default, because it contains the wg private key
|
|
if os.Getenv("SHOW_WG_CONFIG") == "true" {
|
|
log.Printf("%s", config)
|
|
}
|
|
|
|
err = dev.Up()
|
|
if err != nil {
|
|
return NetstackResponse{}, err
|
|
}
|
|
|
|
response.CanHandshake = true
|
|
|
|
// Skip metadata query if endpoint is empty (e.g., for IPv6 where the IPv4 metadata endpoint is not reachable)
|
|
if req.MetadataEndpoint != "" {
|
|
version, duration, err := queryMetadata(req.MetadataEndpoint, req.MetadataTimeoutSec, tnet)
|
|
if err != nil {
|
|
log.Printf("Failed to query metadata URLs: %v\n", err)
|
|
response.CanQueryMetadata = false
|
|
} else {
|
|
log.Printf("Queried metadata endpoint with version: %v\n", version)
|
|
log.Printf("Query duration: %v\n", duration)
|
|
response.CanQueryMetadata = true
|
|
}
|
|
} else {
|
|
log.Printf("Skipping metadata query (no endpoint provided)")
|
|
response.CanQueryMetadata = false
|
|
}
|
|
|
|
for _, host := range req.PingHosts {
|
|
consecutiveFailures := 0
|
|
maxConsecutiveFailures := 3
|
|
|
|
for i := uint8(0); i < req.NumPing; i++ {
|
|
log.Printf("Pinging %s seq=%d", host, i)
|
|
response.SentHosts += 1
|
|
rt, err := sendPing(host, i, req.SendTimeoutSec, req.RecvTimeoutSec, tnet, req.IpVersion)
|
|
if err != nil {
|
|
log.Printf("Failed to send ping: %v\n", err)
|
|
consecutiveFailures++
|
|
|
|
// Early exit if too many consecutive failures
|
|
if consecutiveFailures >= maxConsecutiveFailures {
|
|
log.Printf("Too many consecutive failures (%d), stopping ping attempts for %s", consecutiveFailures, host)
|
|
break
|
|
}
|
|
continue
|
|
}
|
|
|
|
// Reset failure counter on success
|
|
consecutiveFailures = 0
|
|
response.ReceivedHosts += 1
|
|
response.CanResolveDns = true
|
|
log.Printf("Ping latency: %v\n", rt)
|
|
}
|
|
}
|
|
|
|
for _, ip := range req.PingIps {
|
|
consecutiveFailures := 0
|
|
maxConsecutiveFailures := 3
|
|
|
|
for i := uint8(0); i < req.NumPing; i++ {
|
|
log.Printf("Pinging %s seq=%d", ip, i)
|
|
response.SentIps += 1
|
|
rt, err := sendPing(ip, i, req.SendTimeoutSec, req.RecvTimeoutSec, tnet, req.IpVersion)
|
|
if err != nil {
|
|
log.Printf("Failed to send ping: %v\n", err)
|
|
consecutiveFailures++
|
|
|
|
// Early exit if too many consecutive failures
|
|
if consecutiveFailures >= maxConsecutiveFailures {
|
|
log.Printf("Too many consecutive failures (%d), stopping ping attempts for %s", consecutiveFailures, ip)
|
|
break
|
|
}
|
|
} else {
|
|
// Reset failure counter on success
|
|
consecutiveFailures = 0
|
|
response.ReceivedIps += 1
|
|
log.Printf("Ping latency: %v\n", rt)
|
|
}
|
|
|
|
// Sleep between ping attempts (except for the last one)
|
|
if i < req.NumPing-1 {
|
|
time.Sleep(5 * time.Second)
|
|
}
|
|
}
|
|
}
|
|
|
|
var urlsToTry []string
|
|
|
|
if req.IpVersion == 4 {
|
|
urlsToTry = fileUrls
|
|
} else {
|
|
urlsToTry = fileUrlsV6
|
|
}
|
|
|
|
// Try URLs with retry logic
|
|
fileContent, downloadDuration, usedURL, err := downloadFileWithRetry(urlsToTry, req.DownloadTimeoutSec, tnet)
|
|
if err != nil {
|
|
log.Printf("Failed to download file from any URL: %v\n", err)
|
|
} else {
|
|
log.Printf("Downloaded file content length: %.2f MB\n", float64(len(fileContent))/1024/1024)
|
|
log.Printf("Download duration: %v\n", downloadDuration)
|
|
}
|
|
|
|
response.DownloadDurationSec = uint64(downloadDuration.Seconds())
|
|
response.DownloadDurationMilliseconds = uint64(downloadDuration.Milliseconds())
|
|
response.DownloadedFile = usedURL
|
|
if err != nil {
|
|
response.DownloadError = err.Error()
|
|
response.DownloadedFileSizeBytes = 0
|
|
} else {
|
|
response.DownloadError = ""
|
|
response.DownloadedFileSizeBytes = uint64(len(fileContent))
|
|
}
|
|
|
|
return response, nil
|
|
}
|
|
|
|
func sendPing(address string, seq uint8, sendTtimeoutSecs uint64, receiveTimoutSecs uint64, tnet *netstack.Net, ipVersion uint8) (time.Duration, error) {
|
|
maxPingRetries := 2
|
|
baseTimeout := receiveTimoutSecs
|
|
|
|
for attempt := 0; attempt < maxPingRetries; attempt++ {
|
|
// Slightly increase timeout on retries, but keep it reasonable
|
|
adjustedTimeout := baseTimeout + uint64(attempt*1) // +1s per retry only
|
|
|
|
duration, err := sendPingAttempt(address, seq, sendTtimeoutSecs, adjustedTimeout, tnet, ipVersion)
|
|
if err == nil {
|
|
return duration, nil
|
|
}
|
|
|
|
log.Printf("Ping attempt %d/%d failed: %v", attempt+1, maxPingRetries, err)
|
|
if attempt < maxPingRetries-1 {
|
|
time.Sleep(200 * time.Millisecond) // Very brief delay between retries
|
|
}
|
|
}
|
|
|
|
return 0, fmt.Errorf("ping failed after %d attempts", maxPingRetries)
|
|
}
|
|
|
|
func sendPingAttempt(address string, seq uint8, sendTtimeoutSecs uint64, receiveTimoutSecs uint64, tnet *netstack.Net, ipVersion uint8) (time.Duration, error) {
|
|
var socket net.Conn
|
|
var err error
|
|
if ipVersion == 4 {
|
|
socket, err = tnet.Dial("ping4", address)
|
|
} else {
|
|
socket, err = tnet.Dial("ping6", address)
|
|
}
|
|
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
defer socket.Close()
|
|
|
|
var icmpBytes []byte
|
|
|
|
requestPing := icmp.Echo{
|
|
ID: 1337,
|
|
Seq: int(seq),
|
|
Data: []byte("gopher burrow"),
|
|
}
|
|
|
|
if ipVersion == 4 {
|
|
icmpBytes, _ = (&icmp.Message{Type: ipv4.ICMPTypeEcho, Code: 0, Body: &requestPing}).Marshal(nil)
|
|
} else {
|
|
icmpBytes, _ = (&icmp.Message{Type: ipv6.ICMPTypeEchoRequest, Code: 0, Body: &requestPing}).Marshal(nil)
|
|
}
|
|
|
|
start := time.Now()
|
|
|
|
socket.SetWriteDeadline(time.Now().Add(time.Second * time.Duration(sendTtimeoutSecs)))
|
|
_, err = socket.Write(icmpBytes)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
// Wait for reply with limited read attempts to avoid long delays
|
|
maxReadAttempts := 2
|
|
for readAttempt := 0; readAttempt < maxReadAttempts; readAttempt++ {
|
|
socket.SetReadDeadline(time.Now().Add(time.Second * time.Duration(receiveTimoutSecs)))
|
|
n, err := socket.Read(icmpBytes[:])
|
|
if err != nil {
|
|
if readAttempt < maxReadAttempts-1 {
|
|
log.Printf("Read attempt %d failed, retrying: %v", readAttempt+1, err)
|
|
continue
|
|
}
|
|
return 0, err
|
|
}
|
|
|
|
var proto int
|
|
if ipVersion == 4 {
|
|
proto = 1
|
|
} else {
|
|
proto = 58
|
|
}
|
|
|
|
replyPacket, err := icmp.ParseMessage(proto, icmpBytes[:n])
|
|
if err != nil {
|
|
if readAttempt < maxReadAttempts-1 {
|
|
log.Printf("Parse attempt %d failed, retrying: %v", readAttempt+1, err)
|
|
continue
|
|
}
|
|
return 0, err
|
|
}
|
|
|
|
var ok bool
|
|
replyPing, ok := replyPacket.Body.(*icmp.Echo)
|
|
|
|
if !ok {
|
|
if readAttempt < maxReadAttempts-1 {
|
|
log.Printf("Invalid reply type attempt %d, retrying", readAttempt+1)
|
|
continue
|
|
}
|
|
return 0, fmt.Errorf("invalid reply type: %v", replyPacket)
|
|
}
|
|
|
|
if bytes.Equal(replyPing.Data, requestPing.Data) {
|
|
// Accept sequence number matches or close matches (for out-of-order delivery)
|
|
if replyPing.Seq == requestPing.Seq || math.Abs(float64(replyPing.Seq-requestPing.Seq)) <= 1 {
|
|
return time.Since(start), nil
|
|
}
|
|
log.Printf("Sequence mismatch (expected %d, received %d), retrying", requestPing.Seq, replyPing.Seq)
|
|
} else {
|
|
if readAttempt < maxReadAttempts-1 {
|
|
log.Printf("Data mismatch attempt %d, retrying", readAttempt+1)
|
|
continue
|
|
}
|
|
return 0, fmt.Errorf("invalid ping reply: %v (request: %v)", replyPing, requestPing)
|
|
}
|
|
}
|
|
|
|
return 0, fmt.Errorf("ping failed after %d read attempts", maxReadAttempts)
|
|
}
|
|
|
|
func downloadFileWithRetry(urls []string, timeoutSecs uint64, tnet *netstack.Net) ([]byte, time.Duration, string, error) {
|
|
maxRetries := 3
|
|
baseDelay := 1 * time.Second
|
|
consecutiveFailures := 0
|
|
maxConsecutiveFailures := 3
|
|
|
|
for attempt := 0; attempt < maxRetries; attempt++ {
|
|
// Shuffle URLs for each attempt to try different ones
|
|
shuffledUrls := make([]string, len(urls))
|
|
copy(shuffledUrls, urls)
|
|
rand.Shuffle(len(shuffledUrls), func(i, j int) {
|
|
shuffledUrls[i], shuffledUrls[j] = shuffledUrls[j], shuffledUrls[i]
|
|
})
|
|
|
|
for _, url := range shuffledUrls {
|
|
log.Printf("Attempting download from: %s (attempt %d/%d)", url, attempt+1, maxRetries)
|
|
// Increase timeout on retries to handle slow servers
|
|
adjustedTimeout := timeoutSecs + uint64(attempt*5) // +5s per retry
|
|
content, duration, err := downloadFile(url, adjustedTimeout, tnet)
|
|
if err == nil {
|
|
log.Printf("Successfully downloaded from: %s", url)
|
|
return content, duration, url, nil
|
|
}
|
|
log.Printf("Failed to download from %s: %v", url, err)
|
|
consecutiveFailures++
|
|
|
|
// Early exit if too many consecutive failures
|
|
if consecutiveFailures >= maxConsecutiveFailures {
|
|
log.Printf("Too many consecutive download failures (%d), stopping attempts", consecutiveFailures)
|
|
return nil, 0, "", fmt.Errorf("too many consecutive failures (%d), stopping download attempts", consecutiveFailures)
|
|
}
|
|
}
|
|
|
|
if attempt < maxRetries-1 {
|
|
delay := baseDelay * time.Duration(attempt+1)
|
|
log.Printf("All URLs failed, retrying in %v...", delay)
|
|
time.Sleep(delay)
|
|
}
|
|
}
|
|
|
|
return nil, 0, "", fmt.Errorf("failed to download from any URL after %d attempts", maxRetries)
|
|
}
|
|
|
|
func downloadFile(url string, timeoutSecs uint64, tnet *netstack.Net) ([]byte, time.Duration, error) {
|
|
transport := &http.Transport{
|
|
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
|
return tnet.Dial(network, addr)
|
|
},
|
|
}
|
|
|
|
client := &http.Client{
|
|
Transport: transport,
|
|
Timeout: time.Second * time.Duration(timeoutSecs),
|
|
}
|
|
|
|
start := time.Now() // Start timing
|
|
|
|
resp, err := client.Get(url)
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return nil, 0, fmt.Errorf("failed to download file: %s", resp.Status)
|
|
}
|
|
|
|
var buf bytes.Buffer
|
|
_, err = io.Copy(&buf, resp.Body)
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
duration := time.Since(start) // Calculate duration
|
|
|
|
return buf.Bytes(), duration, nil
|
|
}
|
|
|
|
func queryMetadata(url string, timeoutSecs uint64, tnet *netstack.Net) (int, time.Duration, error) {
|
|
transport := &http.Transport{
|
|
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
|
return tnet.Dial(network, addr)
|
|
},
|
|
}
|
|
|
|
client := &http.Client{
|
|
Transport: transport,
|
|
Timeout: time.Second * time.Duration(timeoutSecs),
|
|
}
|
|
|
|
bandwidthVersionUrl, err := netUrl.JoinPath(url, "v1/bandwidth/version")
|
|
if err != nil {
|
|
return 0, 0, err
|
|
}
|
|
|
|
start := time.Now() // Start timing
|
|
|
|
log.Printf("Querying metadata encoding: url = %s", bandwidthVersionUrl)
|
|
resp, err := client.Get(bandwidthVersionUrl)
|
|
if err != nil {
|
|
return 0, 0, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return 0, 0, fmt.Errorf("failed to query metadata endpoint: %s", resp.Status)
|
|
}
|
|
|
|
var contentType = resp.Header.Get("Content-Type")
|
|
|
|
log.Printf("Metadata Content-Type: %s", contentType)
|
|
|
|
var reader io.Reader = resp.Body
|
|
bodyBytes, err := io.ReadAll(reader)
|
|
if err != nil {
|
|
return 0, 0, err
|
|
}
|
|
|
|
var version int
|
|
err = json.Unmarshal(bodyBytes, &version)
|
|
if err != nil {
|
|
return 0, 0, err
|
|
}
|
|
|
|
duration := time.Since(start) // Calculate duration
|
|
|
|
return version, duration, nil
|
|
}
|
|
|
|
func main() {
|
|
// uncomment the lines below to run locally and see README.md for how to get the Wireguard config
|
|
/* var _, err = ping(NetstackRequestGo{
|
|
WgIp: "10.1.155.153",
|
|
PrivateKey: "...",
|
|
PublicKey: "...",
|
|
Endpoint: "13.245.9.123:51822",
|
|
MetadataEndpoint: "http://10.1.0.1:51830",
|
|
Dns: "1.1.1.1",
|
|
IpVersion: 4,
|
|
//PingHosts: nil,
|
|
//PingIps: nil,
|
|
//NumPing: 0,
|
|
//SendTimeoutSec: 0,
|
|
//RecvTimeoutSec: 0,
|
|
//DownloadTimeoutSec: 0,
|
|
MetadataTimeoutSec: 5,
|
|
//AwgArgs: "",
|
|
})
|
|
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
*/
|
|
}
|