chris chris - 1 year ago 112
Perl Question

OpenSSL and Threads in Perl XS

I am working with OpenSSL inside a Perl-XS-Module. I have a C-function that calls OpenSSL-API-functions. It is very simple for test-purposes (init openssl, read a key, make the RSA-object and use it, no arguments). No big checks needed and addresses and memory are ok.

XS is standard h2xs with

in the

void _foo (void)
unsigned char key [3000];
memset (key, 0, 3000);
printf ("\ninit=%d", SSL_library_init ()); // init
FILE *f = fopen ("key.key","r");
printf ("\nf=%d", f);
int keysize = fread (key, 1, 3000, f); // readin
printf ("\nn=%d",keysize);
fclose (f);
printf ("\nkey=%s", key);

BIO *bio = BIO_new_mem_buf (key, keysize);
printf ("\nbio=%ld", bio);
RSA *pk = (RSA *) PEM_read_bio_RSAPrivateKey (bio, NULL, NULL, NULL);
printf ("\npk=%ld", pk);

printf ("\nsz=%d" ,RSA_size(pk)); // ***** crash here if in a perl-thread
printf ("\n\n");

That is working if I do pure C/C++. It is also ok if I have it in the XS-Module and use it in Perl outside a thread. But it crashes if I have it in Perl and inside a thread.

Now I would say that is because I do not have any thread-handling. But if I have a look into other Perl-Modules (e.g. Crypt::OpenSSL::RSA) I do not find and special thread-handling there too.

I am pretty new to XS and maybe I miss something. Maybe someone can give me a hint, thanks!

Answer Source

I found out the answer. I am not sure about it and I do not like it but it seems to be legit.

I have a lot of openssl-includes in my xs. But I did not include ssl.h.

#include <openssl/ssl.h>

No compile-error, no linker-error. Only a segmentation-fault if I use it in threads. Works even outside threads.

If I include the h-file it works all fine. Even without the added openssl-mutex-thread-handling.

Found out after I tried to make my sample "pretty" to post it here. That is a bit weird.... I would prefer an compiler-error...

But it explains why the other module is working.

Thanks for help!!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download