xref: /freebsd/crypto/openssl/demos/bio/server-cmod.c (revision e0c4386e7e71d93b0edc0c8fa156263fc4a8b0b6)
1 /*
2  * Copyright 2015-2017 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  * A minimal TLS server it ses SSL_CTX_config and a configuration file to
12  * set most server parameters.
13  */
14 
15 #include <stdio.h>
16 #include <signal.h>
17 #include <stdlib.h>
18 #include <openssl/err.h>
19 #include <openssl/ssl.h>
20 #include <openssl/conf.h>
21 
main(int argc,char * argv[])22 int main(int argc, char *argv[])
23 {
24     unsigned char buf[512];
25     char *port = "*:4433";
26     BIO *in = NULL;
27     BIO *ssl_bio, *tmp;
28     SSL_CTX *ctx;
29     int ret = EXIT_FAILURE, i;
30 
31     ctx = SSL_CTX_new(TLS_server_method());
32 
33     if (CONF_modules_load_file("cmod.cnf", "testapp", 0) <= 0) {
34         fprintf(stderr, "Error processing config file\n");
35         goto err;
36     }
37 
38     if (SSL_CTX_config(ctx, "server") == 0) {
39         fprintf(stderr, "Error configuring server.\n");
40         goto err;
41     }
42 
43     /* Setup server side SSL bio */
44     ssl_bio = BIO_new_ssl(ctx, 0);
45 
46     if ((in = BIO_new_accept(port)) == NULL)
47         goto err;
48 
49     /*
50      * This means that when a new connection is accepted on 'in', The ssl_bio
51      * will be 'duplicated' and have the new socket BIO push into it.
52      * Basically it means the SSL BIO will be automatically setup
53      */
54     BIO_set_accept_bios(in, ssl_bio);
55 
56  again:
57     /*
58      * The first call will setup the accept socket, and the second will get a
59      * socket.  In this loop, the first actual accept will occur in the
60      * BIO_read() function.
61      */
62 
63     if (BIO_do_accept(in) <= 0)
64         goto err;
65 
66     for (;;) {
67         i = BIO_read(in, buf, sizeof(buf));
68         if (i == 0) {
69             /*
70              * If we have finished, remove the underlying BIO stack so the
71              * next time we call any function for this BIO, it will attempt
72              * to do an accept
73              */
74             printf("Done\n");
75             tmp = BIO_pop(in);
76             BIO_free_all(tmp);
77             goto again;
78         }
79         if (i < 0) {
80             if (BIO_should_retry(in))
81                 continue;
82             goto err;
83         }
84         fwrite(buf, 1, i, stdout);
85         fflush(stdout);
86     }
87 
88     ret = EXIT_SUCCESS;
89  err:
90     if (ret != EXIT_SUCCESS)
91         ERR_print_errors_fp(stderr);
92     BIO_free(in);
93     return ret;
94 }
95