Run util/openssl-format-source -v -c .
[oweals/openssl.git] / demos / bio / saccept.c
1 /* NOCW */
2 /* demos/bio/saccept.c */
3
4 /*-
5  * A minimal program to serve an SSL connection.
6  * It uses blocking.
7  * saccept host:port
8  * host is the interface IP to use.  If any interface, use *:port
9  * The default it *:4433
10  *
11  * cc -I../../include saccept.c -L../.. -lssl -lcrypto -ldl
12  */
13
14 #include <stdio.h>
15 #include <signal.h>
16 #include <openssl/err.h>
17 #include <openssl/ssl.h>
18
19 #define CERT_FILE       "server.pem"
20
21 BIO *in = NULL;
22
23 void close_up()
24 {
25     if (in != NULL)
26         BIO_free(in);
27 }
28
29 int main(int argc, char *argv[])
30 {
31     char *port = NULL;
32     BIO *ssl_bio, *tmp;
33     SSL_CTX *ctx;
34     char buf[512];
35     int ret = 1, i;
36
37     if (argc <= 1)
38         port = "*:4433";
39     else
40         port = argv[1];
41
42     signal(SIGINT, close_up);
43
44     SSL_load_error_strings();
45
46     /* Add ciphers and message digests */
47     OpenSSL_add_ssl_algorithms();
48
49     ctx = SSL_CTX_new(SSLv23_server_method());
50     if (!SSL_CTX_use_certificate_file(ctx, CERT_FILE, SSL_FILETYPE_PEM))
51         goto err;
52     if (!SSL_CTX_use_PrivateKey_file(ctx, CERT_FILE, SSL_FILETYPE_PEM))
53         goto err;
54     if (!SSL_CTX_check_private_key(ctx))
55         goto err;
56
57     /* Setup server side SSL bio */
58     ssl_bio = BIO_new_ssl(ctx, 0);
59
60     if ((in = BIO_new_accept(port)) == NULL)
61         goto err;
62
63     /*
64      * This means that when a new connection is accepted on 'in', The ssl_bio
65      * will be 'duplicated' and have the new socket BIO push into it.
66      * Basically it means the SSL BIO will be automatically setup
67      */
68     BIO_set_accept_bios(in, ssl_bio);
69
70  again:
71     /*
72      * The first call will setup the accept socket, and the second will get a
73      * socket.  In this loop, the first actual accept will occur in the
74      * BIO_read() function.
75      */
76
77     if (BIO_do_accept(in) <= 0)
78         goto err;
79
80     for (;;) {
81         i = BIO_read(in, buf, 512);
82         if (i == 0) {
83             /*
84              * If we have finished, remove the underlying BIO stack so the
85              * next time we call any function for this BIO, it will attempt
86              * to do an accept
87              */
88             printf("Done\n");
89             tmp = BIO_pop(in);
90             BIO_free_all(tmp);
91             goto again;
92         }
93         if (i < 0)
94             goto err;
95         fwrite(buf, 1, i, stdout);
96         fflush(stdout);
97     }
98
99     ret = 0;
100  err:
101     if (ret) {
102         ERR_print_errors_fp(stderr);
103     }
104     if (in != NULL)
105         BIO_free(in);
106     exit(ret);
107     return (!ret);
108 }