0d173aa039a700cef5882704cc5373ca49b775e6
[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     BIO_free(in);
26 }
27
28 int main(int argc, char *argv[])
29 {
30     char *port = NULL;
31     BIO *ssl_bio, *tmp;
32     SSL_CTX *ctx;
33     char buf[512];
34     int ret = 1, i;
35
36     if (argc <= 1)
37         port = "*:4433";
38     else
39         port = argv[1];
40
41     signal(SIGINT, close_up);
42
43     SSL_load_error_strings();
44
45     /* Add ciphers and message digests */
46     OpenSSL_add_ssl_algorithms();
47
48     ctx = SSL_CTX_new(TLS_server_method());
49     if (!SSL_CTX_use_certificate_file(ctx, CERT_FILE, SSL_FILETYPE_PEM))
50         goto err;
51     if (!SSL_CTX_use_PrivateKey_file(ctx, CERT_FILE, SSL_FILETYPE_PEM))
52         goto err;
53     if (!SSL_CTX_check_private_key(ctx))
54         goto err;
55
56     /* Setup server side SSL bio */
57     ssl_bio = BIO_new_ssl(ctx, 0);
58
59     if ((in = BIO_new_accept(port)) == NULL)
60         goto err;
61
62     /*
63      * This means that when a new connection is accepted on 'in', The ssl_bio
64      * will be 'duplicated' and have the new socket BIO push into it.
65      * Basically it means the SSL BIO will be automatically setup
66      */
67     BIO_set_accept_bios(in, ssl_bio);
68
69  again:
70     /*
71      * The first call will setup the accept socket, and the second will get a
72      * socket.  In this loop, the first actual accept will occur in the
73      * BIO_read() function.
74      */
75
76     if (BIO_do_accept(in) <= 0)
77         goto err;
78
79     for (;;) {
80         i = BIO_read(in, buf, 512);
81         if (i == 0) {
82             /*
83              * If we have finished, remove the underlying BIO stack so the
84              * next time we call any function for this BIO, it will attempt
85              * to do an accept
86              */
87             printf("Done\n");
88             tmp = BIO_pop(in);
89             BIO_free_all(tmp);
90             goto again;
91         }
92         if (i < 0)
93             goto err;
94         fwrite(buf, 1, i, stdout);
95         fflush(stdout);
96     }
97
98     ret = 0;
99  err:
100     if (ret) {
101         ERR_print_errors_fp(stderr);
102     }
103     BIO_free(in);
104     exit(ret);
105     return (!ret);
106 }