lm_ssl.c
author Myhailo Danylenko <isbear@ukrpost.net>
Wed, 16 Mar 2016 01:53:56 +0200
changeset 66 a40beb82130c
parent 62 d92358eafead
permissions -rw-r--r--
node: Use new loudmouth feature - public attribute list (v0.9.7)

/* Copyright 2009-2016 Myhailo Danylenko

This file is part of lua-lm.

lua-lm is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#include <lua.h>
#include <lauxlib.h>
#include <glib.h>
#include <loudmouth/loudmouth.h>
#include <stdio.h>

#include "config.h"
#include "util.h"
#include "lm_types.h"

/// lm.ssl
/// Object, containing information about ssl abilities for connection.
/// Create, set parameters, and attach to connection with 'ssl' method.

/// ssl status
/// String, representing what problem have current ssl session.
/// G:
const string2enum_t status_lm_ssl[] = {
	{ "no cert found",             LM_SSL_STATUS_NO_CERT_FOUND             },
	{ "untrusted cert",            LM_SSL_STATUS_UNTRUSTED_CERT            },
	{ "cert expired",              LM_SSL_STATUS_CERT_EXPIRED              },
	{ "cert not activated",        LM_SSL_STATUS_CERT_NOT_ACTIVATED        },
	{ "cert hostname mismatch",    LM_SSL_STATUS_CERT_HOSTNAME_MISMATCH    },
	{ "cert fingerprint mismatch", LM_SSL_STATUS_CERT_FINGERPRINT_MISMATCH },
	{ "generic error",             LM_SSL_STATUS_GENERIC_ERROR             },
	{ NULL,                        0                                       }, // XXX
};

/// ssl callback function
/// User function, called when ssl error happens.
/// A: userdata (lm ssl object), argument enum field (ssl status)
/// R: boolean (false if connection process should be terminated)
LmSSLResponse callback_lm_ssl (LmSSL *ssl, LmSSLStatus status, llm_callback_t *cb)
{
	int ret;
	lua_rawgeti (cb->L, LUA_REGISTRYINDEX, cb->reference);
	bless_lm_ssl (cb->L, ssl);
	// XXX lm_ssl_unref (ssl);
	luaL_pushenum (cb->L, status, status_lm_ssl);
	if (lua_pcall (cb->L, 2, 1, 0)) {
		W ("SSL callback error: %s", lua_tostring (cb->L, -1));
		lua_pop (cb->L, 1);
		return LM_SSL_RESPONSE_CONTINUE;
	}
	ret = lua_toboolean (cb->L, -1);
	lua_pop (cb->L, 1);
	if (ret)
		return LM_SSL_RESPONSE_CONTINUE;
	else
		return LM_SSL_RESPONSE_STOP;
}

#ifndef HAVE_LM_SHA256_FINGERPRINTS
static void string2fingerprint (const char *string, char *buffer)
{
	int i;
	for (i = 0; i < 16; i++) {
		int h = g_ascii_xdigit_value ((char)string[i*3]);
		int l = g_ascii_xdigit_value ((char)string[i*3+1]);
		buffer[i] = (char) ((h >= 0 && l >= 0) ? h*16 + l : 0);
	}
}
#endif

/// lm.ssl.new
/// Creates new ssl object for use with connection.
/// You can specify server key fingerprint, callback function for error handling,
/// both, or neither. Though, fingerprint should go before callback function.
/// SSL fingerprint is a string like 'SHA256:ABCDEF123456...' (or
/// '01:23:45:67:89:AB:CD:EF:FE:DC:BA:98:76:54:32:10' for LM versions, older than 1.5.3).
/// A: string (optional ssl fingerprint), ssl callback function (optional)
/// R: userdata (lm ssl object)
static int new_lm_ssl (lua_State *L)
{
	int args = lua_gettop (L);
	LmSSL *ssl;
	if (args == 0)
		ssl = lm_ssl_new (NULL, NULL, NULL, NULL);
	else if (args == 1 && !lua_isfunction (L, 1)) {
		const char *fingerprint = luaL_checkstring (L, 1);
#ifndef HAVE_LM_SHA256_FINGERPRINTS
		gchar buffer[16] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";

		if (lua_rawlen (L, 1) > 46) {
			string2fingerprint (fingerprint, buffer);
			fingerprint = buffer;
		} else
			fingerprint = NULL;
#endif
		ssl = lm_ssl_new (fingerprint, NULL, NULL, NULL);
	} else {
		llm_callback_t *cb;
		const char *fingerprint = NULL;

		if (args > 1) {
			fingerprint = luaL_checkstring (L, 1);
#ifndef HAVE_LM_SHA256_FINGERPRINTS
			gchar buffer[16] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";

			if (lua_rawlen (L, 1) > 46) {
				string2fingerprint (fingerprint, buffer);
				fingerprint = buffer;
			} else
				fingerprint = NULL;
#endif
			luaL_argcheck (L, lua_isfunction (L, 2), 2, "function expected");
		} else
			luaL_argcheck (L, lua_isfunction (L, 1), 1, "function expected");
		
		cb = luaL_malloc (L, sizeof (llm_callback_t));
		cb->reference = luaL_ref (L, LUA_REGISTRYINDEX);
		cb->L = L;

		ssl = lm_ssl_new (fingerprint, (LmSSLFunction)callback_lm_ssl,
							cb, (GDestroyNotify)llm_callback_destroy);
	}
	bless_lm_ssl (L, ssl);
	lm_ssl_unref (ssl); // XXX
	D ("SSL %p created", ssl);
	return 1;
}

/// lm.ssl.bless
/// Blesses given pointer to lm ssl object.
/// A: lightuserdata (C lm ssl object)
/// R: userdata (lm ssl object)
static int bless_lua_lm_ssl (lua_State *L)
{
	luaL_argcheck (L, lua_islightuserdata (L, 1), 1, "lm ssl lightuserdata expected");
	bless_lm_ssl (L, lua_touserdata (L, 1));
	return 1;
}

/// lm.ssl.supported
/// Indicates if SSL is supported by loudmouth library and what kind of
/// ssl fingerprint is used.
/// R: nil or string ("MD5" or "SHA256")
static int supported_lm_ssl (lua_State *L)
{
	if (lm_ssl_is_supported ()) {
#ifdef HAVE_LM_SHA256_FINGERPRINTS
		lua_pushliteral (L, "SHA256");
#else
		lua_pushliteral (L, "MD5");
#endif
	} else {
		lua_pushnil (L);
	}
	return 1;
}

#ifdef HAVE_LM_SSL_SET_CA
/// ssl:ca_path
/// Set path to trusted ssl certificates. Argument must be a name of a PEM file
/// or a name of directory with hashed certificates.
/// A: string (path)
/// R: lm ssl object
static int ca_path_lm_ssl (lua_State *L)
{
	llm_ssl_t *object = luaL_checklm_ssl (L, 1);
	const gchar *path = luaL_checkstring (L, 2);
	lm_ssl_set_ca (object -> ssl, path);
	lua_pop (L, 1);
	return 1;
}
#endif

#ifdef HAVE_LM_SSL_SET_CIPHER_LIST
/// ssl:cipher_list
/// Set list of allowed ciphers (colon-separated). Names may vary depending on ssl
/// implementation in use.
/// A: string (cipher list)
/// R: lm ssl object
static int cipher_list_lm_ssl (lua_State *L)
{
	llm_ssl_t *object = luaL_checklm_ssl (L, 1);
	const gchar *list = luaL_checkstring (L, 2);
	lm_ssl_set_cipher_list (object -> ssl, list);
	lua_pop (L, 1);
	return 1;
}
#endif

/// ssl:fingerprint
/// Returns fingerprint of remote server.
/// R: string or nil
static int fingerprint_lm_ssl (lua_State *L)
{
	llm_ssl_t *object = luaL_checklm_ssl (L, 1);
	const gchar *fingerprint = lm_ssl_get_fingerprint (object->ssl);
	if (fingerprint == NULL)
		lua_pushnil (L);
	else {
#ifdef HAVE_LM_SHA256_FINGERPRINTS
		lua_pushstring (L, fingerprint);
#else
		char buffer[48];
		snprintf (buffer, 48,
			  "%02hhX:%02hhX:%02hhX:%02hhX:%02hhX:%02hhX:%02hhX:%02hhX:"
			  "%02hhX:%02hhX:%02hhX:%02hhX:%02hhX:%02hhX:%02hhX:%02hhX",
			  fingerprint[0], fingerprint[1], fingerprint[2], fingerprint[3],
			  fingerprint[4], fingerprint[5], fingerprint[6], fingerprint[7],
			  fingerprint[8], fingerprint[9], fingerprint[10], fingerprint[11],
			  fingerprint[12], fingerprint[13], fingerprint[14], fingerprint[15]);
		lua_pushlstring (L, buffer, 47);
#endif
	}
	return 1;
}

/// ssl:tls
/// Sets or returns use of starttls by this ssl object.
/// A: boolean (use starttls), boolean (require starttls)
/// or
/// R: boolean (use starttls), boolean (require starttls)
static int tls_lm_ssl (lua_State *L)
{
	llm_ssl_t *object = luaL_checklm_ssl (L, 1);
	if (lua_gettop (L) > 1) {
		gboolean use     = lua_toboolean (L, 2);
		gboolean require = lua_toboolean (L, 3);
		lm_ssl_use_starttls (object -> ssl, use, require);
		return 0;
	} else {
		lua_pushboolean (L, lm_ssl_get_use_starttls (object -> ssl));
		lua_pushboolean (L, lm_ssl_get_require_starttls (object -> ssl));
		return 2;
	}
}

/// ssl:pointer
/// Returns pointer to underlying C structure.
/// R: lightuserdata
static int pointer_lm_ssl (lua_State *L)
{
	llm_ssl_t *object = luaL_checklm_ssl (L, 1);
	lua_pushlightuserdata (L, object->ssl);
	return 1;
}

static int gc_lm_ssl (lua_State *L)
{
	llm_ssl_t *object = luaL_checklm_ssl (L, 1);
	D ("SSL %p gc called", object);
	lm_ssl_unref (object->ssl);
	return 0;
}

const static luaL_Reg reg_f_lm_ssl[] = {
	{ "new",       new_lm_ssl       },
	{ "bless",     bless_lua_lm_ssl },
	{ "supported", supported_lm_ssl },
	{ NULL,        NULL             },
};

const static luaL_Reg reg_m_lm_ssl[] = {
#ifdef HAVE_LM_SSL_SET_CA
	{ "ca_path",     ca_path_lm_ssl     },
#endif
#ifdef HAVE_LM_SSL_SET_CIPHER_LIST
	{ "cipher_list", cipher_list_lm_ssl },
#endif
	{ "fingerprint", fingerprint_lm_ssl },
	{ "tls",         tls_lm_ssl         },
	{ "pointer",     pointer_lm_ssl     },
	{ "__gc",        gc_lm_ssl          },
	{ NULL,          NULL               },
};

int luaopen_lm_ssl (lua_State *L)
{
	luaL_newmetatable (L, "loudmouth.ssl");
	lua_pushvalue (L, -1);
	lua_setfield (L, -2, "__index");
	luaL_setfuncs (L, reg_m_lm_ssl, 0);
	lua_pop (L, 1);
	lua_newtable (L); // XXX we can specify here exact amount of fields
	luaL_setfuncs (L, reg_f_lm_ssl, 0);
	return 1;
}