Commit 3df7d082 authored by jan.koester's avatar jan.koester
Browse files

cleanups

parent ce2c6831
Loading
Loading
Loading
Loading
+15 −1
Changes for src/ssl.cpp: 15 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -92,7 +92,21 @@ void ssl::accept(std::unique_ptr<socket>& csock, bool nonblock) {
    // Share cert_map with child — no deep copy
    std::unique_ptr<ssl> cssock(new ssl(_tls.cert_map));

    tcp::accept(reinterpret_cast<std::unique_ptr<socket>&>(cssock), nonblock);
    // tcp::accept() only needs a socket& to fill in (fd, peer address) --
    // it never resets/reassigns the unique_ptr itself, so a temporary
    // ownership transfer gets it a real std::unique_ptr<socket> to call
    // through. (The previous reinterpret_cast<unique_ptr<socket>&>(cssock)
    // violated strict aliasing -- unique_ptr<ssl> and unique_ptr<socket>
    // are distinct types -- even though it happened to work here thanks to
    // single inheritance and a virtual ~socket().)
    std::unique_ptr<socket> tmp(cssock.release());
    try {
        tcp::accept(tmp, nonblock);
    } catch (...) {
        cssock.reset(static_cast<ssl*>(tmp.release()));
        throw;
    }
    cssock.reset(static_cast<ssl*>(tmp.release()));

    // Propagate ALPN select callback and framing callback to child socket
    cssock->_tls.alpn_select_cb = _tls.alpn_select_cb;
+1 −1
Changes for test/CMakeLists.txt: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -115,7 +115,7 @@ add_test(

add_test(
    NAME x509_test
    COMMAND x509
    COMMAND x509 "${CMAKE_CURRENT_SOURCE_DIR}/certificate.der"
)

add_test(
+0 −26
Changes for test/https_test.cpp: 0 added lines, 26 removed lines.
Original line number Diff line number Diff line
@@ -402,15 +402,6 @@ static void hpackEncodeLiteralHeader(std::vector<uint8_t>& out, uint8_t static_i
    hpackEncodeString(out, value);
}

// HPACK encode header with new name
static void hpackEncodeLiteralHeaderNewName(std::vector<uint8_t>& out, const std::string& name, const std::string& value) {
    // Literal Header Field with Incremental Indexing - New Name
    // 01000000 followed by name and value
    out.push_back(0x40);
    hpackEncodeString(out, name);
    hpackEncodeString(out, value);
}

// HPACK encode indexed header (fully in static table)
static void hpackEncodeIndexed(std::vector<uint8_t>& out, uint8_t index) {
    // Indexed Header Field: 1xxxxxxx
@@ -469,23 +460,6 @@ static void appendH2DataFrame(condata<char>& out, uint32_t stream_id,
    out.append(body.data(), body.size());
}

// Append HTTP/2 GOAWAY frame directly into SendData
static void appendH2GoawayFrame(condata<char>& out, uint32_t last_stream_id,
                                 H2Error error_code) {
    uint8_t buf[9 + 8];
    writeH2FrameHeader(buf, 8, static_cast<uint8_t>(H2FrameType::GOAWAY), 0, 0);
    uint32_t err = static_cast<uint32_t>(error_code);
    buf[9]  = (last_stream_id >> 24) & 0x7F;
    buf[10] = (last_stream_id >> 16) & 0xFF;
    buf[11] = (last_stream_id >> 8) & 0xFF;
    buf[12] = last_stream_id & 0xFF;
    buf[13] = (err >> 24) & 0xFF;
    buf[14] = (err >> 16) & 0xFF;
    buf[15] = (err >> 8) & 0xFF;
    buf[16] = err & 0xFF;
    out.append(reinterpret_cast<const char*>(buf), sizeof(buf));
}

// Parse HTTP/2 frame header
static bool parseH2FrameHeader(const uint8_t* data, size_t len, H2Frame& frame) {
    if (len < 9) return false;
+0 −147
Changes for test/quic_test.cpp: 0 added lines, 147 removed lines.
Original line number Diff line number Diff line
@@ -398,109 +398,6 @@ static std::vector<uint8_t> buildHttp3Response(uint16_t status_code, const std::
    return response;
}

// HTTP/3 stream callback - handles incoming requests
static void http3StreamCallback(netplus::socket* sock, uint64_t stream_id, 
                                 const std::vector<uint8_t>& data, bool fin) {
    quic* q = static_cast<quic*>(sock);
    
    std::cerr << "[HTTP/3] Stream callback: stream_id=" << stream_id 
              << ", data.size()=" << data.size() 
              << ", fin=" << fin << std::endl;
    
    if (data.empty()) {
        std::cerr << "[HTTP/3] Empty data, returning" << std::endl;
        return;
    }
    
    // Determine stream type
    // stream_id % 4 == 0: client-initiated bidirectional (requests)
    // stream_id % 4 == 2: client-initiated unidirectional (control/QPACK)
    bool is_unidirectional = (stream_id % 4 == 2) || (stream_id % 4 == 3);
    
    std::cerr << "[HTTP/3] Stream " << stream_id 
              << " (uni=" << is_unidirectional << "), size=" << data.size() 
              << ", fin=" << fin << std::endl;
    
    // For unidirectional streams, just log them (control/QPACK setup)
    if (is_unidirectional) {
        if (!data.empty()) {
            // First byte of unidirectional stream indicates type
            // 0x00 = Control stream, 0x01 = Push stream, 0x02 = QPACK encoder, 0x03 = QPACK decoder
            uint8_t stream_type = data[0];
            std::cerr << "[HTTP/3] Unidirectional stream type=" << (int)stream_type << std::endl;
        }
        return;  // Don't respond to control streams
    }
    
    // Only process bidirectional streams when FIN is received (complete request)
    if (!fin) {
        std::cerr << "[HTTP/3] Bidirectional stream waiting for FIN" << std::endl;
        return;
    }
    
    // Parse HTTP/3 frames on bidirectional request streams
    size_t offset = 0;
    while (offset < data.size()) {
        size_t bytes;
        uint64_t frame_type = decodeVarInt(&data[offset], bytes);
        offset += bytes;
        
        if (offset >= data.size()) break;
        
        uint64_t frame_length = decodeVarInt(&data[offset], bytes);
        offset += bytes;
        
        std::cerr << "[HTTP/3] Frame type=" << frame_type 
                  << ", length=" << frame_length << std::endl;
        
        if (frame_type == 0x01) { // HEADERS
            std::cerr << "[HTTP/3] Received HEADERS frame, sending response" << std::endl;
            
            // Detect request path by scanning QPACK-encoded header data
            bool is_badge = false;
            if (offset + frame_length <= data.size()) {
                is_badge = isBadgeSvgPath(
                    reinterpret_cast<const char*>(&data[offset]), frame_length);
            }
            
            std::vector<uint8_t> response;
            if (is_badge) {
                // Serve QUIC success badge SVG as external resource
                response = buildHttp3Response(200, getSvgQuicSuccessBadge(), "image/svg+xml");
            } else {
                // Serve HTML page with inline success badge (avoids sub-resource going over HTTP/2)
                std::string html = R"HTML(<!DOCTYPE html><html><head><title>QUIC HTTP/3 Server</title>
<style>body{font-family:sans-serif;margin:40px;background:#f5f5f5}
.c{max-width:600px;margin:0 auto;background:#fff;padding:30px;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.1)}
h1{color:#22c55e}p{line-height:1.6}.info{background:#f0fdf4;border-left:4px solid #22c55e;padding:15px;margin:20px 0}
.badge{text-align:center;margin:20px 0}</style></head><body><div class="c">
<h1>QUIC HTTP/3 Connection Successful!</h1>
<div class="badge">)HTML";
                html += getSvgQuicSuccessBadge();
                html += R"HTML(</div>
<div class="info"><p><strong>Congratulations!</strong> You are using HTTP/3 with QUIC protocol!</p></div>
<p>Protocol: QUIC (UDP) | Version: HTTP/3 | Encryption: TLS 1.3</p>
</div></body></html>)HTML";
                response = buildHttp3Response(200, html, "text/html; charset=utf-8");
            }
            
            std::cerr << "[HTTP/3] Sending response: stream_id=" << stream_id 
                      << ", response.size()=" << response.size()
                      << ", badge=" << is_badge << std::endl;
            
            try {
                q->sendStreamData(stream_id, response, true);
                std::cerr << "[HTTP/3] Response sent successfully" << std::endl;
            } catch (const std::exception& e) {
                std::cerr << "[HTTP/3] Error sending response: " << e.what() << std::endl;
            }
        }
        
        // Skip frame data
        offset += frame_length;
    }
}

class QuicServer : public event {
  public:
    QuicServer(std::vector<netplus::socket*> serversockets, int timeout=1000)
@@ -757,50 +654,6 @@ h1{color:#2563eb}p{line-height:1.6}.info{background:#eff6ff;border-left:4px soli
    }
};

// Thread function to run HTTPS fallback server
static void runHttpsFallbackServer(std::map<std::string, netplus::ssl::CertificateBundle>& certs) {
    try {
        std::cout << "[HTTPS Fallback] Starting on [::]:8443 (TCP, dual-stack)..." << std::endl;
        
        // Create SSL/TLS socket on port 8443 (TCP) - same port as QUIC (UDP)
        // Bind to :: for dual-stack IPv4+IPv6 (Firefox needs IPv6 support)
        ssl fallbackSock(certs, "::", 8443, 1024, -1);
        std::cout << "[HTTPS Fallback] Socket created on port 8443 (TCP, dual-stack)" << std::endl;
        
        // Configure ALPN: only accept h2 (HTTP/2)
        fallbackSock.setAlpnSelectCallback([](const std::vector<std::string>& client_protos) -> std::string {
            for (const auto& p : client_protos) {
                if (p == "h2") return p;
            }
            return "h2"; // Force h2 even if client didn't offer it
        });

        // Configure framing callback: always HTTP/2
        // stream_id == 0 → epoll post-handshake probe, return empty
        //                   (SETTINGS preface is sent by h2ProcessFrames)
        // stream_id >  0 → produce response for that HTTP/2 stream
        fallbackSock.setFramingCallback([](const std::string& alpn,
                                           uint32_t stream_id,
                                           const std::string& body,
                                           const std::string& content_type) -> std::string {
            if (stream_id == 0) {
                return "";
            }
            return h2BuildResponse(stream_id, body, content_type);
        });

        HttpsFallbackServer srv({&fallbackSock});
        std::cout << "[HTTPS Fallback] Server ready, entering event loop" << std::endl;
        
        srv.runEventloop();
        
    } catch (netplus::NetException& e) {
        std::cerr << "[HTTPS Fallback] NetException: " << e.what() << std::endl;
    } catch (std::exception& e) {
        std::cerr << "[HTTPS Fallback] Exception: " << e.what() << std::endl;
    }
}

// ============================================================================
// Client test thread: connects, sends data, verifies echo, shuts down
// ============================================================================