diff --git a/modules/http3/h3_threads.c b/modules/http3/h3_threads.c index 6855f1fd85d..ec6c4576987 100644 --- a/modules/http3/h3_threads.c +++ b/modules/http3/h3_threads.c @@ -115,8 +115,7 @@ void* APR_THREAD_FUNC h3_event_thread(apr_thread_t* thread, void* data) /* The engine has already answered these clients: refuse them, or they wait out their idle timeout. */ if (io->draining) { - h3q_conn_refuse(conn); /* no new connections during a graceful stop */ - h3q_conn_free(conn); + h3q_conn_refuse(io->qengine, conn); /* no new connections during a graceful stop */ continue; } ap_log_error(APLOG_MARK, APLOG_INFO, 0, io->server, "accepted new QUIC connection"); @@ -124,8 +123,7 @@ void* APR_THREAD_FUNC h3_event_thread(apr_thread_t* thread, void* data) { h3_server_conf* conf = ap_get_module_config(io->server->module_config, &http3_module); ap_log_error(APLOG_MARK, APLOG_WARNING, 0, io->server, "dropping QUIC connection: at H3MaxConnections limit (%u)", conf->h3_max_connections); - h3q_conn_refuse(conn); - h3q_conn_free(conn); + h3q_conn_refuse(io->qengine, conn); continue; } if (!prepare_accepted_connection(io, conn)) diff --git a/modules/http3/include/quic/detail/h3q_ossl_addr.h b/modules/http3/include/quic/detail/h3q_ossl_addr.h new file mode 100644 index 00000000000..dbe789ecf67 --- /dev/null +++ b/modules/http3/include/quic/detail/h3q_ossl_addr.h @@ -0,0 +1,146 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef H3Q_DETAIL_OSSL_ADDR_H +#define H3Q_DETAIL_OSSL_ADDR_H + +#include +#include + +#include + +#include +#include + +#include "quic/h3q.h" + +typedef struct h3q_datagram h3q_datagram; +typedef struct h3q_refused h3q_refused; + +/** A refused connection, kept until its closing period is over. */ +struct h3q_refused +{ + SSL* ssl_conn; + apr_time_t refused_at; + int closing; + h3q_refused* next; +}; + +/** The listener's state. All but the two SSL handles exist to recover a + * connection's peer address, which OpenSSL 3.5 does not otherwise expose; + * that is why the definition lives beside the machinery that fills it. */ +struct h3q_engine +{ + apr_pool_t* pool; + SSL_CTX* ssl_ctx; + SSL* ssl_listener; + uint32_t idle_timeout_secs; + + BIO_METHOD* peer_addr_bio_method; + BIO_ADDR* current_peer_addr; + int peer_addr_ex_index; + h3q_datagram* peer_rx_head; + h3q_datagram* peer_rx_tail; + + /* Only touched from the event thread. A pool cannot free single nodes, so a reaped one waits in refused_free. */ + h3q_refused* refused_head; + h3q_refused* refused_free; +}; + +/** + * Apply the stream modes, incoming-stream policy and idle timeout a freshly + * accepted connection needs before its handshake is driven. + * @param conn Connection to prepare; NULL reports failure. + * @param idle_timeout_secs Idle timeout to apply, in seconds. + * @return 1 on success, 0 on failure. + */ +int h3q_conn_prepare(h3q_conn* conn, uint32_t idle_timeout_secs); + +/** + * Free the refused connections whose closing period is over. + * @param engine Engine the connections were refused on. + * @param all Non-zero to free every refused connection, as at engine shutdown. + */ +void h3q_engine_reap_refused(h3q_engine* engine, int all); + +/** + * Drop every datagram still queued on the engine. + * @param engine Engine whose receive queue is emptied. + */ +void h3q_peer_addr_queue_clear(h3q_engine* engine); + +/** + * BIO_meth_set_ctrl handler for the peer-address filter BIO. + * @param bio Filter BIO receiving the control operation. + * @param cmd Control command, forwarded to the underlying BIO. + * @param num Command-specific numeric argument. + * @param ptr Command-specific pointer argument. + * @return Whatever the underlying BIO returns for @p cmd. + */ +long h3q_peer_addr_bio_ctrl(BIO* bio, int cmd, long num, void* ptr); + +/** + * BIO_meth_set_sendmmsg handler, forwarding to the underlying BIO. + * @param bio Filter BIO the datagrams are written through. + * @param msg Array of messages to send. + * @param stride Size of one entry in @p msg. + * @param num_msg Number of entries in @p msg. + * @param flags Flags passed through to the underlying BIO. + * @param msgs_processed Out: how many messages were sent. + * @return 1 on success, 0 on failure. + */ +int h3q_peer_addr_bio_sendmmsg(BIO* bio, BIO_MSG* msg, size_t stride, size_t num_msg, uint64_t flags, size_t* msgs_processed); + +/** + * BIO_meth_set_recvmmsg handler, recording each datagram's peer address. + * @param bio Filter BIO the datagrams are read through. + * @param msg Array receiving the messages. + * @param stride Size of one entry in @p msg. + * @param num_msg Capacity of @p msg. + * @param flags Flags passed through to the underlying BIO. + * @param msgs_processed Out: how many messages were received. + * @return 1 on success, 0 on failure. + */ +int h3q_peer_addr_bio_recvmmsg(BIO* bio, BIO_MSG* msg, size_t stride, size_t num_msg, uint64_t flags, size_t* msgs_processed); + +/** + * BIO_meth_set_destroy handler, clearing the datagram queue. + * @param bio Filter BIO being destroyed. + * @return 1 on success. + */ +int h3q_peer_addr_bio_destroy(BIO* bio); + +/** + * SSL ex_data free callback for a connection's stored peer address. + * @param parent Object the ex_data belongs to. + * @param ptr The stored BIO_ADDR, freed here. + * @param ad ex_data store being torn down. + * @param idx Index the value was stored at. + * @param argl Long argument registered with the index. + * @param argp Pointer argument registered with the index. + */ +void h3q_peer_addr_ex_free(void* parent, void* ptr, CRYPTO_EX_DATA* ad, int idx, long argl, void* argp); + +/** + * SSL_CTX new-pending-conn callback, attaching the peer address to @p conn. + * @param ctx Context the connection was created on. + * @param conn Newly pending connection. + * @param arg The owning h3q_engine. + * @return 1 to accept the connection, 0 to reject it. + */ +int h3q_new_pending_conn_cb(SSL_CTX* ctx, SSL* conn, void* arg); + +#endif /* H3Q_DETAIL_OSSL_ADDR_H */ diff --git a/modules/http3/include/quic/h3q_conn.h b/modules/http3/include/quic/h3q_conn.h index ad6874dc757..1a86b013a5e 100644 --- a/modules/http3/include/quic/h3q_conn.h +++ b/modules/http3/include/quic/h3q_conn.h @@ -112,9 +112,11 @@ int h3q_conn_shutdown(h3q_conn* conn, int is_rapid, uint64_t app_error, const ch /** * Close a connection the server will not serve with CONNECTION_REFUSED, so * the client fails at once instead of waiting out its idle timeout. - * @param conn Connection to refuse; it still has to be freed. + * @param engine Engine the connection was accepted from. + * @param conn Connection to refuse; the engine takes it over and frees it + * once the close is done, so the caller must not free it. */ -void h3q_conn_refuse(h3q_conn* conn); +void h3q_conn_refuse(h3q_engine* engine, h3q_conn* conn); /** * Release a connection handle. diff --git a/modules/http3/quic/detail/h3q_ossl_addr.c b/modules/http3/quic/detail/h3q_ossl_addr.c new file mode 100644 index 00000000000..3e4c527e74a --- /dev/null +++ b/modules/http3/quic/detail/h3q_ossl_addr.c @@ -0,0 +1,326 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef _WIN32 +#include +#include +#endif + +#include +#include + +#include +#include +#include + +#include "h3_os.h" +#include "quic/detail/h3q_ossl_addr.h" + +#ifdef H3Q_DCID_DEBUG + +static void h3q_hex(char* out, const unsigned char* data, size_t len) +{ + size_t i; + for (i = 0; i < len; i++) + sprintf(out + i * 2, "%02x", data[i]); + out[len * 2] = '\0'; +} + +static void h3q_trace_quic(const char* direction, const unsigned char* data, size_t data_len) +{ + unsigned char dcid[20]; + unsigned char scid[20]; + size_t dcid_len = 0; + size_t scid_len = 0; + size_t off; + char dcid_hex[41]; + char scid_hex[41]; + FILE* f; + + if (data_len < 1) + return; + + if (data[0] & 0x80) { + /* Long header: [flags(1)][version(4)][dcid_len(1)][dcid...][scid_len(1)][scid...] */ + if (data_len < 6) + return; + dcid_len = data[5]; + if (dcid_len > 20 || data_len < 6 + dcid_len) + return; + memcpy(dcid, data + 6, dcid_len); + + off = 6 + dcid_len; + if (data_len > off) { + scid_len = data[off]; + if (scid_len <= 20 && data_len >= off + 1 + scid_len) + memcpy(scid, data + off + 1, scid_len); + else + scid_len = 0; + } + + h3q_hex(dcid_hex, dcid, dcid_len); + h3q_hex(scid_hex, scid, scid_len); + f = fopen("/tmp/h3q_dcid.log", "a"); + if (f) { + fprintf(f, "[h3q] %s long DCID(%zu): %s SCID(%zu): %s\n", + direction, dcid_len, dcid_hex, scid_len, scid_hex); + fclose(f); + } + } else { + /* Short header: [flags(1)][dcid...] */ + dcid_len = 8; + if (data_len < 1 + dcid_len) + return; + memcpy(dcid, data + 1, dcid_len); + + h3q_hex(dcid_hex, dcid, dcid_len); + f = fopen("/tmp/h3q_dcid.log", "a"); + if (f) { + fprintf(f, "[h3q] %s short DCID(%zu): %s\n", + direction, dcid_len, dcid_hex); + fclose(f); + } + } +} + +#endif /* H3Q_DCID_DEBUG */ + +struct h3q_datagram +{ + unsigned char* data; + size_t data_len; + BIO_ADDR* peer; + BIO_ADDR* local; + h3q_datagram* next; +}; + +static void h3q_datagram_free(h3q_datagram* item) +{ + OPENSSL_free(item->data); + BIO_ADDR_free(item->peer); + BIO_ADDR_free(item->local); + OPENSSL_free(item); +} + +static void h3q_queue_drop_head(h3q_engine* engine) +{ + h3q_datagram* item = engine->peer_rx_head; + engine->peer_rx_head = item->next; + if (!engine->peer_rx_head) + { + engine->peer_rx_tail = NULL; + } + h3q_datagram_free(item); +} + +void h3q_peer_addr_queue_clear(h3q_engine* engine) +{ + h3q_datagram* item = engine->peer_rx_head; + while (item) + { + h3q_datagram* next = item->next; + h3q_datagram_free(item); + item = next; + } + engine->peer_rx_head = NULL; + engine->peer_rx_tail = NULL; +} + +static int h3q_queue_fill(h3q_engine* engine, BIO_MSG* msg, size_t stride, size_t count) +{ + for (size_t i = 0; i < count; i++) + { + BIO_MSG* source = (BIO_MSG*)((unsigned char*)msg + i * stride); + h3q_datagram* item = OPENSSL_zalloc(sizeof(*item)); + if (!item || !source->data || source->data_len == 0) + { + OPENSSL_free(item); + h3q_peer_addr_queue_clear(engine); + return 0; + } +#ifdef H3Q_DCID_DEBUG + h3q_trace_quic("RECV", source->data, source->data_len); +#endif + item->data = OPENSSL_memdup(source->data, source->data_len); + item->data_len = source->data_len; + item->peer = source->peer ? BIO_ADDR_dup(source->peer) : NULL; + item->local = source->local ? BIO_ADDR_dup(source->local) : NULL; + if (!item->data || (source->peer && !item->peer) || (source->local && !item->local)) + { + OPENSSL_free(item->data); + BIO_ADDR_free(item->peer); + BIO_ADDR_free(item->local); + OPENSSL_free(item); + h3q_peer_addr_queue_clear(engine); + return 0; + } + if (engine->peer_rx_tail) + { + engine->peer_rx_tail->next = item; + } + else + { + engine->peer_rx_head = item; + } + engine->peer_rx_tail = item; + } + return 1; +} + +static int h3q_queue_pop(h3q_engine* engine, BIO_MSG* msg) +{ + h3q_datagram* item = engine->peer_rx_head; + if (!item || !msg || !msg->data) + { + return 0; + } + if (msg->data_len < item->data_len) + { + /* Drop it, or the queue head never clears and the pump spins. */ + h3q_queue_drop_head(engine); + return 0; + } + memcpy(msg->data, item->data, item->data_len); + msg->data_len = item->data_len; + if (msg->peer && item->peer) + { + BIO_ADDR_copy(msg->peer, item->peer); + } + if (msg->local && item->local) + { + BIO_ADDR_copy(msg->local, item->local); + } + h3q_queue_drop_head(engine); + return 1; +} + +long h3q_peer_addr_bio_ctrl(BIO* bio, int cmd, long num, void* ptr) +{ + BIO* next = BIO_next(bio); + return next ? BIO_ctrl(next, cmd, num, ptr) : 0; +} + +int h3q_peer_addr_bio_sendmmsg(BIO* bio, BIO_MSG* msg, size_t stride, size_t num_msg, uint64_t flags, size_t* msgs_processed) +{ + BIO* next = BIO_next(bio); + +#ifdef H3Q_DCID_DEBUG + { + size_t i; + for (i = 0; i < num_msg; i++) { + BIO_MSG* m = (BIO_MSG*)((unsigned char*)msg + i * stride); + if (m->data && m->data_len > 0) + h3q_trace_quic("SEND", m->data, m->data_len); + } + } +#endif + + return next ? BIO_sendmmsg(next, msg, stride, num_msg, flags, msgs_processed) : 0; +} + +int h3q_peer_addr_bio_recvmmsg(BIO* bio, BIO_MSG* msg, size_t stride, size_t num_msg, uint64_t flags, size_t* msgs_processed) +{ + h3q_engine* engine = BIO_get_data(bio); + BIO* next = BIO_next(bio); + size_t count; + + if (!engine || !next || !msg || !msgs_processed || num_msg == 0) + { + return 0; + } + + BIO_ADDR_clear(engine->current_peer_addr); + + if (!engine->peer_rx_head) + { + size_t received = 0; + int rv = BIO_recvmmsg(next, msg, stride, num_msg, flags, &received); + if (!rv || received == 0) + { + *msgs_processed = received; + return rv; + } + if (!h3q_queue_fill(engine, msg, stride, received)) + { + *msgs_processed = 0; + return 0; + } + } + + /* Pop from queue: batch short-header packets (existing connections); + * long-header packets go one at a time for peer-address capture. */ + count = 0; + while (count < num_msg && engine->peer_rx_head) + { + h3q_datagram* head = engine->peer_rx_head; + int is_long = (head->data_len > 0 && (head->data[0] & 0x80)); + + if (is_long && count > 0) + { + break; + } + + BIO_MSG* dst = (BIO_MSG*)((unsigned char*)msg + count * stride); + if (!h3q_queue_pop(engine, dst)) + { + break; + } + count++; + + if (is_long) + { + if (dst->peer) + { + BIO_ADDR_copy(engine->current_peer_addr, dst->peer); + } + break; + } + } + *msgs_processed = count; + return count > 0 ? 1 : 0; +} + +int h3q_peer_addr_bio_destroy(BIO* bio) +{ + h3q_engine* engine = BIO_get_data(bio); + if (engine) + { + h3q_peer_addr_queue_clear(engine); + } + return 1; +} + +void h3q_peer_addr_ex_free(void* parent H3_UNUSED, void* ptr, CRYPTO_EX_DATA* ad H3_UNUSED, int idx H3_UNUSED, long argl H3_UNUSED, void* argp H3_UNUSED) +{ + BIO_ADDR_free(ptr); +} + +int h3q_new_pending_conn_cb(SSL_CTX* ctx H3_UNUSED, SSL* conn, void* arg) +{ + h3q_engine* engine = arg; + if (!engine || engine->peer_addr_ex_index < 0 || BIO_ADDR_family(engine->current_peer_addr) == AF_UNSPEC) + { + return 1; + } + + BIO_ADDR* peer = BIO_ADDR_dup(engine->current_peer_addr); + if (!peer || !SSL_set_ex_data(conn, engine->peer_addr_ex_index, peer)) + { + BIO_ADDR_free(peer); + return 0; + } + return 1; +} diff --git a/modules/http3/quic/h3q_conn.c b/modules/http3/quic/h3q_conn.c index 68a21b5bcb1..10b1f22f81f 100644 --- a/modules/http3/quic/h3q_conn.c +++ b/modules/http3/quic/h3q_conn.c @@ -575,12 +575,14 @@ int h3q_conn_shutdown(h3q_conn* conn, int is_rapid, uint64_t app_error, const ch return is_rapid || conn->close_len == 0 || h3q_now() >= conn->close_until; } -void h3q_conn_refuse(h3q_conn* conn) +void h3q_conn_refuse(h3q_engine* engine, h3q_conn* conn) { ngtcp2_ccerr ccerr; + (void)engine; ngtcp2_ccerr_default(&ccerr); ngtcp2_ccerr_set_transport_error(&ccerr, NGTCP2_CONNECTION_REFUSED, NULL, 0); h3q_conn_close(conn, &ccerr); + h3q_conn_free(conn); /* the engine keeps the stored close to answer the client's retransmissions */ } void h3q_conn_free(h3q_conn* conn) diff --git a/modules/http3/quic/h3q_ossl.c b/modules/http3/quic/h3q_ossl.c new file mode 100644 index 00000000000..4a811ea1c3b --- /dev/null +++ b/modules/http3/quic/h3q_ossl.c @@ -0,0 +1,286 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef _WIN32 +#include +#include +#endif + +#include +#include + +#include +#include + +#include "h3_check.h" +#include "h3_os.h" +#include "quic/detail/h3q_ossl_addr.h" +#include "quic/detail/h3q_tls.h" +#include "quic/h3q.h" +#include "quic/h3q_conn.h" + +#define H3Q_PUMP_INNER_BUDGET 64 + +h3q_engine* h3q_engine_create(const h3q_config* cfg, int udp_fd, char* err, size_t errlen) +{ + CHECK(cfg); + h3q_engine* engine = calloc(1, sizeof(*engine)); + if (!engine) + { + h3q_tls_error(err, errlen, "allocating the engine failed"); + return NULL; + } + engine->peer_addr_ex_index = -1; + + if (!cfg->pool || apr_pool_create(&engine->pool, cfg->pool) != APR_SUCCESS) + { + h3q_tls_error(err, errlen, "allocating the engine pool failed"); + h3q_engine_destroy(engine); + return NULL; + } + + if (!cfg->ssl_ctx || !SSL_CTX_up_ref(cfg->ssl_ctx)) + { + h3q_tls_error(err, errlen, "no TLS context to serve from"); + h3q_engine_destroy(engine); + return NULL; + } + engine->ssl_ctx = cfg->ssl_ctx; + engine->idle_timeout_secs = cfg->idle_timeout_secs; + + BIO_METHOD* bm = BIO_meth_new(BIO_TYPE_FILTER | BIO_get_new_index(), "h3q_peer_addr"); + if (!bm) + { + h3q_tls_error(err, errlen, "BIO_meth_new failed"); + h3q_engine_destroy(engine); + return NULL; + } + engine->peer_addr_bio_method = bm; + /* An unset handler installs fine and then drops every datagram. */ + if (!BIO_meth_set_ctrl(bm, h3q_peer_addr_bio_ctrl) || !BIO_meth_set_sendmmsg(bm, h3q_peer_addr_bio_sendmmsg) || !BIO_meth_set_recvmmsg(bm, h3q_peer_addr_bio_recvmmsg) || !BIO_meth_set_destroy(bm, h3q_peer_addr_bio_destroy)) + { + h3q_tls_error(err, errlen, "installing the peer address BIO handlers failed"); + h3q_engine_destroy(engine); + return NULL; + } + + engine->current_peer_addr = BIO_ADDR_new(); + engine->peer_addr_ex_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, h3q_peer_addr_ex_free); + if (!engine->current_peer_addr || engine->peer_addr_ex_index < 0) + { + h3q_tls_error(err, errlen, "initializing peer address recovery failed"); + h3q_engine_destroy(engine); + return NULL; + } + + SSL_CTX_set_new_pending_conn_cb(engine->ssl_ctx, h3q_new_pending_conn_cb, engine); + + uint64_t listener_flags = cfg->address_validation ? 0 : (uint64_t)SSL_LISTENER_FLAG_NO_VALIDATE; + engine->ssl_listener = SSL_new_listener(engine->ssl_ctx, listener_flags); + if (!engine->ssl_listener) + { + h3q_tls_error(err, errlen, "SSL_new_listener failed"); + h3q_engine_destroy(engine); + return NULL; + } + + BIO* bio = BIO_new_dgram(udp_fd, BIO_NOCLOSE); + if (!bio) + { + h3q_tls_error(err, errlen, "BIO_new_dgram failed for fd=%d", udp_fd); + h3q_engine_destroy(engine); + return NULL; + } + + BIO* filter_bio = BIO_new(bm); + if (!filter_bio) + { + h3q_tls_error(err, errlen, "BIO_new(h3q_peer_addr) failed"); + BIO_free(bio); + h3q_engine_destroy(engine); + return NULL; + } + + BIO_set_data(filter_bio, engine); + bio = BIO_push(filter_bio, bio); + SSL_set_bio(engine->ssl_listener, bio, bio); + + if (!SSL_listen(engine->ssl_listener) || !SSL_set_blocking_mode(engine->ssl_listener, 0)) + { + h3q_tls_error(err, errlen, "SSL_listen failed"); + h3q_engine_destroy(engine); + return NULL; + } + + return engine; +} + +void h3q_engine_destroy(h3q_engine* engine) +{ + if (!engine) + { + return; + } + h3q_peer_addr_queue_clear(engine); + h3q_engine_reap_refused(engine, 1); + if (engine->ssl_listener) + { + SSL_free(engine->ssl_listener); + } + if (engine->current_peer_addr) + { + BIO_ADDR_free(engine->current_peer_addr); + } + if (engine->peer_addr_bio_method) + { + BIO_meth_free(engine->peer_addr_bio_method); + } + if (engine->ssl_ctx) + { + SSL_CTX_free(engine->ssl_ctx); + } + if (engine->pool) + { + apr_pool_destroy(engine->pool); + } + free(engine); +} + +int h3q_engine_pump(h3q_engine* engine) +{ + int rounds = 0; + int had_queued; + + if (!engine || !engine->ssl_listener) + { + return 0; + } + had_queued = (engine->peer_rx_head != NULL); + if (SSL_handle_events(engine->ssl_listener) != 1) + { + return -1; + } + while (engine->peer_rx_head && ++rounds < H3Q_PUMP_INNER_BUDGET) + { + if (SSL_handle_events(engine->ssl_listener) != 1) + { + return -1; + } + } + h3q_engine_reap_refused(engine, 0); + if (engine->peer_rx_head) + { + return 1; + } + return (had_queued || rounds > 0) ? 1 : 0; +} + +void h3q_engine_want(h3q_engine* engine, int* want_read, int* want_write, int* timeout_ms) +{ + if (!engine || !engine->ssl_listener) + { + *want_read = 0; + *want_write = 0; + *timeout_ms = 1000; + return; + } + *want_read = SSL_net_read_desired(engine->ssl_listener); + *want_write = SSL_net_write_desired(engine->ssl_listener); + + struct timeval tv = {0}; + int is_infinite = 0; + if (SSL_get_event_timeout(engine->ssl_listener, &tv, &is_infinite) && !is_infinite) + { + /* long is 32-bit on Windows, so tv_sec * 1000 overflows it. */ + int64_t ms = (int64_t)tv.tv_sec * 1000 + (int64_t)tv.tv_usec / 1000; + if (ms >= 0 && ms < (int64_t)*timeout_ms) + { + *timeout_ms = (int)ms; + } + } + /* A zero would spin the caller's wait when a timer reports as due. */ + if (*timeout_ms < 1) + { + *timeout_ms = 1; + } +} + +h3q_conn* h3q_engine_accept_conn(h3q_engine* engine) +{ + if (!engine || !engine->ssl_listener) + { + return NULL; + } + SSL* conn; + while ((conn = SSL_accept_connection(engine->ssl_listener, SSL_ACCEPT_CONNECTION_NO_BLOCK)) != NULL) + { + if (h3q_conn_prepare((h3q_conn*)conn, engine->idle_timeout_secs)) + { + return (h3q_conn*)conn; + } + SSL_free(conn); + } + return NULL; +} + +int h3q_engine_peer_addr(h3q_engine* engine, h3q_conn* conn, struct sockaddr_storage* addr, socklen_t* addr_len) +{ + /* Report it: losing a client address is not worth aborting the child. */ + if (!engine || !conn || !addr || !addr_len) + { + return 0; + } + if (engine->peer_addr_ex_index < 0) + { + return 0; + } + + /* Recorded by h3q_new_pending_conn_cb when the connection first appeared. */ + const BIO_ADDR* peer = SSL_get_ex_data((SSL*)conn, engine->peer_addr_ex_index); + if (!peer) + { + return 0; + } + + memset(addr, 0, sizeof(*addr)); + size_t rawlen = 0; + int family = BIO_ADDR_family(peer); + if (family == AF_INET) + { + struct sockaddr_in* sin = (struct sockaddr_in*)addr; + if (!BIO_ADDR_rawaddress(peer, &sin->sin_addr, &rawlen) || rawlen != sizeof(sin->sin_addr)) + { + return 0; + } + sin->sin_family = AF_INET; + sin->sin_port = BIO_ADDR_rawport(peer); + *addr_len = sizeof(*sin); + return 1; + } + if (family == AF_INET6) + { + struct sockaddr_in6* sin6 = (struct sockaddr_in6*)addr; + if (!BIO_ADDR_rawaddress(peer, &sin6->sin6_addr, &rawlen) || rawlen != sizeof(sin6->sin6_addr)) + { + return 0; + } + sin6->sin6_family = AF_INET6; + sin6->sin6_port = BIO_ADDR_rawport(peer); + *addr_len = sizeof(*sin6); + return 1; + } + return 0; +} diff --git a/modules/http3/quic/h3q_ossl_conn.c b/modules/http3/quic/h3q_ossl_conn.c new file mode 100644 index 00000000000..ee0ac816c5b --- /dev/null +++ b/modules/http3/quic/h3q_ossl_conn.c @@ -0,0 +1,265 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef _WIN32 +#include +#include +#endif + +#include +#include +#include +#include + +#include +#include + +#include "h3_check.h" +#include "quic/detail/h3q_ossl_addr.h" +#include "quic/h3q_conn.h" + +/* Stream modes, incoming-stream policy and idle timeout, applied to a freshly accepted connection. */ +int h3q_conn_prepare(h3q_conn* conn, uint32_t idle_timeout_secs) +{ + SSL* ssl_conn = (SSL*)conn; + if (!ssl_conn || !SSL_set_blocking_mode(ssl_conn, 0)) + { + return 0; + } + SSL_set_default_stream_mode(ssl_conn, SSL_DEFAULT_STREAM_MODE_NONE); + SSL_set_incoming_stream_policy(ssl_conn, SSL_INCOMING_STREAM_POLICY_ACCEPT, 0); + SSL_set_generic_value_uint(ssl_conn, SSL_VALUE_QUIC_IDLE_TIMEOUT, (uint64_t)idle_timeout_secs * 1000); + return 1; +} + +/* OpenSSL copies written bytes and reports no per-stream acknowledgements. */ +void h3q_conn_set_user(h3q_conn* conn, void* user) +{ + (void)conn; + (void)user; +} + +/* OpenSSL's QUIC server drops 0-RTT packets. */ +int h3q_conn_has_early_data(h3q_conn* conn) +{ + (void)conn; + return 0; +} + +/* OpenSSL manages the peer's stream credit itself and does not report it. */ +uint64_t h3q_conn_max_remote_streams_bidi(h3q_conn* conn) +{ + (void)conn; + return 0; +} + +/* OpenSSL reports no per-connection activity: always treat the connection as touched. */ +int h3q_conn_take_activity(h3q_conn* conn) +{ + (void)conn; + return 1; +} + +h3q_stream* h3q_conn_open_uni_stream(h3q_conn* conn, int64_t* out_id) +{ + SSL* ssl_conn = (SSL*)conn; + CHECK(ssl_conn); + CHECK(out_id); + SSL* stream = SSL_new_stream(ssl_conn, SSL_STREAM_FLAG_UNI); + if (!stream) + { + return NULL; + } + *out_id = (int64_t)SSL_get_stream_id(stream); + return (h3q_stream*)stream; +} + +h3q_stream* h3q_conn_accept_stream(h3q_conn* conn) +{ + SSL* ssl_conn = (SSL*)conn; + if (!ssl_conn) + { + return NULL; + } + return (h3q_stream*)SSL_accept_stream(ssl_conn, SSL_ACCEPT_STREAM_NO_BLOCK); +} + +int h3q_conn_is_handshake_done(h3q_conn* conn) +{ + SSL* ssl_conn = (SSL*)conn; + return ssl_conn ? SSL_is_init_finished(ssl_conn) : 0; +} + +int h3q_conn_tls_info(h3q_conn* conn, h3q_tls_info* out) +{ + SSL* ssl_conn = (SSL*)conn; + if (!ssl_conn || !out) + { + return 0; + } + const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_conn); + if (!cipher) + { + return 0; + } + int alg_bits = 0; + out->cipher_bits = SSL_CIPHER_get_bits(cipher, &alg_bits); + out->cipher_alg_bits = alg_bits; + out->cipher = SSL_CIPHER_get_name(cipher); + const char* version = SSL_get_version(ssl_conn); + out->protocol = (version && strncmp(version, "TLS", 3) == 0) ? version : "TLSv1.3"; + out->resumed = SSL_session_reused(ssl_conn) ? 1u : 0u; + return 1; +} + +int h3q_conn_is_closed(h3q_conn* conn) +{ + SSL* ssl_conn = (SSL*)conn; + return ssl_conn ? (SSL_get_shutdown(ssl_conn) != 0) : 1; +} + +int h3q_conn_shutdown(h3q_conn* conn, int is_rapid, uint64_t app_error, const char* reason) +{ + SSL* ssl_conn = (SSL*)conn; + if (!ssl_conn) + { + return 1; + } + uint64_t flags = is_rapid ? (uint64_t)SSL_SHUTDOWN_FLAG_RAPID : 0; + int ret = 0; + if (reason) + { + SSL_SHUTDOWN_EX_ARGS args = {.quic_error_code = app_error, .quic_reason = reason}; + ret = SSL_shutdown_ex(ssl_conn, flags, &args, sizeof(args)); + } + else if (flags != 0) + { + SSL_SHUTDOWN_EX_ARGS args = {0}; + ret = SSL_shutdown_ex(ssl_conn, flags, &args, sizeof(args)); + } + else + { + ret = SSL_shutdown(ssl_conn); + } + + if (ret == 1) + { + return 1; + } + if (ret < 0) + { + int err = SSL_get_error(ssl_conn, ret); + if (err != SSL_ERROR_WANT_READ && err != SSL_ERROR_WANT_WRITE) + { + return 1; + } + } + return 0; +} + +/* How long a refused connection waits for its handshake to finish before it is closed anyway. */ +#define H3Q_REFUSE_HANDSHAKE_WAIT_SECS 5 + +/* OpenSSL cannot send the CONNECTION_REFUSED transport error, and its CONNECTION_CLOSE is sent in the packet type of + * the lowest encryption level it still holds: a client which got the server's handshake flight has discarded the keys + * for that already. So the close is held back until the handshake is done and goes out as an application error in a + * 1-RTT packet, which every client can read. The engine keeps the connection until then and through the closing + * period. */ +void h3q_conn_refuse(h3q_engine* engine, h3q_conn* conn) +{ + SSL* ssl_conn = (SSL*)conn; + h3q_refused* refused; + if (!ssl_conn) + { + return; + } + refused = engine->refused_free; + if (refused) + { + engine->refused_free = refused->next; + memset(refused, 0, sizeof(*refused)); + } + else + { + refused = apr_pcalloc(engine->pool, sizeof(*refused)); + } + refused->ssl_conn = ssl_conn; + refused->refused_at = apr_time_now(); + refused->next = engine->refused_head; + engine->refused_head = refused; +} + +void h3q_engine_reap_refused(h3q_engine* engine, int all) +{ + h3q_refused** slot = &engine->refused_head; + apr_time_t now = apr_time_now(); + while (*slot) + { + h3q_refused* refused = *slot; + SSL_SHUTDOWN_EX_ARGS args = {.quic_error_code = 0x107 /* H3_EXCESSIVE_LOAD */, .quic_reason = "refused"}; + int done = all; + if (!done && !refused->closing && (SSL_is_init_finished(refused->ssl_conn) || now - refused->refused_at >= apr_time_from_sec(H3Q_REFUSE_HANDSHAKE_WAIT_SECS))) + { + refused->closing = 1; + } + if (!done && refused->closing) + { + done = (SSL_shutdown_ex(refused->ssl_conn, SSL_SHUTDOWN_FLAG_RAPID, &args, sizeof(args)) == 1); + } + if (done) + { + *slot = refused->next; + SSL_free(refused->ssl_conn); + refused->next = engine->refused_free; + engine->refused_free = refused; + } + else + { + slot = &refused->next; + } + } +} + +void h3q_conn_free(h3q_conn* conn) +{ + if (conn) + { + SSL_free((SSL*)conn); + } +} + +void h3q_conn_close_reason(h3q_conn* conn, char* buf, size_t buflen) +{ + if (!buf || buflen == 0) + { + return; + } + buf[0] = '\0'; + + char errbuf[H3Q_ERRLEN] = {0}; + ERR_error_string_n(ERR_peek_last_error(), errbuf, sizeof(errbuf)); + + SSL_CONN_CLOSE_INFO cci = {0}; + if (conn && SSL_get_conn_close_info((SSL*)conn, &cci, sizeof(cci))) + { + const char* origin = (cci.flags & SSL_CONN_CLOSE_FLAG_LOCAL) ? "local" : "remote"; + const char* layer = (cci.flags & SSL_CONN_CLOSE_FLAG_TRANSPORT) ? "transport" : "app"; + const char* reason = cci.reason ? cci.reason : ""; + snprintf(buf, buflen, "%s %s err=0x%llx frame=0x%llx reason=\"%.*s\" (%s)", origin, layer, (unsigned long long)cci.error_code, (unsigned long long)cci.frame_type, (int)cci.reason_len, reason, errbuf); + return; + } + snprintf(buf, buflen, "%s", errbuf); +} diff --git a/modules/http3/quic/h3q_ossl_stream.c b/modules/http3/quic/h3q_ossl_stream.c new file mode 100644 index 00000000000..2a6ed3b9a20 --- /dev/null +++ b/modules/http3/quic/h3q_ossl_stream.c @@ -0,0 +1,145 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef _WIN32 +#include +#include +#endif + +#include + +#include "quic/h3q_stream.h" + +h3q_write_result h3q_stream_write(h3q_stream* st, const h3q_vec* vec, size_t nvec, int fin) +{ + SSL* ssl = (SSL*)st; + h3q_write_result res = {0}; + size_t expected = 0; + for (size_t k = 0; k < nvec; k++) + { + expected += vec[k].len; + } + for (size_t k = 0; k < nvec; k++) + { + size_t w = 0; + int wrv = SSL_write_ex(ssl, vec[k].base, vec[k].len, &w); + if (wrv <= 0) + { + if (SSL_get_error(ssl, wrv) == SSL_ERROR_WANT_WRITE) + { + res.blocked = 1; + } + else + { + res.broken = 1; + } + break; + } + res.accepted += w; + if (w < vec[k].len) + { + res.blocked = 1; + break; + } + } + if (fin && !res.blocked && !res.broken && res.accepted == expected) + { + SSL_stream_conclude(ssl, 0); + } + return res; +} + +int h3q_stream_is_write_blocked(h3q_stream* st) +{ + SSL* ssl = (SSL*)st; + uint64_t avail = 0; + if (ssl && SSL_get_generic_value_uint(ssl, SSL_VALUE_STREAM_WRITE_BUF_AVAIL, &avail) == 1 && avail == 0) + { + return 1; + } + return 0; +} + +int h3q_stream_read(h3q_stream* st, unsigned char* buf, size_t read_size, size_t* nread, int* fin) +{ + SSL* ssl = (SSL*)st; + *fin = 0; + int rv = SSL_read_ex(ssl, buf, read_size, nread); + if (rv == 1 && *nread > 0) + { + return 1; + } + if (rv == 1 || SSL_get_error(ssl, rv) == SSL_ERROR_ZERO_RETURN) + { + *fin = 1; + } + return 0; +} + +void h3q_stream_is_read_finished(h3q_stream* st, int* read_finished, int* write_finished) +{ + SSL* ssl = (SSL*)st; + int rstate = SSL_get_stream_read_state(ssl); + *read_finished = (rstate == SSL_STREAM_STATE_FINISHED || rstate == SSL_STREAM_STATE_RESET_REMOTE || rstate == SSL_STREAM_STATE_CONN_CLOSED); + int wstate = SSL_STREAM_STATE_FINISHED; + if (rstate != SSL_STREAM_STATE_CONN_CLOSED && rstate != SSL_STREAM_STATE_RESET_REMOTE) + { + wstate = SSL_get_stream_write_state(ssl); + } + /* A peer-initiated unidirectional stream has no send side. */ + *write_finished = (wstate == SSL_STREAM_STATE_FINISHED || wstate == SSL_STREAM_STATE_RESET_LOCAL || wstate == SSL_STREAM_STATE_WRONG_DIR); +} + +int h3q_stream_is_read_reset(h3q_stream* st) +{ + return st ? (SSL_get_stream_read_state((SSL*)st) == SSL_STREAM_STATE_RESET_REMOTE) : 0; +} + +int h3q_stream_is_early(h3q_stream* st) +{ + (void)st; + return 0; +} + +void h3q_stream_reset(h3q_stream* st, uint64_t err) +{ + if (!st) + { + return; + } + SSL_STREAM_RESET_ARGS args = {err}; + SSL_stream_reset((SSL*)st, &args, sizeof(args)); +} + +/* OpenSSL has no explicit STOP_SENDING: it sends one when a stream whose read side is not finished is freed. */ +void h3q_stream_abort(h3q_stream* st, uint64_t err) +{ + h3q_stream_reset(st, err); +} + +void h3q_stream_free(h3q_stream* st) +{ + if (st) + { + SSL_free((SSL*)st); + } +} + +int64_t h3q_stream_id(h3q_stream* st) +{ + SSL* ssl = (SSL*)st; + return ssl ? (int64_t)SSL_get_stream_id(ssl) : -1; +} diff --git a/test/modules/http3/test_113_refuse.py b/test/modules/http3/test_113_refuse.py index 290d2ccccf5..696733f159e 100644 --- a/test/modules/http3/test_113_refuse.py +++ b/test/modules/http3/test_113_refuse.py @@ -6,6 +6,7 @@ from .env import H3Conf QUIC_CONNECTION_REFUSED = 0x2 +H3_EXCESSIVE_LOAD = 0x107 class TestConnectionLimit: @@ -37,5 +38,7 @@ def probe(): env.httpd_error_log.ignore_recent( matches=[r'.*dropping QUIC connection: at H3MaxConnections limit.*']) assert second.terminated is not None, f"{second!r}" - assert second.terminated.error_code == QUIC_CONNECTION_REFUSED, f"{second!r}" + # OpenSSL cannot send the transport error, it closes with an application one + expected = H3_EXCESSIVE_LOAD if env.h3_ossl_backend else QUIC_CONNECTION_REFUSED + assert second.terminated.error_code == expected, f"{second!r}" assert elapsed < 5, f"refused connection took {elapsed:.1f}s to fail"