Skip to content

Instantly share code, notes, and snippets.

@francisbrito
Last active August 29, 2015 14:23
Show Gist options
  • Save francisbrito/dcc4032cf593db1d6c44 to your computer and use it in GitHub Desktop.
Save francisbrito/dcc4032cf593db1d6c44 to your computer and use it in GitHub Desktop.
Custom BIOs
#include <string.h>
#include <stdlib.h>
#include "custom_bio.h"
BIO_METHOD dotter_method = {
BIO_TYPE_FILTER,
"dotter filter",
dotter_write,
dotter_read,
NULL,
NULL,
NULL,
dotter_new,
NULL,
NULL
};
BIO_METHOD* BIO_f_dotter() {
return &dotter_method;
}
BIO_METHOD dasher_method = {
BIO_TYPE_FILTER,
"dasher filter",
dasher_write,
dasher_read,
NULL,
NULL,
NULL,
dasher_new,
NULL,
NULL
};
BIO_METHOD* BIO_f_dasher() {
return &dasher_method;
}
int dotter_write(BIO* b, const char* text, int len) {
if (text == NULL || len <= 0 || b->next_bio == NULL) return 0;
int new_len = len * 2, i = 0;
char new_text[new_len];
for(; i < new_len; i++) {
new_text[i] = i % 2 == 0 ? '.' : text[i / 2];
}
return BIO_write(b->next_bio, new_text, new_len);
}
int dotter_read(BIO* b, char* text, int len) {
if (text == NULL || len <= 0 || b->next_bio == NULL) return 0;
return BIO_read(b->next_bio, text, len);
}
int dotter_new(BIO* b) {
b->init = 1; // BIOs need to be initialized.
return 1;
}
int dasher_write(BIO* b, const char* text, int len) {
if (text == NULL || len <= 0 || b->next_bio == NULL) return 0;
int new_len = len * 2, i = 0;
char new_text[new_len];
for(; i < new_len; i++) {
new_text[i] = i % 2 != 0 ? '-' : text[i / 2];
}
return BIO_write(b->next_bio, new_text, new_len);
}
int dasher_read(BIO* b, char* text, int len) {
if (text == NULL || len <= 0 || b->next_bio == NULL) return 0;
return BIO_read(b->next_bio, text, len);
}
int dasher_new(BIO* b) {
b->init = 1; // BIOs need to be initialized.
return 1;
}
#ifndef __CUSTOM_BIO__
#define __CUSTOM_BIO__
#include <openssl/bio.h>
BIO_METHOD* BIO_f_dotter();
BIO_METHOD* BIO_f_dasher();
int dotter_write(BIO*, const char*, int);
int dotter_read(BIO*, char*, int);
int dotter_new(BIO*);
int dasher_write(BIO*, const char*, int);
int dasher_read(BIO*, char*, int);
int dasher_new(BIO*);
#endif
#include <string.h>
#include <stdlib.h>
#include "custom_bio.h"
int main(int argc, char const *argv[]) {
BIO *dotter, *dasher, *stdout_bio;
dotter = BIO_new(BIO_f_dotter());
dasher = BIO_new(BIO_f_dasher());
stdout_bio = BIO_new_fp(stdout, BIO_NOCLOSE);
// input -> dotter -> dasher -> output.
BIO_push(dotter, dasher);
BIO_push(dasher, stdout_bio);
const char text[] = "foobar";
BIO_write(dotter, text, strlen(text));
BIO_flush(dotter);
BIO_free_all(dotter);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment