]> git.ipfire.org Git - thirdparty/openssl.git/blame - demos/bio/saccept.c
Server side version negotiation rewrite
[thirdparty/openssl.git] / demos / bio / saccept.c
CommitLineData
d02b48c6
RE
1/* NOCW */
2/* demos/bio/saccept.c */
3
23a22b4c
MC
4/*-
5 * A minimal program to serve an SSL connection.
d02b48c6
RE
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 *
f3efeaad 11 * cc -I../../include saccept.c -L../.. -lssl -lcrypto -ldl
d02b48c6
RE
12 */
13
14#include <stdio.h>
15#include <signal.h>
ec577822
BM
16#include <openssl/err.h>
17#include <openssl/ssl.h>
d02b48c6 18
0f113f3e 19#define CERT_FILE "server.pem"
d02b48c6 20
0f113f3e 21BIO *in = NULL;
d02b48c6
RE
22
23void close_up()
0f113f3e 24{
ca3a82c3 25 BIO_free(in);
0f113f3e 26}
d02b48c6 27
24f77b34 28int main(int argc, char *argv[])
0f113f3e
MC
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
32ec4153 48 ctx = SSL_CTX_new(TLS_server_method());
0f113f3e
MC
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 }
ca3a82c3 103 BIO_free(in);
0f113f3e
MC
104 exit(ret);
105 return (!ret);
106}