xref: /freebsd/crypto/openssl/test/quic-openssl-docker/hq-interop/quic-hq-interop-server.c (revision e7be843b4a162e68651d3911f0357ed464915629)
1 /*
2  *  Copyright 2024-2025 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  *  Licensed under the Apache License 2.0 (the "License").  You may not use
5  *  this file except in compliance with the License.  You can obtain a copy
6  *  in the file LICENSE in the source distribution or at
7  *  https://www.openssl.org/source/license.html
8  */
9 
10 /**
11  * @file quic-hq-interop-server.c
12  * @brief Minimal QUIC HTTP/0.9 server implementation.
13  *
14  * This file implements a lightweight QUIC server supporting the HTTP/0.9
15  * protocol for interoperability testing. It includes functions for setting
16  * up a secure QUIC connection, handling ALPN negotiation, and serving client
17  * requests.  Intended for use with the quic-interop-runner
18  * available at https://interop.seemann.io
19  *
20  * Key functionalities:
21  * - Setting up SSL_CTX with QUIC support.
22  * - Negotiating ALPN strings during the TLS handshake.
23  * - Listening and accepting incoming QUIC connections.
24  * - Handling client requests via HTTP/0.9 protocol.
25  *
26  * Usage:
27  *   <port> <server.crt> <server.key>
28  * The server binds to the specified port and serves files using the given
29  * certificate and private key.
30  *
31  * Environment variables:
32  * - FILEPREFIX: Specifies the directory containing files to serve.
33  *   Defaults to "./downloads" if not set.
34  * - SSLKEYLOGFILE: specifies that keylogging should be preformed on the server
35  *   should be set to a file name to record keylog data to
36  * - NO_ADDR_VALIDATE: Disables server address validation of clients
37  *
38  */
39 
40 #include <string.h>
41 
42 /* Include the appropriate header file for SOCK_STREAM */
43 #ifdef _WIN32
44 # include <stdarg.h>
45 # include <winsock2.h>
46 # include <ws2tcpip.h>
47 #else
48 # include <sys/socket.h>
49 # include <netinet/in.h>
50 # include <unistd.h>
51 #endif
52 
53 #include <openssl/bio.h>
54 #include <openssl/ssl.h>
55 #include <openssl/err.h>
56 #include <openssl/quic.h>
57 
58 #define BUF_SIZE 4096
59 
60 /**
61  * @brief ALPN (Application-Layer Protocol Negotiation) identifier for QUIC.
62  *
63  * This constant defines the ALPN string used during the TLS handshake
64  * to negotiate the application-layer protocol between the client and
65  * the server. It specifies "hq-interop" as the supported protocol.
66  *
67  * Format:
68  * - The first byte represents the length of the ALPN string.
69  * - Subsequent bytes represent the ASCII characters of the protocol name.
70  *
71  * Value:
72  * - Protocol: "hq-interop"
73  * - Length: 10 bytes
74  *
75  * Usage:
76  * This is passed to the ALPN callback function to validate and
77  * negotiate the desired protocol during the TLS handshake.
78  */
79 static const unsigned char alpn_ossltest[] = {
80     10, 'h', 'q', '-', 'i', 'n', 't', 'e', 'r', 'o', 'p',
81 };
82 
83 /**
84  * @brief Directory prefix for serving requested files.
85  *
86  * This variable specifies the directory path used as the base location
87  * for serving files in response to client requests. It is used to construct
88  * the full file path for requested resources.
89  *
90  * Default:
91  * - If not set via the FILEPREFIX environment variable, it defaults to
92  *   "./downloads".
93  *
94  * Usage:
95  * - Updated at runtime based on the FILEPREFIX environment variable.
96  * - Used to locate and serve files during incoming requests.
97  */
98 static char *fileprefix = NULL;
99 
100 /**
101  * @brief Callback for ALPN (Application-Layer Protocol Negotiation) selection.
102  *
103  * This function is invoked during the TLS handshake on the server side to
104  * validate and negotiate the desired ALPN (Application-Layer Protocol
105  * Negotiation) protocol with the client. It ensures that the negotiated
106  * protocol matches the predefined "hq-interop" string.
107  *
108  * @param ssl       Pointer to the SSL connection object.
109  * @param[out] out  Pointer to the negotiated ALPN protocol string.
110  * @param[out] out_len Length of the negotiated ALPN protocol string.
111  * @param in        Pointer to the client-provided ALPN protocol list.
112  * @param in_len    Length of the client-provided ALPN protocol list.
113  * @param arg       Optional user-defined argument (unused in this context).
114  *
115  * @return SSL_TLSEXT_ERR_OK on successful ALPN negotiation,
116  *         SSL_TLSEXT_ERR_ALERT_FATAL otherwise.
117  *
118  * Usage:
119  * - This function is set as the ALPN selection callback in the SSL_CTX
120  *   using `SSL_CTX_set_alpn_select_cb`.
121  * - Ensures that only the predefined ALPN protocol is accepted.
122  *
123  * Note:
124  * - The predefined protocol is specified in the `alpn_ossltest` array.
125  */
select_alpn(SSL * ssl,const unsigned char ** out,unsigned char * out_len,const unsigned char * in,unsigned int in_len,void * arg)126 static int select_alpn(SSL *ssl, const unsigned char **out,
127                        unsigned char *out_len, const unsigned char *in,
128                        unsigned int in_len, void *arg)
129 {
130     /*
131      * Use the next_proto helper function here.
132      * This scans the list of alpns we support and matches against
133      * what the client is requesting
134      */
135     if (SSL_select_next_proto((unsigned char **)out, out_len, alpn_ossltest,
136                               sizeof(alpn_ossltest), in,
137                               in_len) == OPENSSL_NPN_NEGOTIATED)
138         return SSL_TLSEXT_ERR_OK;
139     return SSL_TLSEXT_ERR_ALERT_FATAL;
140 }
141 
142 /**
143  * @brief Creates and configures an SSL_CTX for a QUIC server.
144  *
145  * This function initializes an SSL_CTX object with the QUIC server method
146  * and configures it using the provided certificate and private key. The
147  * context is prepared for handling secure QUIC connections and performing
148  * ALPN (Application-Layer Protocol Negotiation).
149  *
150  * @param cert_path Path to the server's certificate chain file in PEM format.
151  *                  The chain file must include the server's leaf certificate
152  *                  followed by intermediate CA certificates.
153  * @param key_path  Path to the server's private key file in PEM format. The
154  *                  private key must correspond to the leaf certificate in
155  *                  the chain file.
156  *
157  * @return Pointer to the initialized SSL_CTX on success, or NULL on failure.
158  *
159  * Configuration:
160  * - Loads the certificate chain and private key into the context.
161  * - Disables client certificate verification (no mutual TLS).
162  * - Sets up the ALPN selection callback for protocol negotiation.
163  *
164  * Error Handling:
165  * - If any step fails (e.g., loading the certificate or key), the function
166  *   frees the SSL_CTX and returns NULL.
167  *
168  * Usage:
169  * - Call this function to create an SSL_CTX before starting the QUIC server.
170  * - Ensure valid paths for the certificate and private key are provided.
171  *
172  * Note:
173  * - The ALPN callback only supports the predefined protocol defined in
174  *   `alpn_ossltest`.
175  */
create_ctx(const char * cert_path,const char * key_path)176 static SSL_CTX *create_ctx(const char *cert_path, const char *key_path)
177 {
178     SSL_CTX *ctx;
179 
180     /*
181      * An SSL_CTX holds shared configuration information for multiple
182      * subsequent per-client connections. We specifically load a QUIC
183      * server method here.
184      */
185     ctx = SSL_CTX_new(OSSL_QUIC_server_method());
186     if (ctx == NULL)
187         goto err;
188 
189     /*
190      * Load the server's certificate *chain* file (PEM format), which includes
191      * not only the leaf (end-entity) server certificate, but also any
192      * intermediate issuer-CA certificates.  The leaf certificate must be the
193      * first certificate in the file.
194      *
195      * In advanced use-cases this can be called multiple times, once per public
196      * key algorithm for which the server has a corresponding certificate.
197      * However, the corresponding private key (see below) must be loaded first,
198      * *before* moving on to the next chain file.
199      *
200      * The requisite files "chain.pem" and "pkey.pem" can be generated by running
201      * "make chain" in this directory.  If the server will be executed from some
202      * other directory, move or copy the files there.
203      */
204     if (SSL_CTX_use_certificate_chain_file(ctx, cert_path) <= 0) {
205         fprintf(stderr, "couldn't load certificate file: %s\n", cert_path);
206         goto err;
207     }
208 
209     /*
210      * Load the corresponding private key, this also checks that the private
211      * key matches the just loaded end-entity certificate.  It does not check
212      * whether the certificate chain is valid, the certificates could be
213      * expired, or may otherwise fail to form a chain that a client can validate.
214      */
215     if (SSL_CTX_use_PrivateKey_file(ctx, key_path, SSL_FILETYPE_PEM) <= 0) {
216         fprintf(stderr, "couldn't load key file: %s\n", key_path);
217         goto err;
218     }
219 
220     /*
221      * Since we're not soliciting or processing client certificates, we don't
222      * need to configure a trusted-certificate store, so no call to
223      * SSL_CTX_set_default_verify_paths() is needed.  The server's own
224      * certificate chain is assumed valid.
225      */
226     SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
227 
228     /* Setup ALPN negotiation callback to decide which ALPN is accepted. */
229     SSL_CTX_set_alpn_select_cb(ctx, select_alpn, NULL);
230 
231     return ctx;
232 
233 err:
234     SSL_CTX_free(ctx);
235     return NULL;
236 }
237 
238 /**
239  * @brief Creates and binds a UDP socket to the specified port.
240  *
241  * This function initializes a new UDP socket, binds it to the specified
242  * port on the local host, and returns the socket file descriptor for
243  * further use.
244  *
245  * @param port The port number to which the UDP socket should be bound.
246  *
247  * @return On success, returns the BIO of the created socket.
248  *         On failure, returns NULL.
249  *
250  * Steps:
251  * - Creates a new UDP socket using the `socket` system call.
252  * - Configures the socket address structure to bind to the specified port
253  *   on the local host.
254  * - Binds the socket to the port using the `bind` system call.
255  *
256  * Error Handling:
257  * - If socket creation or binding fails, an error message is printed to
258  *   `stderr`, the socket (if created) is closed, and -1 is returned.
259  *
260  * Usage:
261  * - Call this function to set up a socket for handling incoming QUIC
262  *   connections.
263  *
264  * Notes:
265  * - This function assumes UDP (`SOCK_DGRAM`).
266  * - This function accepts on both IPv4 and IPv6.
267  * - The specified port is converted to network byte order using `htons`.
268  */
create_socket(uint16_t port)269 static BIO *create_socket(uint16_t port)
270 {
271     int fd = -1;
272     BIO *sock = NULL;
273     BIO_ADDR *addr = NULL;
274     int opt = 0;
275 #ifdef _WIN32
276     struct in6_addr in6addr_any;
277 
278     memset(&in6addr_any, 0, sizeof(in6addr_any));
279 #endif
280 
281     /* Retrieve the file descriptor for a new UDP socket */
282     if ((fd = BIO_socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP, 0)) < 0) {
283         fprintf(stderr, "cannot create socket");
284         goto err;
285     }
286 
287     /*
288      * IPv6_V6ONLY is only available on some platforms. If it is defined,
289      * disable it to accept both IPv4 and IPv6 connections. Otherwise, the
290      * server will only accept IPv6 connections.
291      */
292 #ifdef IPV6_V6ONLY
293     if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &opt, sizeof(opt)) < 0) {
294         fprintf(stderr, "setsockopt IPV6_V6ONLY failed");
295         goto err;
296     }
297 #endif
298 
299     /*
300      * Create a new BIO_ADDR
301      */
302     addr = BIO_ADDR_new();
303     if (addr == NULL) {
304         fprintf(stderr, "Unable to create BIO_ADDR\n");
305         goto err;
306     }
307 
308     /*
309      * Build an INADDR_ANY BIO_ADDR
310      */
311     if (!BIO_ADDR_rawmake(addr, AF_INET6, &in6addr_any, sizeof(in6addr_any), htons(port))) {
312         fprintf(stderr, "unable to bind to port %d\n", port);
313         goto err;
314     }
315 
316     /* Bind to the new UDP socket */
317     if (!BIO_bind(fd, addr, 0)) {
318         fprintf(stderr, "cannot bind to %u\n", port);
319         goto err;
320     }
321 
322     /*
323      * Create a new datagram socket
324      */
325     sock = BIO_new(BIO_s_datagram());
326     if (sock == NULL) {
327         fprintf(stderr, "cannot create dgram bio\n");
328         goto err;
329     }
330 
331     /*
332      * associate the underlying socket with the dgram BIO
333      */
334     if (!BIO_set_fd(sock, fd, BIO_CLOSE)) {
335         fprintf(stderr, "Unable to set fd of dgram sock\n");
336         goto err;
337     }
338 
339     /*
340      * Free our allocated addr
341      */
342     BIO_ADDR_free(addr);
343     return sock;
344 
345 err:
346     BIO_ADDR_free(addr);
347     BIO_free(sock);
348     BIO_closesocket(fd);
349     return NULL;
350 }
351 
352 /**
353  * @brief Handles I/O failures on an SSL stream based on the result code.
354  *
355  * This function processes the result of an SSL I/O operation and handles
356  * different types of errors that may occur during the operation. It takes
357  * appropriate actions such as retrying the operation, reporting errors, or
358  * returning specific status codes based on the error type.
359  *
360  * @param ssl A pointer to the SSL object representing the stream.
361  * @param res The result code from the SSL I/O operation.
362  * @return An integer indicating the outcome:
363  *         - 0: EOF, indicating the stream has been closed.
364  *         - -1: A fatal error occurred or the stream has been reset.
365  *
366  *
367  * @note If the failure is due to an SSL verification error, additional
368  * information will be logged to stderr.
369  */
handle_io_failure(SSL * ssl,int res)370 static int handle_io_failure(SSL *ssl, int res)
371 {
372     switch (SSL_get_error(ssl, res)) {
373     case SSL_ERROR_ZERO_RETURN:
374         /* EOF */
375         return 0;
376 
377     case SSL_ERROR_SYSCALL:
378         return -1;
379 
380     case SSL_ERROR_SSL:
381         /*
382          * Some stream fatal error occurred. This could be because of a
383          * stream reset - or some failure occurred on the underlying
384          * connection.
385          */
386         switch (SSL_get_stream_read_state(ssl)) {
387         case SSL_STREAM_STATE_RESET_REMOTE:
388             fprintf(stderr, "Stream reset occurred\n");
389             /*
390              * The stream has been reset but the connection is still
391              * healthy.
392              */
393             break;
394 
395         case SSL_STREAM_STATE_CONN_CLOSED:
396             fprintf(stderr, "Connection closed\n");
397             /* Connection is already closed. */
398             break;
399 
400         default:
401             fprintf(stderr, "Unknown stream failure\n");
402             break;
403         }
404         /*
405          * If the failure is due to a verification error we can get more
406          * information about it from SSL_get_verify_result().
407          */
408         if (SSL_get_verify_result(ssl) != X509_V_OK)
409             fprintf(stderr, "Verify error: %s\n",
410                     X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
411         return -1;
412 
413     default:
414         return -1;
415     }
416 }
417 
418 /**
419  * @brief Processes a new incoming QUIC stream for an HTTP/0.9 GET request.
420  *
421  * This function reads an HTTP/0.9 GET request from the provided QUIC stream,
422  * retrieves the requested file from the server's file system, and sends the
423  * file contents back to the client over the stream.
424  *
425  * @param Pointer to the SSL object representing the QUIC stream.
426  *
427  * Operation:
428  * - Reads the HTTP/0.9 GET request from the client.
429  * - Parses the request to extract the requested file name.
430  * - Constructs the file path using the `fileprefix` directory.
431  * - Reads the requested file in chunks and sends it to the client.
432  * - Concludes the QUIC stream once the file is fully sent.
433  *
434  * Error Handling:
435  * - If the request is invalid or the file cannot be opened, appropriate
436  *   error messages are logged, and the function exits without sending data.
437  * - Errors during file reading or writing to the stream are handled, with
438  *   retries for buffer-related issues (e.g., full send buffer).
439  *
440  * Notes:
441  * - The request is expected to be a valid HTTP/0.9 GET request.
442  * - File paths are sanitized to prevent path traversal vulnerabilities.
443  * - The function uses blocking operations for reading and writing data.
444  *
445  * Usage:
446  * - Called for each accepted QUIC stream to handle client requests.
447  */
process_new_stream(SSL * stream)448 static void process_new_stream(SSL *stream)
449 {
450     unsigned char buf[BUF_SIZE];
451     char path[BUF_SIZE];
452     char *req = (char *)buf;
453     char *reqname;
454     char *creturn;
455     size_t nread;
456     BIO *readbio;
457     size_t bytes_read = 0;
458     size_t bytes_written = 0;
459     size_t offset = 0;
460     int rc;
461     int ret;
462     size_t total_read = 0;
463 
464     memset(buf, 0, BUF_SIZE);
465     for (;;) {
466         nread = 0;
467         ret = SSL_read_ex(stream, &buf[total_read],
468                           sizeof(buf) - total_read - 1, &nread);
469         total_read += nread;
470         if (ret <= 0) {
471             ret = handle_io_failure(stream, ret);
472             if (ret == 0) {
473                 /* EOF condition, fin bit set, we got the whole request */
474                 break;
475             } else {
476                 /* permanent failure, abort */
477                 fprintf(stderr, "Failure on stream\n");
478                 return;
479             }
480         }
481     }
482 
483     /* We should have a valid http 0.9 GET request here */
484     fprintf(stderr, "Request is %s\n", req);
485 
486     /* Look for the last '/' char in the request */
487     reqname = strrchr(req, '/');
488     if (reqname == NULL)
489         return;
490     reqname++;
491 
492     /* Requests have a trailing \r\n, eliminate them */
493     creturn = strchr(reqname, '\r');
494     if (creturn != NULL)
495         *creturn = '\0';
496 
497     snprintf(path, BUF_SIZE, "%s/%s", fileprefix, reqname);
498 
499     fprintf(stderr, "Serving %s\n", path);
500     readbio = BIO_new_file(path, "r");
501     if (readbio == NULL) {
502         fprintf(stderr, "Unable to open %s\n", path);
503         ERR_print_errors_fp(stderr);
504         goto done;
505     }
506 
507     /* Read the readbio file into a buffer, and just send it to the requestor */
508     while (BIO_eof(readbio) <= 0) {
509         bytes_read = 0;
510         if (!BIO_read_ex(readbio, buf, BUF_SIZE, &bytes_read)) {
511             if (BIO_eof(readbio) <= 0) {
512                 fprintf(stderr, "Failed to read from %s\n", path);
513                 ERR_print_errors_fp(stderr);
514                 goto out;
515             } else {
516                 break;
517             }
518         }
519 
520         offset = 0;
521         for (;;) {
522             bytes_written = 0;
523             rc = SSL_write_ex(stream, &buf[offset], bytes_read, &bytes_written);
524             if (rc <= 0) {
525                 rc = SSL_get_error(stream, rc);
526                 switch (rc) {
527                 case SSL_ERROR_WANT_WRITE:
528                     fprintf(stderr, "Send buffer full, retrying\n");
529                     continue;
530                     break;
531                 default:
532                     fprintf(stderr, "Unhandled error cause %d\n", rc);
533                     goto done;
534                     break;
535                 }
536             }
537             bytes_read -= bytes_written;
538             offset += bytes_written;
539             bytes_written = 0;
540             if (bytes_read == 0)
541                 break;
542         }
543     }
544 
545 done:
546     if (!SSL_stream_conclude(stream, 0))
547         fprintf(stderr, "Failed to conclude stream\n");
548 
549 out:
550     BIO_free(readbio);
551     return;
552 }
553 
554 /**
555  * @brief Runs the QUIC server to accept and handle client connections.
556  *
557  * This function initializes a QUIC listener, binds it to the provided UDP
558  * socket, and enters a loop to accept client connections and process incoming
559  * QUIC streams. Each connection is handled until termination, and streams are
560  * processed individually using the `process_new_stream` function.
561  *
562  * @param ctx Pointer to the SSL_CTX object configured for QUIC.
563  * @param sock  BIO of the bound UDP socket.
564  *
565  * @return Returns 0 on error; otherwise, the server runs indefinitely.
566  *
567  * Operation:
568  * - Creates a QUIC listener using the provided SSL_CTX and associates it
569  *   with the specified UDP socket.
570  * - Waits for incoming QUIC connections and accepts them.
571  * - For each connection:
572  *   - Accepts incoming streams.
573  *   - Processes each stream using `process_new_stream`.
574  *   - Shuts down the connection upon completion.
575  *
576  * Error Handling:
577  * - If listener creation or connection acceptance fails, the function logs
578  *   an error message and exits the loop.
579  * - Cleans up allocated resources (e.g., listener, connection) on failure.
580  *
581  * Usage:
582  * - Call this function in the main server loop after setting up the
583  *   SSL_CTX and binding a UDP socket.
584  *
585  * Notes:
586  * - Uses blocking operations for listener, connection, and stream handling.
587  * - Incoming streams are processed based on the configured stream policy.
588  * - The server runs in an infinite loop unless a fatal error occurs.
589  */
run_quic_server(SSL_CTX * ctx,BIO * sock)590 static int run_quic_server(SSL_CTX *ctx, BIO *sock)
591 {
592     int ok = 0;
593     SSL *listener, *conn, *stream;
594     unsigned long errcode;
595     uint64_t flags = 0;
596 
597     /*
598      * If NO_ADDR_VALIDATE exists in our environment
599      * then disable address validation on our listener
600      */
601     if (getenv("NO_ADDR_VALIDATE") != NULL)
602         flags |= SSL_LISTENER_FLAG_NO_VALIDATE;
603 
604     /*
605      * Create a new QUIC listener. Listeners, and other QUIC objects, default
606      * to operating in blocking mode. The configured behaviour is inherited by
607      * child objects.
608      */
609     if ((listener = SSL_new_listener(ctx, flags)) == NULL)
610         goto err;
611 
612     /* Provide the listener with our UDP socket. */
613     SSL_set_bio(listener, sock, sock);
614 
615     /* Begin listening. */
616     if (!SSL_listen(listener))
617         goto err;
618 
619     /*
620      * Begin an infinite loop of listening for connections. We will only
621      * exit this loop if we encounter an error.
622      */
623     for (;;) {
624         /* Pristine error stack for each new connection */
625         ERR_clear_error();
626 
627         /* Block while waiting for a client connection */
628         printf("Waiting for connection\n");
629         conn = SSL_accept_connection(listener, 0);
630         if (conn == NULL) {
631             fprintf(stderr, "error while accepting connection\n");
632             goto err;
633         }
634         printf("Accepted new connection\n");
635 
636         /*
637          * QUIC requires that we inform the connection that
638          * we always want to accept new streams, rather than reject them
639          * Additionally, while we don't make an explicit call here, we
640          * are using the default stream mode, as would be specified by
641          * a call to SSL_set_default_stream_mode
642          */
643         if (!SSL_set_incoming_stream_policy(conn,
644                                             SSL_INCOMING_STREAM_POLICY_ACCEPT,
645                                             0)) {
646             fprintf(stderr, "Failed to set incomming stream policy\n");
647             goto close_conn;
648         }
649 
650         /*
651          * Until the connection is closed, accept incomming stream
652          * requests and serve them
653          */
654         for (;;) {
655             /*
656              * Note that SSL_accept_stream is blocking here, as the
657              * conn SSL object inherited the deafult blocking property
658              * from its parent, the listener SSL object.  As such there
659              * is no need to handle retry failures here.
660              */
661             stream = SSL_accept_stream(conn, 0);
662             if (stream == NULL) {
663                 /*
664                  * If we don't get a stream, either we
665                  * Hit a legitimate error, and should bail out
666                  * or
667                  * The Client closed the connection, and there are no
668                  * more incomming streams expected
669                  *
670                  * Filter on the shutdown error, and only print an error
671                  * message if the cause is not SHUTDOWN
672                  */
673                 ERR_print_errors_fp(stderr);
674                 errcode = ERR_get_error();
675                 if (ERR_GET_REASON(errcode) != SSL_R_PROTOCOL_IS_SHUTDOWN)
676                     fprintf(stderr, "Failure in accept stream, error %s\n",
677                             ERR_reason_error_string(errcode));
678                 break;
679             }
680             process_new_stream(stream);
681             SSL_free(stream);
682         }
683 
684         /*
685          * Shut down the connection. We may need to call this multiple times
686          * to ensure the connection is shutdown completely.
687          */
688 close_conn:
689         while (SSL_shutdown(conn) != 1)
690             continue;
691 
692         SSL_free(conn);
693     }
694 
695 err:
696     SSL_free(listener);
697     return ok;
698 }
699 
700 /**
701  * @brief Entry point for the minimal QUIC HTTP/0.9 server.
702  *
703  * This function initializes the server, sets up a QUIC context, binds a UDP
704  * socket to the specified port, and starts the main QUIC server loop to handle
705  * client connections and requests.
706  *
707  * @param argc Number of command-line arguments.
708  * @param argv Array of command-line arguments:
709  *             - argv[0]: Program name.
710  *             - argv[1]: Port number to bind the server.
711  *             - argv[2]: Path to the server's certificate file (PEM format).
712  *             - argv[3]: Path to the server's private key file (PEM format).
713  *
714  * @return Returns EXIT_SUCCESS on successful execution, or EXIT_FAILURE
715  *         on error.
716  *
717  * Operation:
718  * - Validates the command-line arguments.
719  * - Reads the FILEPREFIX environment variable to set the file prefix for
720  *   serving files (default is "./downloads").
721  * - Creates an SSL_CTX with QUIC support using the provided certificate and
722  *   key files.
723  * - Parses and validates the port number.
724  * - Creates and binds a UDP socket to the specified port.
725  * - Starts the server loop using `run_quic_server` to accept and process
726  *   client connections.
727  *
728  * Error Handling:
729  * - If any initialization step fails (e.g., invalid arguments, socket
730  *   creation, context setup), appropriate error messages are logged, and
731  *   the program exits with EXIT_FAILURE.
732  *
733  * Usage:
734  * - Run the program with the required arguments to start the server:
735  *   `./server <port> <server.crt> <server.key>`
736  *
737  * Notes:
738  * - Ensure that the certificate and key files exist and are valid.
739  * - The server serves files from the directory specified by FILEPREFIX.
740  */
main(int argc,char * argv[])741 int main(int argc, char *argv[])
742 {
743     int res = EXIT_FAILURE;
744     SSL_CTX *ctx = NULL;
745     BIO *sock = NULL;
746     unsigned long port;
747 
748     if (argc != 4) {
749         fprintf(stderr, "usage: %s <port> <server.crt> <server.key>\n", argv[0]);
750         goto out;
751     }
752 
753     fileprefix = getenv("FILEPREFIX");
754     if (fileprefix == NULL)
755         fileprefix = "./downloads";
756 
757     fprintf(stderr, "Fileprefix is %s\n", fileprefix);
758 
759     /* Create SSL_CTX that supports QUIC. */
760     if ((ctx = create_ctx(argv[2], argv[3])) == NULL) {
761         ERR_print_errors_fp(stderr);
762         fprintf(stderr, "Failed to create context\n");
763         goto out;
764     }
765 
766     /* Parse port number from command line arguments. */
767     port = strtoul(argv[1], NULL, 0);
768     if (port == 0 || port > UINT16_MAX) {
769         fprintf(stderr, "Failed to parse port number\n");
770         goto out;
771     }
772     fprintf(stderr, "Binding to port %lu\n", port);
773 
774     /* Create and bind a UDP socket. */
775     if ((sock = create_socket((uint16_t)port)) == NULL) {
776         ERR_print_errors_fp(stderr);
777         fprintf(stderr, "Failed to create socket\n");
778         goto out;
779     }
780 
781     /* QUIC server connection acceptance loop. */
782     if (!run_quic_server(ctx, sock)) {
783         ERR_print_errors_fp(stderr);
784         fprintf(stderr, "Failed to run quic server\n");
785         goto out;
786     }
787 
788     res = EXIT_SUCCESS;
789 out:
790     /* Free resources. */
791     SSL_CTX_free(ctx);
792     BIO_free(sock);
793     return res;
794 }
795