Tutorial 10: OpenSSL 1: A simple connection without any security Using BIO
Following programs are basic implementation of BIO library. BIO is a abstraction library used to handle communication of various kinds, including files and sockets, both secure and not.for both secure and unsecure communication .
Note:
These programs are only for testing purpose and not optimize for production use. there may be some extra lines on code which are not used and still not removed. You will need openssl installed in your server to compile these programs.
You can compile these two programs using
gcc server.c -lssl -o server
gcc client.c -lssl -o client
Server:
Note:
These programs are only for testing purpose and not optimize for production use. there may be some extra lines on code which are not used and still not removed. You will need openssl installed in your server to compile these programs.
You can compile these two programs using
gcc server.c -lssl -o server
gcc client.c -lssl -o client
Server:
#include <stdio.h>
#include <string .h> //for memset
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/bio.h>
#define MAXCHARS 1024
int main(int argc, char *argv[]) {
SSL_load_error_strings();
OpenSSL_add_all_algorithms();
char buf[MAXCHARS];
BIO *bio;
if((bio = BIO_new_accept("port")) == NULL) {
ERR_print_errors_fp(stderr);
exit(1);
}
if(BIO_do_accept(bio) <= 0) {
ERR_print_errors_fp(stderr);
exit(1);
}
for (;;){
int x = BIO_read(bio, buf, sizeof(buf));
if(x == 0)
{
//break; if any connection is closed this will break the loop
continue;
}
else if(x < 0)
{
if(! BIO_should_retry(bio))
{
printf("X<0 failed read\n");
break;
}
printf("X<0 retry positive\n");
}
else if(BIO_write(bio, buf, strlen(buf)) <= 0)
{
if(! BIO_should_retry(bio))
{
printf("Should retry error\n");
}
printf("Should retry positive\n");
}
else
{
printf("%s\n",buf);
memset(buf,'\0',sizeof(buf));
}
}
BIO_free(bio);
return 0;
}
Client:
#include <stdio.h>
#include <string.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/bio.h>
#define MAXCHARS 1024
int main(int argc, char *argv[]) {
SSL_load_error_strings();
OpenSSL_add_all_algorithms();
char buf[MAXCHARS];
BIO *my_bio;
if((my_bio = BIO_new_connect("host:port")) == NULL) {
ERR_print_errors_fp(stderr);
exit(1);
}
if(BIO_do_accept(my_bio) <= 0) {
ERR_print_errors_fp(stderr);
exit(1);
}
while(fgets(buf,sizeof(buf), stdin)!=NULL)
{
if(BIO_write(my_bio, buf, strlen(buf)) <= 0)
{
if(! BIO_should_retry(my_bio))
{
printf("Should retry error\n");
}
printf("Should retry positive\n");
}
else {
int x = BIO_read(my_bio, buf, sizeof(buf));
if(x == 0)
{
break;
}
else if(x < 0)
{
if(! BIO_should_retry(my_bio))
{
printf("X<0 failed read\n");
break;
}
printf("X<0 retry positive\n");
}
else printf("the response is %s\n");
}
}
BIO_free(my_bio);
return 0;
}
Comments
Post a Comment