Path: blob/main/crypto/openssl/demos/http3/ossl-nghttp3-demo-server.c
39536 views
/*1* Copyright 2024-2025 The OpenSSL Project Authors. All Rights Reserved.2*3* Licensed under the Apache License 2.0 (the "License"). You may not use4* this file except in compliance with the License. You can obtain a copy5* in the file LICENSE in the source distribution or at6* https://www.openssl.org/source/license.html7*/8#include <assert.h>9#include <netinet/in.h>10#include <nghttp3/nghttp3.h>11#include <openssl/err.h>12#include <openssl/quic.h>13#include <openssl/ssl.h>14#include <unistd.h>15#include <sys/stat.h>16#include <fcntl.h>17#include <sys/socket.h>1819#ifndef PATH_MAX20# define PATH_MAX 25521#endif2223#define nghttp3_arraylen(A) (sizeof(A) / sizeof(*(A)))2425/* The crappy test wants 20 bytes */26#define NULL_PAYLOAD "12345678901234567890"27static uint8_t *nulldata = (uint8_t *) NULL_PAYLOAD;28static size_t nulldata_sz = sizeof(NULL_PAYLOAD) - 1;2930/* The nghttp3 variable we need in the main part and read_from_ssl_ids */31static nghttp3_settings settings;32static const nghttp3_mem *mem;33static nghttp3_callbacks callbacks = {0};3435/* 3 streams created by the server and 4 by the client (one is bidi) */36struct ssl_id {37SSL *s; /* the stream openssl uses in SSL_read(), SSL_write etc */38uint64_t id; /* the stream identifier the nghttp3 uses */39int status; /* 0 or one the below status and origin */40};41/* status and origin of the streams the possible values are: */42#define CLIENTUNIOPEN 0x01 /* unidirectional open by the client (2, 6 and 10) */43#define CLIENTCLOSED 0x02 /* closed by the client */44#define CLIENTBIDIOPEN 0x04 /* bidirectional open by the client (something like 0, 4, 8 ...) */45#define SERVERUNIOPEN 0x08 /* unidirectional open by the server (3, 7 and 11) */46#define SERVERCLOSED 0x10 /* closed by the server (us) */47#define TOBEREMOVED 0x20 /* marked for removing in read_from_ssl_ids, */48/* it will be removed after processing all events */49#define ISLISTENER 0x40 /* the stream is a listener from SSL_new_listener() */50#define ISCONNECTION 0x80 /* the stream is a connection from SSL_accept_connection() */5152#define MAXSSL_IDS 2053#define MAXURL 2555455struct h3ssl {56struct ssl_id ssl_ids[MAXSSL_IDS];57int end_headers_received; /* h3 header received call back called */58int datadone; /* h3 has given openssl all the data of the response */59int has_uni; /* we have the 3 uni directional stream needed */60int close_done; /* connection begins terminating EVENT_EC */61int close_wait; /* we are waiting for a close or a new request */62int done; /* connection terminated EVENT_ECD, after EVENT_EC */63int new_conn; /* a new connection has been received */64int received_from_two; /* workaround for -607 on nghttp3_conn_read_stream on stream 2 */65int restart; /* new request/response cycle started */66uint64_t id_bidi; /* the id of the stream used to read request and send response */67char *fileprefix; /* prefix of the directory to fetch files from */68char url[MAXURL]; /* url to serve the request */69uint8_t *ptr_data; /* pointer to the data to send */70size_t ldata; /* amount of bytes to send */71int offset_data; /* offset to next data to send */72};7374static void make_nv(nghttp3_nv *nv, const char *name, const char *value)75{76nv->name = (uint8_t *)name;77nv->value = (uint8_t *)value;78nv->namelen = strlen(name);79nv->valuelen = strlen(value);80nv->flags = NGHTTP3_NV_FLAG_NONE;81}8283static void init_ids(struct h3ssl *h3ssl)84{85struct ssl_id *ssl_ids;86int i;87char *prior_fileprefix = h3ssl->fileprefix;8889if (h3ssl->ptr_data != NULL && h3ssl->ptr_data != nulldata)90free(h3ssl->ptr_data);9192memset(h3ssl, 0, sizeof(struct h3ssl));9394ssl_ids = h3ssl->ssl_ids;95for (i = 0; i < MAXSSL_IDS; i++)96ssl_ids[i].id = UINT64_MAX;97h3ssl->id_bidi = UINT64_MAX;9899/* restore the fileprefix */100h3ssl->fileprefix = prior_fileprefix;101}102103static void reuse_h3ssl(struct h3ssl *h3ssl)104{105h3ssl->end_headers_received = 0;106h3ssl->datadone = 0;107h3ssl->close_done = 0;108h3ssl->close_wait = 0;109h3ssl->done = 0;110memset(h3ssl->url, '\0', sizeof(h3ssl->url));111if (h3ssl->ptr_data != NULL && h3ssl->ptr_data != nulldata)112free(h3ssl->ptr_data);113h3ssl->ptr_data = NULL;114h3ssl->offset_data = 0;115h3ssl->ldata = 0;116}117118static void add_id_status(uint64_t id, SSL *ssl, struct h3ssl *h3ssl, int status)119{120struct ssl_id *ssl_ids;121int i;122123ssl_ids = h3ssl->ssl_ids;124for (i = 0; i < MAXSSL_IDS; i++) {125if (ssl_ids[i].s == NULL) {126ssl_ids[i].s = ssl;127ssl_ids[i].id = id;128ssl_ids[i].status = status;129return;130}131}132printf("Oops too many streams to add!!!\n");133exit(1);134}135static void add_id(uint64_t id, SSL *ssl, struct h3ssl *h3ssl)136{137add_id_status(id, ssl, h3ssl, 0);138}139140/* Add listener and connection */141static void add_ids_listener(SSL *ssl, struct h3ssl *h3ssl)142{143add_id_status(UINT64_MAX, ssl, h3ssl, ISLISTENER);144}145static void add_ids_connection(struct h3ssl *h3ssl, SSL *ssl)146{147add_id_status(UINT64_MAX, ssl, h3ssl, ISCONNECTION);148}149static SSL *get_ids_connection(struct h3ssl *h3ssl)150{151struct ssl_id *ssl_ids;152int i;153154ssl_ids = h3ssl->ssl_ids;155for (i = 0; i < MAXSSL_IDS; i++) {156if (ssl_ids[i].status & ISCONNECTION) {157printf("get_ids_connection\n");158return ssl_ids[i].s;159}160}161return NULL;162}163static void replace_ids_connection(struct h3ssl *h3ssl, SSL *oldstream, SSL *newstream)164{165struct ssl_id *ssl_ids;166int i;167168ssl_ids = h3ssl->ssl_ids;169for (i = 0; i < MAXSSL_IDS; i++) {170if (ssl_ids[i].status & ISCONNECTION && ssl_ids[i].s == oldstream) {171printf("replace_ids_connection\n");172ssl_ids[i].s = newstream;173}174}175}176177/* remove the ids marked for removal */178static void remove_marked_ids(struct h3ssl *h3ssl)179{180struct ssl_id *ssl_ids;181int i;182183ssl_ids = h3ssl->ssl_ids;184for (i = 0; i < MAXSSL_IDS; i++) {185if (ssl_ids[i].status & TOBEREMOVED) {186printf("remove_id %llu\n", (unsigned long long) ssl_ids[i].id);187SSL_free(ssl_ids[i].s);188ssl_ids[i].s = NULL;189ssl_ids[i].id = UINT64_MAX;190ssl_ids[i].status = 0;191return;192}193}194}195196/* add the status bytes to the status */197static void set_id_status(uint64_t id, int status, struct h3ssl *h3ssl)198{199struct ssl_id *ssl_ids;200int i;201202ssl_ids = h3ssl->ssl_ids;203for (i = 0; i < MAXSSL_IDS; i++) {204if (ssl_ids[i].id == id) {205printf("set_id_status: %llu to %d\n", (unsigned long long) ssl_ids[i].id, status);206ssl_ids[i].status = ssl_ids[i].status | status;207return;208}209}210printf("Oops can't set status, can't find stream!!!\n");211assert(0);212}213static int get_id_status(uint64_t id, struct h3ssl *h3ssl)214{215struct ssl_id *ssl_ids;216int i;217218ssl_ids = h3ssl->ssl_ids;219for (i = 0; i < MAXSSL_IDS; i++) {220if (ssl_ids[i].id == id) {221printf("get_id_status: %llu to %d\n",222(unsigned long long) ssl_ids[i].id, ssl_ids[i].status);223return ssl_ids[i].status;224}225}226printf("Oops can't get status, can't find stream!!!\n");227assert(0);228return -1;229}230231/* check that all streams opened by the client are closed */232static int are_all_clientid_closed(struct h3ssl *h3ssl)233{234struct ssl_id *ssl_ids;235int i;236237ssl_ids = h3ssl->ssl_ids;238for (i = 0; i < MAXSSL_IDS; i++) {239if (ssl_ids[i].id == UINT64_MAX)240continue;241printf("are_all_clientid_closed: %llu status %d : %d\n",242(unsigned long long) ssl_ids[i].id, ssl_ids[i].status, CLIENTUNIOPEN | CLIENTCLOSED);243if (ssl_ids[i].status & CLIENTUNIOPEN) {244if (ssl_ids[i].status & CLIENTCLOSED) {245printf("are_all_clientid_closed: %llu closed\n",246(unsigned long long) ssl_ids[i].id);247SSL_free(ssl_ids[i].s);248ssl_ids[i].s = NULL;249ssl_ids[i].id = UINT64_MAX;250continue;251}252printf("are_all_clientid_closed: %llu open\n", (unsigned long long) ssl_ids[i].id);253return 0;254}255}256return 1;257}258259/* free all the ids except listener and connection */260static void close_all_ids(struct h3ssl *h3ssl)261{262struct ssl_id *ssl_ids;263int i;264265ssl_ids = h3ssl->ssl_ids;266for (i = 0; i < MAXSSL_IDS; i++) {267if (ssl_ids[i].id == UINT64_MAX)268continue;269SSL_free(ssl_ids[i].s);270ssl_ids[i].s = NULL;271ssl_ids[i].id = UINT64_MAX;272}273}274275static int on_recv_header(nghttp3_conn *conn, int64_t stream_id, int32_t token,276nghttp3_rcbuf *name, nghttp3_rcbuf *value,277uint8_t flags, void *user_data,278void *stream_user_data)279{280nghttp3_vec vname, vvalue;281struct h3ssl *h3ssl = (struct h3ssl *)user_data;282283/* Received a single HTTP header. */284vname = nghttp3_rcbuf_get_buf(name);285vvalue = nghttp3_rcbuf_get_buf(value);286287fwrite(vname.base, vname.len, 1, stdout);288fprintf(stdout, ": ");289fwrite(vvalue.base, vvalue.len, 1, stdout);290fprintf(stdout, "\n");291292if (token == NGHTTP3_QPACK_TOKEN__PATH) {293int len = (((vvalue.len) < (MAXURL)) ? (vvalue.len) : (MAXURL));294295memset(h3ssl->url, 0, sizeof(h3ssl->url));296if (vvalue.base[0] == '/') {297if (vvalue.base[1] == '\0') {298strncpy(h3ssl->url, "index.html", MAXURL);299} else {300memcpy(h3ssl->url, vvalue.base + 1, len - 1);301h3ssl->url[len - 1] = '\0';302}303} else {304memcpy(h3ssl->url, vvalue.base, len);305}306}307308return 0;309}310311static int on_end_headers(nghttp3_conn *conn, int64_t stream_id, int fin,312void *user_data, void *stream_user_data)313{314struct h3ssl *h3ssl = (struct h3ssl *)user_data;315316fprintf(stderr, "on_end_headers!\n");317h3ssl->end_headers_received = 1;318return 0;319}320321static int on_recv_data(nghttp3_conn *conn, int64_t stream_id,322const uint8_t *data, size_t datalen,323void *conn_user_data, void *stream_user_data)324{325fprintf(stderr, "on_recv_data! %ld\n", (unsigned long)datalen);326fprintf(stderr, "on_recv_data! %.*s\n", (int)datalen, data);327return 0;328}329330static int on_end_stream(nghttp3_conn *h3conn, int64_t stream_id,331void *conn_user_data, void *stream_user_data)332{333struct h3ssl *h3ssl = (struct h3ssl *)conn_user_data;334335printf("on_end_stream!\n");336h3ssl->done = 1;337return 0;338}339340/* Read from the stream and push to the h3conn */341static int quic_server_read(nghttp3_conn *h3conn, SSL *stream, uint64_t id, struct h3ssl *h3ssl)342{343int ret, r;344uint8_t msg2[16000];345size_t l = sizeof(msg2);346347if (!SSL_has_pending(stream))348return 0; /* Nothing to read */349350ret = SSL_read(stream, msg2, l);351if (ret <= 0) {352fprintf(stderr, "SSL_read %d on %llu failed\n",353SSL_get_error(stream, ret),354(unsigned long long) id);355switch (SSL_get_error(stream, ret)) {356case SSL_ERROR_WANT_READ:357return 0;358case SSL_ERROR_ZERO_RETURN:359return 1;360default:361ERR_print_errors_fp(stderr);362return -1;363}364return -1;365}366367/* XXX: work around nghttp3_conn_read_stream returning -607 on stream 2 */368if (!h3ssl->received_from_two && id != 2) {369r = nghttp3_conn_read_stream(h3conn, id, msg2, ret, 0);370} else {371r = ret; /* ignore it for the moment ... */372}373374printf("nghttp3_conn_read_stream used %d of %d on %llu\n", r,375ret, (unsigned long long) id);376if (r != ret) {377/* chrome returns -607 on stream 2 */378if (!nghttp3_err_is_fatal(r)) {379printf("nghttp3_conn_read_stream used %d of %d (not fatal) on %llu\n", r,380ret, (unsigned long long) id);381if (id == 2)382h3ssl->received_from_two = 1;383return 1;384}385return -1;386}387return 1;388}389390/*391* creates the control stream, the encoding and decoding streams.392* nghttp3_conn_bind_control_stream() is for the control stream.393*/394static int quic_server_h3streams(nghttp3_conn *h3conn, struct h3ssl *h3ssl)395{396SSL *rstream = NULL;397SSL *pstream = NULL;398SSL *cstream = NULL;399SSL *conn;400uint64_t r_streamid, p_streamid, c_streamid;401402conn = get_ids_connection(h3ssl);403if (conn == NULL) {404fprintf(stderr, "quic_server_h3streams no connection\n");405fflush(stderr);406return -1;407}408rstream = SSL_new_stream(conn, SSL_STREAM_FLAG_UNI);409if (rstream != NULL) {410printf("=> Opened on %llu\n",411(unsigned long long)SSL_get_stream_id(rstream));412} else {413fprintf(stderr, "=> Stream == NULL!\n");414goto err;415}416pstream = SSL_new_stream(conn, SSL_STREAM_FLAG_UNI);417if (pstream != NULL) {418printf("=> Opened on %llu\n",419(unsigned long long)SSL_get_stream_id(pstream));420} else {421fprintf(stderr, "=> Stream == NULL!\n");422goto err;423}424cstream = SSL_new_stream(conn, SSL_STREAM_FLAG_UNI);425if (cstream != NULL) {426fprintf(stderr, "=> Opened on %llu\n",427(unsigned long long)SSL_get_stream_id(cstream));428fflush(stderr);429} else {430fprintf(stderr, "=> Stream == NULL!\n");431goto err;432}433r_streamid = SSL_get_stream_id(rstream);434p_streamid = SSL_get_stream_id(pstream);435c_streamid = SSL_get_stream_id(cstream);436if (nghttp3_conn_bind_qpack_streams(h3conn, p_streamid, r_streamid)) {437fprintf(stderr, "nghttp3_conn_bind_qpack_streams failed!\n");438goto err;439}440if (nghttp3_conn_bind_control_stream(h3conn, c_streamid)) {441fprintf(stderr, "nghttp3_conn_bind_qpack_streams failed!\n");442goto err;443}444printf("control: %llu enc %llu dec %llu\n",445(unsigned long long)c_streamid,446(unsigned long long)p_streamid,447(unsigned long long)r_streamid);448add_id(SSL_get_stream_id(rstream), rstream, h3ssl);449add_id(SSL_get_stream_id(pstream), pstream, h3ssl);450add_id(SSL_get_stream_id(cstream), cstream, h3ssl);451452return 0;453err:454fflush(stderr);455SSL_free(rstream);456SSL_free(pstream);457SSL_free(cstream);458return -1;459}460461/* Try to read from the streams we have */462static int read_from_ssl_ids(nghttp3_conn **curh3conn, struct h3ssl *h3ssl)463{464int hassomething = 0, i;465struct ssl_id *ssl_ids = h3ssl->ssl_ids;466SSL_POLL_ITEM items[MAXSSL_IDS] = {0}, *item = items;467static const struct timeval nz_timeout = {0, 0};468size_t result_count = SIZE_MAX;469int numitem = 0, ret;470uint64_t processed_event = 0;471int has_ids_to_remove = 0;472nghttp3_conn *h3conn = *curh3conn;473474/*475* Process all the streams476* the first one is the connection if we get something here is a new stream477*/478for (i = 0; i < MAXSSL_IDS; i++) {479if (ssl_ids[i].s != NULL) {480item->desc = SSL_as_poll_descriptor(ssl_ids[i].s);481item->events = UINT64_MAX; /* TODO adjust to the event we need process */482item->revents = UINT64_MAX; /* TODO adjust to the event we need process */483numitem++;484item++;485}486}487488/*489* SSL_POLL_FLAG_NO_HANDLE_EVENTS would require to use:490* SSL_get_event_timeout on the connection stream491* select/wait using the timeout value (which could be no wait time)492* SSL_handle_events493* SSL_poll494* for the moment we let SSL_poll to performs ticking internally495* on an automatic basis.496*/497ret = SSL_poll(items, numitem, sizeof(SSL_POLL_ITEM), &nz_timeout,498SSL_POLL_FLAG_NO_HANDLE_EVENTS, &result_count);499if (!ret) {500fprintf(stderr, "SSL_poll failed\n");501printf("SSL_poll failed\n");502return -1; /* something is wrong */503}504printf("read_from_ssl_ids %ld events\n", (unsigned long)result_count);505if (result_count == 0) {506/* Timeout may be something somewhere */507return 0;508}509510/* reset the states */511h3ssl->new_conn = 0;512h3ssl->restart = 0;513h3ssl->done = 0;514515/* Process all the item we have polled */516for (i = 0, item = items; i < numitem; i++, item++) {517SSL *s;518519if (item->revents == SSL_POLL_EVENT_NONE)520continue;521processed_event = 0;522/* get the stream */523s = item->desc.value.ssl;524525/* New connection */526if (item->revents & SSL_POLL_EVENT_IC) {527SSL *conn = SSL_accept_connection(item->desc.value.ssl, 0);528SSL *oldconn;529530printf("SSL_accept_connection\n");531if (conn == NULL) {532fprintf(stderr, "error while accepting connection\n");533ret = -1;534goto err;535}536537/* the previous might be still there */538oldconn = get_ids_connection(h3ssl);539if (oldconn != NULL) {540/* XXX we support only one connection for the moment */541printf("SSL_accept_connection closing previous\n");542SSL_free(oldconn);543replace_ids_connection(h3ssl, oldconn, conn);544reuse_h3ssl(h3ssl);545close_all_ids(h3ssl);546h3ssl->id_bidi = UINT64_MAX;547h3ssl->has_uni = 0;548} else {549printf("SSL_accept_connection first connection\n");550add_ids_connection(h3ssl, conn);551}552h3ssl->new_conn = 1;553/* create the new h3conn */554nghttp3_conn_del(*curh3conn);555nghttp3_settings_default(&settings);556if (nghttp3_conn_server_new(curh3conn, &callbacks, &settings, mem,557h3ssl)) {558fprintf(stderr, "nghttp3_conn_client_new failed!\n");559exit(1);560}561h3conn = *curh3conn;562hassomething++;563564if (!SSL_set_incoming_stream_policy(conn,565SSL_INCOMING_STREAM_POLICY_ACCEPT, 0)) {566fprintf(stderr, "error while setting inccoming stream policy\n");567ret = -1;568goto err;569}570571printf("SSL_accept_connection\n");572processed_event = processed_event | SSL_POLL_EVENT_IC;573}574/* SSL_accept_stream if SSL_POLL_EVENT_ISB or SSL_POLL_EVENT_ISU */575if ((item->revents & SSL_POLL_EVENT_ISB) ||576(item->revents & SSL_POLL_EVENT_ISU)) {577SSL *stream = SSL_accept_stream(item->desc.value.ssl, 0);578uint64_t new_id;579int r;580581if (stream == NULL) {582ret = -1;583goto err;584}585new_id = SSL_get_stream_id(stream);586printf("=> Received connection on %lld %d\n", (unsigned long long) new_id,587SSL_get_stream_type(stream));588add_id(new_id, stream, h3ssl);589if (h3ssl->close_wait) {590printf("in close_wait so we will have a new request\n");591reuse_h3ssl(h3ssl);592h3ssl->restart = 1; /* Checked in wait_close loop */593}594if (SSL_get_stream_type(stream) == SSL_STREAM_TYPE_BIDI) {595/* bidi that is the id where we have to send the response */596if (h3ssl->id_bidi != UINT64_MAX) {597set_id_status(h3ssl->id_bidi, TOBEREMOVED, h3ssl);598has_ids_to_remove++;599}600h3ssl->id_bidi = new_id;601reuse_h3ssl(h3ssl);602h3ssl->restart = 1;603} else {604set_id_status(new_id, CLIENTUNIOPEN, h3ssl);605}606607r = quic_server_read(h3conn, stream, new_id, h3ssl);608if (r == -1) {609ret = -1;610goto err;611}612if (r == 1)613hassomething++;614615if (item->revents & SSL_POLL_EVENT_ISB)616processed_event = processed_event | SSL_POLL_EVENT_ISB;617if (item->revents & SSL_POLL_EVENT_ISU)618processed_event = processed_event | SSL_POLL_EVENT_ISU;619}620if (item->revents & SSL_POLL_EVENT_OSB) {621/* Create new streams when allowed */622/* at least one bidi */623processed_event = processed_event | SSL_POLL_EVENT_OSB;624printf("Create bidi?\n");625}626if (item->revents & SSL_POLL_EVENT_OSU) {627/* at least one uni */628/* we have 4 streams from the client 2, 6 , 10 and 0 */629/* need 3 streams to the client */630printf("Create uni?\n");631processed_event = processed_event | SSL_POLL_EVENT_OSU;632if (!h3ssl->has_uni) {633printf("Create uni\n");634ret = quic_server_h3streams(h3conn, h3ssl);635if (ret == -1) {636fprintf(stderr, "quic_server_h3streams failed!\n");637goto err;638}639h3ssl->has_uni = 1;640hassomething++;641}642}643if (item->revents & SSL_POLL_EVENT_EC) {644/* the connection begins terminating */645printf("Connection terminating\n");646printf("Connection terminating restart %d\n", h3ssl->restart);647if (!h3ssl->close_done) {648h3ssl->close_done = 1;649} else {650h3ssl->done = 1;651}652hassomething++;653processed_event = processed_event | SSL_POLL_EVENT_EC;654}655if (item->revents & SSL_POLL_EVENT_ECD) {656/* the connection is terminated */657printf("Connection terminated\n");658h3ssl->done = 1;659hassomething++;660processed_event = processed_event | SSL_POLL_EVENT_ECD;661}662663if (item->revents & SSL_POLL_EVENT_R) {664/* try to read */665uint64_t id = UINT64_MAX;666int r;667668/* get the id, well the connection has no id... */669id = SSL_get_stream_id(item->desc.value.ssl);670printf("revent READ on %llu\n", (unsigned long long)id);671r = quic_server_read(h3conn, s, id, h3ssl);672if (r == 0) {673uint8_t msg[1];674size_t l = sizeof(msg);675676/* check that the other side is closed */677r = SSL_read(s, msg, l);678printf("SSL_read tells %d\n", r);679if (r > 0) {680ret = -1;681goto err;682}683r = SSL_get_error(s, r);684if (r != SSL_ERROR_ZERO_RETURN) {685ret = -1;686goto err;687}688set_id_status(id, TOBEREMOVED, h3ssl);689has_ids_to_remove++;690continue;691}692if (r == -1) {693ret = -1;694goto err;695}696hassomething++;697processed_event = processed_event | SSL_POLL_EVENT_R;698}699if (item->revents & SSL_POLL_EVENT_ER) {700/* mark it closed */701uint64_t id = UINT64_MAX;702int status;703704id = SSL_get_stream_id(item->desc.value.ssl);705status = get_id_status(id, h3ssl);706707printf("revent exception READ on %llu\n", (unsigned long long)id);708if (status & CLIENTUNIOPEN) {709set_id_status(id, CLIENTCLOSED, h3ssl);710hassomething++;711}712processed_event = processed_event | SSL_POLL_EVENT_ER;713}714if (item->revents & SSL_POLL_EVENT_W) {715/* we ignore those for the moment */716processed_event = processed_event | SSL_POLL_EVENT_W;717}718if (item->revents & SSL_POLL_EVENT_EW) {719/* write part received a STOP_SENDING */720uint64_t id = UINT64_MAX;721int status;722723id = SSL_get_stream_id(item->desc.value.ssl);724status = get_id_status(id, h3ssl);725726if (status & SERVERCLOSED) {727printf("both sides closed on %llu\n", (unsigned long long)id);728set_id_status(id, TOBEREMOVED, h3ssl);729has_ids_to_remove++;730hassomething++;731}732processed_event = processed_event | SSL_POLL_EVENT_EW;733}734if (item->revents != processed_event) {735/* Figure out ??? */736uint64_t id = UINT64_MAX;737738id = SSL_get_stream_id(item->desc.value.ssl);739printf("revent %llu (%d) on %llu NOT PROCESSED!\n",740(unsigned long long)item->revents, SSL_POLL_EVENT_W,741(unsigned long long)id);742}743}744ret = hassomething;745err:746if (has_ids_to_remove)747remove_marked_ids(h3ssl);748return ret;749}750751static void handle_events_from_ids(struct h3ssl *h3ssl)752{753struct ssl_id *ssl_ids = h3ssl->ssl_ids;754int i;755756ssl_ids = h3ssl->ssl_ids;757for (i = 0; i < MAXSSL_IDS; i++) {758if (ssl_ids[i].s != NULL &&759(ssl_ids[i].status & ISCONNECTION || ssl_ids[i].status & ISLISTENER)) {760if (SSL_handle_events(ssl_ids[i].s))761ERR_print_errors_fp(stderr);762}763}764}765766static size_t get_file_length(struct h3ssl *h3ssl)767{768char filename[PATH_MAX];769struct stat st;770771memset(filename, 0, PATH_MAX);772if (h3ssl->fileprefix != NULL)773strcat(filename, h3ssl->fileprefix);774strcat(filename, h3ssl->url);775776if (strcmp(h3ssl->url, "big") == 0) {777printf("big!!!\n");778return (size_t)INT_MAX;779}780if (stat(filename, &st) == 0) {781/* Only process regular files */782if (S_ISREG(st.st_mode)) {783printf("get_file_length %s %lld\n", filename, (unsigned long long) st.st_size);784return (size_t)st.st_size;785}786}787printf("Can't get_file_length %s\n", filename);788return 0;789}790791static char *get_file_data(struct h3ssl *h3ssl)792{793char filename[PATH_MAX];794size_t size = get_file_length(h3ssl);795char *res;796int fd;797798if (size == 0)799return NULL;800801memset(filename, 0, PATH_MAX);802if (h3ssl->fileprefix != NULL)803strcat(filename, h3ssl->fileprefix);804strcat(filename, h3ssl->url);805806res = malloc(size+1);807res[size] = '\0';808fd = open(filename, O_RDONLY);809if (read(fd, res, size) == -1) {810close(fd);811free(res);812return NULL;813}814close(fd);815printf("read from %s : %zu\n", filename, size);816return res;817}818819static nghttp3_ssize step_read_data(nghttp3_conn *conn, int64_t stream_id,820nghttp3_vec *vec, size_t veccnt,821uint32_t *pflags, void *user_data,822void *stream_user_data)823{824struct h3ssl *h3ssl = (struct h3ssl *)user_data;825826if (h3ssl->datadone) {827*pflags = NGHTTP3_DATA_FLAG_EOF;828return 0;829}830/* send the data */831printf("step_read_data for %s %zu\n", h3ssl->url, h3ssl->ldata);832if (h3ssl->ldata <= 4096) {833vec[0].base = &(h3ssl->ptr_data[h3ssl->offset_data]);834vec[0].len = h3ssl->ldata;835h3ssl->datadone++;836*pflags = NGHTTP3_DATA_FLAG_EOF;837} else {838vec[0].base = &(h3ssl->ptr_data[h3ssl->offset_data]);839vec[0].len = 4096;840if (h3ssl->ldata == INT_MAX) {841printf("big = endless!\n");842} else {843h3ssl->offset_data = h3ssl->offset_data + 4096;844h3ssl->ldata = h3ssl->ldata - 4096;845}846}847848return 1;849}850851static int quic_server_write(struct h3ssl *h3ssl, uint64_t streamid,852uint8_t *buff, size_t len, uint64_t flags,853size_t *written)854{855struct ssl_id *ssl_ids;856int i;857858ssl_ids = h3ssl->ssl_ids;859for (i = 0; i < MAXSSL_IDS; i++) {860if (ssl_ids[i].id == streamid) {861if (!SSL_write_ex2(ssl_ids[i].s, buff, len, flags, written) ||862*written != len) {863fprintf(stderr, "couldn't write on connection\n");864ERR_print_errors_fp(stderr);865return 0;866}867printf("written %lld on %lld flags %lld\n", (unsigned long long)len,868(unsigned long long)streamid, (unsigned long long)flags);869return 1;870}871}872printf("quic_server_write %lld on %lld (NOT FOUND!)\n", (unsigned long long)len,873(unsigned long long)streamid);874return 0;875}876877#define OSSL_NELEM(x) (sizeof(x) / sizeof((x)[0]))878879/*880* This is a basic demo of QUIC server functionality in which one connection at881* a time is accepted in a blocking loop.882*/883884/* ALPN string for TLS handshake. We pretent h3-29 and h3 */885static const unsigned char alpn_ossltest[] = { 5, 'h', '3', '-', '2',886'9', 2, 'h', '3' };887888/*889* This callback validates and negotiates the desired ALPN on the server side.890*/891static int select_alpn(SSL *ssl, const unsigned char **out,892unsigned char *out_len, const unsigned char *in,893unsigned int in_len, void *arg)894{895if (SSL_select_next_proto((unsigned char **)out, out_len, alpn_ossltest,896sizeof(alpn_ossltest), in,897in_len) != OPENSSL_NPN_NEGOTIATED)898return SSL_TLSEXT_ERR_ALERT_FATAL;899900return SSL_TLSEXT_ERR_OK;901}902903/* Create SSL_CTX. */904static SSL_CTX *create_ctx(const char *cert_path, const char *key_path)905{906SSL_CTX *ctx;907908ctx = SSL_CTX_new(OSSL_QUIC_server_method());909if (ctx == NULL)910goto err;911912/* Load certificate and corresponding private key. */913if (SSL_CTX_use_certificate_chain_file(ctx, cert_path) <= 0) {914fprintf(stderr, "couldn't load certificate file: %s\n", cert_path);915goto err;916}917918if (SSL_CTX_use_PrivateKey_file(ctx, key_path, SSL_FILETYPE_PEM) <= 0) {919fprintf(stderr, "couldn't load key file: %s\n", key_path);920goto err;921}922923if (!SSL_CTX_check_private_key(ctx)) {924fprintf(stderr, "private key check failed\n");925goto err;926}927928/* Setup ALPN negotiation callback. */929SSL_CTX_set_alpn_select_cb(ctx, select_alpn, NULL);930return ctx;931932err:933SSL_CTX_free(ctx);934return NULL;935}936937/* Create UDP socket using given port. */938static int create_socket(uint16_t port)939{940int fd = -1;941struct sockaddr_in sa = {0};942943if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {944fprintf(stderr, "cannot create socket");945goto err;946}947948sa.sin_family = AF_INET;949sa.sin_port = htons(port);950951if (bind(fd, (const struct sockaddr *)&sa, sizeof(sa)) < 0) {952fprintf(stderr, "cannot bind to %u\n", port);953goto err;954}955956return fd;957958err:959if (fd >= 0)960BIO_closesocket(fd);961962return -1;963}964965/* Copied from demos/guide/quic-server-non-block.c */966/**967* @brief Waits for activity on the SSL socket, either for reading or writing.968*969* This function monitors the underlying file descriptor of the given SSL970* connection to determine when it is ready for reading or writing, or both.971* It uses the select function to wait until the socket is either readable972* or writable, depending on what the SSL connection requires.973*974* @param ssl A pointer to the SSL object representing the connection.975*976* @note This function blocks until there is activity on the socket. In a real977* application, you might want to perform other tasks while waiting, such as978* updating a GUI or handling other connections.979*980* @note This function uses select for simplicity and portability. Depending981* on your application's requirements, you might consider using other982* mechanisms like poll or epoll for handling multiple file descriptors.983*/984static int wait_for_activity(SSL *ssl)985{986int sock, isinfinite;987fd_set read_fd, write_fd;988struct timeval tv;989struct timeval *tvp = NULL;990991/* Get hold of the underlying file descriptor for the socket */992if ((sock = SSL_get_fd(ssl)) == -1) {993fprintf(stderr, "Unable to get file descriptor");994return -1;995}996997/* Initialize the fd_set structure */998FD_ZERO(&read_fd);999FD_ZERO(&write_fd);10001001/*1002* Determine if we would like to write to the socket, read from it, or both.1003*/1004if (SSL_net_write_desired(ssl))1005FD_SET(sock, &write_fd);1006if (SSL_net_read_desired(ssl))1007FD_SET(sock, &read_fd);10081009/* Add the socket file descriptor to the fd_set */1010FD_SET(sock, &read_fd);10111012/*1013* Find out when OpenSSL would next like to be called, regardless of1014* whether the state of the underlying socket has changed or not.1015*/1016if (SSL_get_event_timeout(ssl, &tv, &isinfinite) && !isinfinite)1017tvp = &tv;10181019/*1020* Wait until the socket is writeable or readable. We use select here1021* for the sake of simplicity and portability, but you could equally use1022* poll/epoll or similar functions1023*1024* NOTE: For the purposes of this demonstration code this effectively1025* makes this demo block until it has something more useful to do. In a1026* real application you probably want to go and do other work here (e.g.1027* update a GUI, or service other connections).1028*1029* Let's say for example that you want to update the progress counter on1030* a GUI every 100ms. One way to do that would be to use the timeout in1031* the last parameter to "select" below. If the tvp value is greater1032* than 100ms then use 100ms instead. Then, when select returns, you1033* check if it did so because of activity on the file descriptors or1034* because of the timeout. If the 100ms GUI timeout has expired but the1035* tvp timeout has not then go and update the GUI and then restart the1036* "select" (with updated timeouts).1037*/10381039return (select(sock + 1, &read_fd, &write_fd, NULL, tvp));1040}10411042/* Main loop for server to accept QUIC connections. */1043static int run_quic_server(SSL_CTX *ctx, int fd)1044{1045int ok = 0;1046int hassomething = 0;1047SSL *listener = NULL;1048nghttp3_conn *h3conn = NULL;1049struct h3ssl h3ssl;1050SSL *ssl;1051char *fileprefix = getenv("FILEPREFIX");10521053/* Create a new QUIC listener. */1054if ((listener = SSL_new_listener(ctx, 0)) == NULL)1055goto err;10561057/* Provide the listener with our UDP socket. */1058if (!SSL_set_fd(listener, fd))1059goto err;10601061/* Begin listening. */1062if (!SSL_listen(listener))1063goto err;10641065/*1066* Listeners, and other QUIC objects, default to operating in blocking mode.1067* The configured behaviour is inherited by child objects.1068* Make sure we won't block as we use select().1069*/1070if (!SSL_set_blocking_mode(listener, 0))1071goto err;10721073/* Setup callbacks. */1074callbacks.recv_header = on_recv_header;1075callbacks.end_headers = on_end_headers;1076callbacks.recv_data = on_recv_data;1077callbacks.end_stream = on_end_stream;10781079/* mem default */1080mem = nghttp3_mem_default();10811082for (;;) {1083nghttp3_nv resp[10];1084size_t num_nv;1085nghttp3_data_reader dr;1086int ret;1087int numtimeout;1088char slength[22];1089int hasnothing;10901091init_ids(&h3ssl);1092h3ssl.fileprefix = fileprefix;1093printf("listener: %p\n", (void *)listener);1094add_ids_listener(listener, &h3ssl);10951096if (!hassomething) {1097printf("waiting on socket\n");1098fflush(stdout);1099ret = wait_for_activity(listener);1100if (ret == -1) {1101fprintf(stderr, "wait_for_activity failed!\n");1102goto err;1103}1104}1105/*1106* Service the connection. In a real application this would be done1107* concurrently. In this demonstration program a single connection is1108* accepted and serviced at a time.1109*/1110newconn:11111112printf("process_server starting...\n");1113fflush(stdout);11141115/* wait until we have received the headers */1116restart:1117numtimeout = 0;1118num_nv = 0;1119while (!h3ssl.end_headers_received) {1120if (!hassomething) {1121if (wait_for_activity(listener) == 0) {1122printf("waiting for end_headers_received timeout %d\n", numtimeout);1123numtimeout++;1124if (numtimeout == 25)1125goto err;1126}1127handle_events_from_ids(&h3ssl);1128}1129hassomething = read_from_ssl_ids(&h3conn, &h3ssl);1130if (hassomething == -1) {1131fprintf(stderr, "read_from_ssl_ids hassomething failed\n");1132goto err;1133} else if (hassomething == 0) {1134printf("read_from_ssl_ids hassomething nothing...\n");1135} else {1136numtimeout = 0;1137printf("read_from_ssl_ids hassomething %d...\n", hassomething);1138if (h3ssl.close_done) {1139/* Other side has closed */1140break;1141}1142h3ssl.restart = 0;1143}1144}1145if (h3ssl.close_done) {1146printf("Other side close without request\n");1147goto wait_close;1148}1149printf("end_headers_received!!!\n");1150if (!h3ssl.has_uni) {1151/* time to create those otherwise we can't push anything to the client */1152printf("Create uni\n");1153if (quic_server_h3streams(h3conn, &h3ssl) == -1) {1154fprintf(stderr, "quic_server_h3streams failed!\n");1155goto err;1156}1157h3ssl.has_uni = 1;1158}11591160/* we have receive the request build the response and send it */1161/* XXX add MAKE_NV("connection", "close"), to resp[] and recheck */1162make_nv(&resp[num_nv++], ":status", "200");1163h3ssl.ldata = get_file_length(&h3ssl);1164if (h3ssl.ldata == 0) {1165/* We don't find the file: use default test string */1166h3ssl.ptr_data = nulldata;1167h3ssl.ldata = nulldata_sz;1168sprintf(slength, "%zu", h3ssl.ldata);1169/* content-type: text/html */1170make_nv(&resp[num_nv++], "content-type", "text/html");1171} else if (h3ssl.ldata == INT_MAX) {1172/* endless file for tests */1173sprintf(slength, "%zu", h3ssl.ldata);1174h3ssl.ptr_data = (uint8_t *) malloc(4096);1175memset(h3ssl.ptr_data, 'A', 4096);1176} else {1177/* normal file we have opened */1178sprintf(slength, "%zu", h3ssl.ldata);1179h3ssl.ptr_data = (uint8_t *) get_file_data(&h3ssl);1180if (h3ssl.ptr_data == NULL)1181abort();1182printf("before nghttp3_conn_submit_response on %llu for %s ...\n",1183(unsigned long long) h3ssl.id_bidi, h3ssl.url);1184if (strstr(h3ssl.url, ".png"))1185make_nv(&resp[num_nv++], "content-type", "image/png");1186else if (strstr(h3ssl.url, ".ico"))1187make_nv(&resp[num_nv++], "content-type", "image/vnd.microsoft.icon");1188else if (strstr(h3ssl.url, ".htm"))1189make_nv(&resp[num_nv++], "content-type", "text/html");1190else1191make_nv(&resp[num_nv++], "content-type", "application/octet-stream");1192make_nv(&resp[num_nv++], "content-length", slength);1193}11941195dr.read_data = step_read_data;1196if (nghttp3_conn_submit_response(h3conn, h3ssl.id_bidi, resp, num_nv, &dr)) {1197fprintf(stderr, "nghttp3_conn_submit_response failed!\n");1198goto err;1199}1200printf("nghttp3_conn_submit_response on %llu...\n", (unsigned long long) h3ssl.id_bidi);1201for (;;) {1202nghttp3_vec vec[256];1203nghttp3_ssize sveccnt;1204int fin, i;1205int64_t streamid;12061207sveccnt = nghttp3_conn_writev_stream(h3conn, &streamid, &fin, vec,1208nghttp3_arraylen(vec));1209if (sveccnt <= 0) {1210printf("nghttp3_conn_writev_stream done: %ld stream: %llu fin %d\n",1211(long int)sveccnt,1212(unsigned long long)streamid,1213fin);1214if (streamid != -1 && fin) {1215printf("Sending end data on %llu fin %d\n",1216(unsigned long long) streamid, fin);1217nghttp3_conn_add_write_offset(h3conn, streamid, 0);1218continue;1219}1220if (!h3ssl.datadone)1221goto err;1222else1223break; /* Done */1224}1225printf("nghttp3_conn_writev_stream: %ld fin: %d\n", (long int)sveccnt, fin);1226for (i = 0; i < sveccnt; i++) {1227size_t numbytes = vec[i].len;1228int flagwrite = 0;12291230printf("quic_server_write on %llu for %ld\n",1231(unsigned long long)streamid, (unsigned long)vec[i].len);1232if (fin && i == sveccnt - 1)1233flagwrite = SSL_WRITE_FLAG_CONCLUDE;1234if (!quic_server_write(&h3ssl, streamid, vec[i].base,1235vec[i].len, flagwrite, &numbytes)) {1236fprintf(stderr, "quic_server_write failed!\n");1237goto err;1238}1239}1240if (nghttp3_conn_add_write_offset(1241h3conn, streamid,1242(size_t)nghttp3_vec_len(vec, (size_t)sveccnt))) {1243fprintf(stderr, "nghttp3_conn_add_write_offset failed!\n");1244goto err;1245}1246}1247printf("nghttp3_conn_submit_response DONE!!!\n");12481249if (h3ssl.datadone) {1250/*1251* All the data was sent.1252* close stream zero1253*/1254if (!h3ssl.close_done) {1255set_id_status(h3ssl.id_bidi, SERVERCLOSED, &h3ssl);1256h3ssl.close_wait = 1;1257}1258} else {1259printf("nghttp3_conn_submit_response still not finished\n");1260}12611262/* wait until closed */1263wait_close:1264hasnothing = 0;1265for (;;) {12661267if (!hasnothing) {1268SSL *newssl = get_ids_connection(&h3ssl);12691270printf("hasnothing nothing WAIT %d!!!\n", h3ssl.close_done);1271if (newssl == NULL)1272newssl = listener;1273ret = wait_for_activity(newssl);1274if (ret == -1)1275goto err;1276if (ret == 0)1277printf("hasnothing timeout\n");1278/* we have something or a timeout */1279handle_events_from_ids(&h3ssl);1280}1281hasnothing = read_from_ssl_ids(&h3conn, &h3ssl);1282if (hasnothing == -1) {1283printf("hasnothing failed\n");1284break;1285/* goto err; well in fact not */1286} else if (hasnothing == 0) {1287printf("hasnothing nothing\n");1288continue;1289} else {1290printf("hasnothing something\n");1291if (h3ssl.done) {1292printf("hasnothing something... DONE\n");1293/* we might already have the next connection to accept */1294hassomething = 1;1295break;1296}1297if (h3ssl.new_conn) {1298printf("hasnothing something... NEW CONN\n");1299h3ssl.new_conn = 0;1300goto newconn;1301}1302if (h3ssl.restart) {1303printf("hasnothing something... RESTART\n");1304h3ssl.restart = 0;1305goto restart;1306}1307if (are_all_clientid_closed(&h3ssl)) {1308printf("hasnothing something... DONE other side closed\n");1309/* there might 2 or 3 message we will ignore */1310hassomething = 0;1311break;1312}1313}1314}13151316/*1317* Free the streams, then loop again, accepting another connection.1318*/1319close_all_ids(&h3ssl);1320ssl = get_ids_connection(&h3ssl);1321if (ssl != NULL) {1322SSL_free(ssl);1323replace_ids_connection(&h3ssl, ssl, NULL);1324}1325hassomething = 0;1326}13271328ok = 1;1329err:1330if (!ok)1331ERR_print_errors_fp(stderr);13321333SSL_free(listener);1334return ok;1335}13361337/*1338* demo server... just return a 20 bytes ascii string as response for any1339* request single h3 connection and single threaded.1340*/1341int main(int argc, char **argv)1342{1343int rc = 1;1344SSL_CTX *ctx = NULL;1345int fd = -1;1346unsigned long port;13471348if (argc < 4) {1349fprintf(stderr, "usage: %s <port> <server.crt> <server.key>\n",1350argv[0]);1351goto err;1352}13531354/* Create SSL_CTX. */1355if ((ctx = create_ctx(argv[2], argv[3])) == NULL)1356goto err;13571358/* Parse port number from command line arguments. */1359port = strtoul(argv[1], NULL, 0);1360if (port == 0 || port > UINT16_MAX) {1361fprintf(stderr, "invalid port: %lu\n", port);1362goto err;1363}13641365/* Create UDP socket. */1366if ((fd = create_socket((uint16_t)port)) < 0)1367goto err;13681369/* Enter QUIC server connection acceptance loop. */1370if (!run_quic_server(ctx, fd))1371goto err;13721373rc = 0;1374err:1375if (rc != 0)1376ERR_print_errors_fp(stderr);13771378SSL_CTX_free(ctx);13791380if (fd != -1)1381BIO_closesocket(fd);13821383return rc;1384}138513861387