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