wahern / luaossl

Most comprehensive OpenSSL module in the Lua universe.
http://25thandclement.com/~william/projects/luaossl.html
Other
142 stars 48 forks source link

How to turn an ffi pointer to SSL* into a luaossl object? #121

Closed daurnimator closed 6 years ago

daurnimator commented 6 years ago

In some code, I have a pointer to an SSL* in the form of a LuaJIT ffi pointer. How can I get a luaossl SSL* userdata of this pointer?

For the interim, I've come up with the following little module:

/* Compile with:

gcc -shared -Wall -Wextra -I /usr/include/luajit-2.0/ -o pushssl.so pushssl.c
*/

#include <lua.h>
#include <lauxlib.h>
#define LUA_TCDATA 10

#include <openssl/ssl.h>
#if (!(OPENSSL_VERSION_NUMBER < 0x10100001L || defined LIBRESSL_VERSION_NUMBER))
#define HAVE_OPENSSL11_API 1
#else
#define HAVE_OPENSSL11_API 0
#endif

#ifndef HAVE_SSL_UP_REF
#define HAVE_SSL_UP_REF HAVE_OPENSSL11_API
#endif

#if !HAVE_SSL_UP_REF
#include <openssl/crypto.h>
#define SSL_up_ref(ssl) CRYPTO_add(&(ssl)->references, 1, CRYPTO_LOCK_SSL)
#endif

static int pushssl(lua_State *L) {
    SSL **ptr = NULL;
    SSL **ssl;

    luaL_checktype(L, 1, LUA_TCDATA);
    ptr = (SSL**)lua_topointer(L, 1);
    luaL_argcheck(L, ptr, 1, "SSL* cdata must be non-null");

    ssl = lua_newuserdata(L, sizeof *ssl);
    *ssl = *ptr;

    luaL_getmetatable(L, "SSL*");
    if (lua_isnil(L, -1))
        return 0;

    if (!SSL_up_ref(*ssl))
        return 0;

    lua_setmetatable(L, -2);
    return 1;
}

int luaopen_pushssl(lua_State *L) {
    lua_pushcfunction(L, pushssl);
    return 1;
}

Is there anything luaossl could include to help with this?

daurnimator commented 6 years ago

One feature I'd like if possible is pushing the same pointer returning the same object. Should be possible with a weak table indexed by lightuserdata of pointer.

daurnimator commented 6 years ago

https://gist.github.com/daurnimator/0cd557db935317280e55af7dbd1e086f