aboutsummaryrefslogtreecommitdiffstats
path: root/util-src
diff options
context:
space:
mode:
Diffstat (limited to 'util-src')
-rw-r--r--util-src/Makefile41
-rw-r--r--util-src/Makefile.win38
-rw-r--r--util-src/encodings.c395
-rw-r--r--util-src/hashes.c206
-rw-r--r--util-src/make.bat1
-rw-r--r--util-src/pposix.c761
-rw-r--r--util-src/signal.c412
-rw-r--r--util-src/windows.c89
8 files changed, 1943 insertions, 0 deletions
diff --git a/util-src/Makefile b/util-src/Makefile
new file mode 100644
index 00000000..90d65e51
--- /dev/null
+++ b/util-src/Makefile
@@ -0,0 +1,41 @@
+
+include ../config.unix
+
+LUA_SUFFIX?=5.1
+LUA_INCDIR?=/usr/include/lua$(LUA_SUFFIX)
+LUA_LIB?=lua$(LUA_SUFFIX)
+IDN_LIB?=idn
+OPENSSL_LIB?=crypto
+CC?=gcc
+CXX?=g++
+LD?=gcc
+CFLAGS+=-ggdb
+
+.PHONY: all install clean
+.SUFFIXES: .c .o .so
+
+all: encodings.so hashes.so pposix.so signal.so
+
+install: encodings.so hashes.so pposix.so signal.so
+ install *.so ../util/
+
+clean:
+ rm -f *.o
+ rm -f *.so
+ rm -f ../util/*.so
+
+encodings.so: encodings.o
+ MACOSX_DEPLOYMENT_TARGET="10.3"; export MACOSX_DEPLOYMENT_TARGET;
+ $(CC) -o $@ $< $(LDFLAGS) $(IDNA_LIBS)
+
+hashes.so: hashes.o
+ MACOSX_DEPLOYMENT_TARGET="10.3"; export MACOSX_DEPLOYMENT_TARGET;
+ $(CC) -o $@ $< $(LDFLAGS) -l$(OPENSSL_LIB)
+
+.c.o:
+ $(CC) $(CFLAGS) -I$(LUA_INCDIR) -c -o $@ $<
+
+.o.so:
+ MACOSX_DEPLOYMENT_TARGET="10.3"; export MACOSX_DEPLOYMENT_TARGET;
+ $(LD) -o $@ $< $(LDFLAGS)
+
diff --git a/util-src/Makefile.win b/util-src/Makefile.win
new file mode 100644
index 00000000..7b141097
--- /dev/null
+++ b/util-src/Makefile.win
@@ -0,0 +1,38 @@
+
+LUA_PATH=$(LUA_DEV)
+IDN_PATH=..\..\libidn-1.15
+OPENSSL_PATH=..\..\openssl-0.9.8k
+
+LUA_INCLUDE=$(LUA_PATH)\include
+LUA_LIB=$(LUA_PATH)\lib\lua5.1.lib
+
+IDN_LIB=$(IDN_PATH)\win32\lib\libidn.lib
+IDN_INCLUDE1=$(IDN_PATH)\lib
+IDN_INCLUDE2=$(IDN_PATH)\win32\include
+OPENSSL_LIB=$(OPENSSL_PATH)\out32dll\libeay32.lib
+OPENSSL_INCLUDE=$(OPENSSL_PATH)\include
+
+CL=cl /LD /MD /nologo
+
+all: encodings.dll hashes.dll windows.dll
+
+install: encodings.dll hashes.dll windows.dll
+ copy /Y *.dll ..\util\
+
+clean:
+ del encodings.dll encodings.exp encodings.lib encodings.obj encodings.dll.manifest
+ del hashes.dll hashes.exp hashes.lib hashes.obj hashes.dll.manifest
+ del windows.dll windows.exp windows.lib windows.obj windows.dll.manifest
+
+encodings.dll: encodings.c
+ $(CL) encodings.c /I"$(LUA_INCLUDE)" /I"$(IDN_INCLUDE1)" /I"$(IDN_INCLUDE2)" /link "$(LUA_LIB)" "$(IDN_LIB)" /export:luaopen_util_encodings
+ del encodings.exp encodings.lib encodings.obj encodings.dll.manifest
+
+hashes.dll: hashes.c
+ $(CL) hashes.c /I"$(LUA_INCLUDE)" /I"$(OPENSSL_INCLUDE)" /link "$(LUA_LIB)" "$(OPENSSL_LIB)" /export:luaopen_util_hashes
+ del hashes.exp hashes.lib hashes.obj hashes.dll.manifest
+
+windows.dll: windows.c
+ $(CL) windows.c /I"$(LUA_INCLUDE)" /link "$(LUA_LIB)" dnsapi.lib /export:luaopen_util_windows
+ del windows.exp windows.lib windows.obj windows.dll.manifest
+
diff --git a/util-src/encodings.c b/util-src/encodings.c
new file mode 100644
index 00000000..b9b6160a
--- /dev/null
+++ b/util-src/encodings.c
@@ -0,0 +1,395 @@
+/* Prosody IM
+-- Copyright (C) 2008-2010 Matthew Wild
+-- Copyright (C) 2008-2010 Waqas Hussain
+--
+-- This project is MIT/X11 licensed. Please see the
+-- COPYING file in the source package for more information.
+--
+*/
+
+/*
+* encodings.c
+* Lua library for base64, stringprep and idna encodings
+*/
+
+/* Newer MSVC compilers deprecate strcpy as unsafe, but we use it in a safe way */
+#define _CRT_SECURE_NO_DEPRECATE
+
+#include <string.h>
+#include <stdlib.h>
+#include "lua.h"
+#include "lauxlib.h"
+
+/***************** BASE64 *****************/
+
+static const char code[]=
+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+static void base64_encode(luaL_Buffer *b, unsigned int c1, unsigned int c2, unsigned int c3, int n)
+{
+ unsigned long tuple=c3+256UL*(c2+256UL*c1);
+ int i;
+ char s[4];
+ for (i=0; i<4; i++) {
+ s[3-i] = code[tuple % 64];
+ tuple /= 64;
+ }
+ for (i=n+1; i<4; i++) s[i]='=';
+ luaL_addlstring(b,s,4);
+}
+
+static int Lbase64_encode(lua_State *L) /** encode(s) */
+{
+ size_t l;
+ const unsigned char *s=(const unsigned char*)luaL_checklstring(L,1,&l);
+ luaL_Buffer b;
+ int n;
+ luaL_buffinit(L,&b);
+ for (n=l/3; n--; s+=3) base64_encode(&b,s[0],s[1],s[2],3);
+ switch (l%3)
+ {
+ case 1: base64_encode(&b,s[0],0,0,1); break;
+ case 2: base64_encode(&b,s[0],s[1],0,2); break;
+ }
+ luaL_pushresult(&b);
+ return 1;
+}
+
+static void base64_decode(luaL_Buffer *b, int c1, int c2, int c3, int c4, int n)
+{
+ unsigned long tuple=c4+64L*(c3+64L*(c2+64L*c1));
+ char s[3];
+ switch (--n)
+ {
+ case 3: s[2]=(char) tuple;
+ case 2: s[1]=(char) (tuple >> 8);
+ case 1: s[0]=(char) (tuple >> 16);
+ }
+ luaL_addlstring(b,s,n);
+}
+
+static int Lbase64_decode(lua_State *L) /** decode(s) */
+{
+ size_t l;
+ const char *s=luaL_checklstring(L,1,&l);
+ luaL_Buffer b;
+ int n=0;
+ char t[4];
+ luaL_buffinit(L,&b);
+ for (;;)
+ {
+ int c=*s++;
+ switch (c)
+ {
+ const char *p;
+ default:
+ p=strchr(code,c); if (p==NULL) return 0;
+ t[n++]= (char) (p-code);
+ if (n==4)
+ {
+ base64_decode(&b,t[0],t[1],t[2],t[3],4);
+ n=0;
+ }
+ break;
+ case '=':
+ switch (n)
+ {
+ case 1: base64_decode(&b,t[0],0,0,0,1); break;
+ case 2: base64_decode(&b,t[0],t[1],0,0,2); break;
+ case 3: base64_decode(&b,t[0],t[1],t[2],0,3); break;
+ }
+ n=0;
+ break;
+ case 0:
+ luaL_pushresult(&b);
+ return 1;
+ case '\n': case '\r': case '\t': case ' ': case '\f': case '\b':
+ break;
+ }
+ }
+}
+
+static const luaL_Reg Reg_base64[] =
+{
+ { "encode", Lbase64_encode },
+ { "decode", Lbase64_decode },
+ { NULL, NULL }
+};
+
+/***************** STRINGPREP *****************/
+#ifdef USE_STRINGPREP_ICU
+
+#include <unicode/usprep.h>
+#include <unicode/ustring.h>
+#include <unicode/utrace.h>
+
+static int icu_stringprep_prep(lua_State *L, const UStringPrepProfile *profile)
+{
+ size_t input_len;
+ int32_t unprepped_len, prepped_len, output_len;
+ const char *input;
+ char output[1024];
+
+ UChar unprepped[1024]; /* Temporary unicode buffer (1024 characters) */
+ UChar prepped[1024];
+
+ UErrorCode err = U_ZERO_ERROR;
+
+ if(!lua_isstring(L, 1)) {
+ lua_pushnil(L);
+ return 1;
+ }
+ input = lua_tolstring(L, 1, &input_len);
+ if (input_len >= 1024) {
+ lua_pushnil(L);
+ return 1;
+ }
+ u_strFromUTF8(unprepped, 1024, &unprepped_len, input, input_len, &err);
+ if (U_FAILURE(err)) {
+ lua_pushnil(L);
+ return 1;
+ }
+ prepped_len = usprep_prepare(profile, unprepped, unprepped_len, prepped, 1024, 0, NULL, &err);
+ if (U_FAILURE(err)) {
+ lua_pushnil(L);
+ return 1;
+ } else {
+ u_strToUTF8(output, 1024, &output_len, prepped, prepped_len, &err);
+ if (U_SUCCESS(err) && output_len < 1024)
+ lua_pushlstring(L, output, output_len);
+ else
+ lua_pushnil(L);
+ return 1;
+ }
+}
+
+UStringPrepProfile *icu_nameprep;
+UStringPrepProfile *icu_nodeprep;
+UStringPrepProfile *icu_resourceprep;
+UStringPrepProfile *icu_saslprep;
+
+/* initialize global ICU stringprep profiles */
+void init_icu()
+{
+ UErrorCode err = U_ZERO_ERROR;
+ utrace_setLevel(UTRACE_VERBOSE);
+ icu_nameprep = usprep_openByType(USPREP_RFC3491_NAMEPREP, &err);
+ icu_nodeprep = usprep_openByType(USPREP_RFC3920_NODEPREP, &err);
+ icu_resourceprep = usprep_openByType(USPREP_RFC3920_RESOURCEPREP, &err);
+ icu_saslprep = usprep_openByType(USPREP_RFC4013_SASLPREP, &err);
+ if (U_FAILURE(err)) fprintf(stderr, "[c] util.encodings: error: %s\n", u_errorName((UErrorCode)err));
+}
+
+#define MAKE_PREP_FUNC(myFunc, prep) \
+static int myFunc(lua_State *L) { return icu_stringprep_prep(L, prep); }
+
+MAKE_PREP_FUNC(Lstringprep_nameprep, icu_nameprep) /** stringprep.nameprep(s) */
+MAKE_PREP_FUNC(Lstringprep_nodeprep, icu_nodeprep) /** stringprep.nodeprep(s) */
+MAKE_PREP_FUNC(Lstringprep_resourceprep, icu_resourceprep) /** stringprep.resourceprep(s) */
+MAKE_PREP_FUNC(Lstringprep_saslprep, icu_saslprep) /** stringprep.saslprep(s) */
+
+static const luaL_Reg Reg_stringprep[] =
+{
+ { "nameprep", Lstringprep_nameprep },
+ { "nodeprep", Lstringprep_nodeprep },
+ { "resourceprep", Lstringprep_resourceprep },
+ { "saslprep", Lstringprep_saslprep },
+ { NULL, NULL }
+};
+#else /* USE_STRINGPREP_ICU */
+
+/****************** libidn ********************/
+
+#include <stringprep.h>
+
+static int stringprep_prep(lua_State *L, const Stringprep_profile *profile)
+{
+ size_t len;
+ const char *s;
+ char string[1024];
+ int ret;
+ if(!lua_isstring(L, 1)) {
+ lua_pushnil(L);
+ return 1;
+ }
+ s = lua_tolstring(L, 1, &len);
+ if (len >= 1024) {
+ lua_pushnil(L);
+ return 1; /* TODO return error message */
+ }
+ strcpy(string, s);
+ ret = stringprep(string, 1024, (Stringprep_profile_flags)0, profile);
+ if (ret == STRINGPREP_OK) {
+ lua_pushstring(L, string);
+ return 1;
+ } else {
+ lua_pushnil(L);
+ return 1; /* TODO return error message */
+ }
+}
+
+#define MAKE_PREP_FUNC(myFunc, prep) \
+static int myFunc(lua_State *L) { return stringprep_prep(L, prep); }
+
+MAKE_PREP_FUNC(Lstringprep_nameprep, stringprep_nameprep) /** stringprep.nameprep(s) */
+MAKE_PREP_FUNC(Lstringprep_nodeprep, stringprep_xmpp_nodeprep) /** stringprep.nodeprep(s) */
+MAKE_PREP_FUNC(Lstringprep_resourceprep, stringprep_xmpp_resourceprep) /** stringprep.resourceprep(s) */
+MAKE_PREP_FUNC(Lstringprep_saslprep, stringprep_saslprep) /** stringprep.saslprep(s) */
+
+static const luaL_Reg Reg_stringprep[] =
+{
+ { "nameprep", Lstringprep_nameprep },
+ { "nodeprep", Lstringprep_nodeprep },
+ { "resourceprep", Lstringprep_resourceprep },
+ { "saslprep", Lstringprep_saslprep },
+ { NULL, NULL }
+};
+#endif
+
+/***************** IDNA *****************/
+#ifdef USE_STRINGPREP_ICU
+#include <unicode/ustdio.h>
+#include <unicode/uidna.h>
+/* IDNA2003 or IDNA2008 ? ? ? */
+static int Lidna_to_ascii(lua_State *L) /** idna.to_ascii(s) */
+{
+ size_t len;
+ int32_t ulen, dest_len, output_len;
+ const char *s = luaL_checklstring(L, 1, &len);
+ UChar ustr[1024];
+ UErrorCode err = U_ZERO_ERROR;
+ UChar dest[1024];
+ char output[1024];
+
+ u_strFromUTF8(ustr, 1024, &ulen, s, len, &err);
+ if (U_FAILURE(err)) {
+ lua_pushnil(L);
+ return 1;
+ }
+
+ dest_len = uidna_IDNToASCII(ustr, ulen, dest, 1024, UIDNA_USE_STD3_RULES, NULL, &err);
+ if (U_FAILURE(err)) {
+ lua_pushnil(L);
+ return 1;
+ } else {
+ u_strToUTF8(output, 1024, &output_len, dest, dest_len, &err);
+ if (U_SUCCESS(err) && output_len < 1024)
+ lua_pushlstring(L, output, output_len);
+ else
+ lua_pushnil(L);
+ return 1;
+ }
+}
+
+static int Lidna_to_unicode(lua_State *L) /** idna.to_unicode(s) */
+{
+ size_t len;
+ int32_t ulen, dest_len, output_len;
+ const char *s = luaL_checklstring(L, 1, &len);
+ UChar ustr[1024];
+ UErrorCode err = U_ZERO_ERROR;
+ UChar dest[1024];
+ char output[1024];
+
+ u_strFromUTF8(ustr, 1024, &ulen, s, len, &err);
+ if (U_FAILURE(err)) {
+ lua_pushnil(L);
+ return 1;
+ }
+
+ dest_len = uidna_IDNToUnicode(ustr, ulen, dest, 1024, UIDNA_USE_STD3_RULES, NULL, &err);
+ if (U_FAILURE(err)) {
+ lua_pushnil(L);
+ return 1;
+ } else {
+ u_strToUTF8(output, 1024, &output_len, dest, dest_len, &err);
+ if (U_SUCCESS(err) && output_len < 1024)
+ lua_pushlstring(L, output, output_len);
+ else
+ lua_pushnil(L);
+ return 1;
+ }
+}
+
+#else /* USE_STRINGPREP_ICU */
+/****************** libidn ********************/
+
+#include <idna.h>
+#include <idn-free.h>
+
+static int Lidna_to_ascii(lua_State *L) /** idna.to_ascii(s) */
+{
+ size_t len;
+ const char *s = luaL_checklstring(L, 1, &len);
+ char* output = NULL;
+ int ret = idna_to_ascii_8z(s, &output, IDNA_USE_STD3_ASCII_RULES);
+ if (ret == IDNA_SUCCESS) {
+ lua_pushstring(L, output);
+ idn_free(output);
+ return 1;
+ } else {
+ lua_pushnil(L);
+ idn_free(output);
+ return 1; /* TODO return error message */
+ }
+}
+
+static int Lidna_to_unicode(lua_State *L) /** idna.to_unicode(s) */
+{
+ size_t len;
+ const char *s = luaL_checklstring(L, 1, &len);
+ char* output = NULL;
+ int ret = idna_to_unicode_8z8z(s, &output, 0);
+ if (ret == IDNA_SUCCESS) {
+ lua_pushstring(L, output);
+ idn_free(output);
+ return 1;
+ } else {
+ lua_pushnil(L);
+ idn_free(output);
+ return 1; /* TODO return error message */
+ }
+}
+#endif
+
+static const luaL_Reg Reg_idna[] =
+{
+ { "to_ascii", Lidna_to_ascii },
+ { "to_unicode", Lidna_to_unicode },
+ { NULL, NULL }
+};
+
+/***************** end *****************/
+
+static const luaL_Reg Reg[] =
+{
+ { NULL, NULL }
+};
+
+LUALIB_API int luaopen_util_encodings(lua_State *L)
+{
+#ifdef USE_STRINGPREP_ICU
+ init_icu();
+#endif
+ luaL_register(L, "encodings", Reg);
+
+ lua_pushliteral(L, "base64");
+ lua_newtable(L);
+ luaL_register(L, NULL, Reg_base64);
+ lua_settable(L,-3);
+
+ lua_pushliteral(L, "stringprep");
+ lua_newtable(L);
+ luaL_register(L, NULL, Reg_stringprep);
+ lua_settable(L,-3);
+
+ lua_pushliteral(L, "idna");
+ lua_newtable(L);
+ luaL_register(L, NULL, Reg_idna);
+ lua_settable(L,-3);
+
+ lua_pushliteral(L, "version"); /** version */
+ lua_pushliteral(L, "-3.14");
+ lua_settable(L,-3);
+ return 1;
+}
diff --git a/util-src/hashes.c b/util-src/hashes.c
new file mode 100644
index 00000000..8f7d7140
--- /dev/null
+++ b/util-src/hashes.c
@@ -0,0 +1,206 @@
+/* Prosody IM
+-- Copyright (C) 2009-2010 Matthew Wild
+-- Copyright (C) 2009-2010 Waqas Hussain
+--
+-- This project is MIT/X11 licensed. Please see the
+-- COPYING file in the source package for more information.
+--
+*/
+
+
+/*
+* hashes.c
+* Lua library for sha1, sha256 and md5 hashes
+*/
+
+#include <string.h>
+#include <stdlib.h>
+#include <inttypes.h>
+
+#include "lua.h"
+#include "lauxlib.h"
+#include <openssl/sha.h>
+#include <openssl/md5.h>
+
+#define HMAC_IPAD 0x36363636
+#define HMAC_OPAD 0x5c5c5c5c
+
+const char *hex_tab = "0123456789abcdef";
+void toHex(const unsigned char *in, int length, unsigned char *out) {
+ int i;
+ for (i = 0; i < length; i++) {
+ out[i*2] = hex_tab[(in[i] >> 4) & 0xF];
+ out[i*2+1] = hex_tab[(in[i]) & 0xF];
+ }
+}
+
+#define MAKE_HASH_FUNCTION(myFunc, func, size) \
+static int myFunc(lua_State *L) { \
+ size_t len; \
+ const char *s = luaL_checklstring(L, 1, &len); \
+ int hex_out = lua_toboolean(L, 2); \
+ unsigned char hash[size], result[size*2]; \
+ func((const unsigned char*)s, len, hash); \
+ if (hex_out) { \
+ toHex(hash, size, result); \
+ lua_pushlstring(L, (char*)result, size*2); \
+ } else { \
+ lua_pushlstring(L, (char*)hash, size);\
+ } \
+ return 1; \
+}
+
+MAKE_HASH_FUNCTION(Lsha1, SHA1, SHA_DIGEST_LENGTH)
+MAKE_HASH_FUNCTION(Lsha224, SHA224, SHA224_DIGEST_LENGTH)
+MAKE_HASH_FUNCTION(Lsha256, SHA256, SHA256_DIGEST_LENGTH)
+MAKE_HASH_FUNCTION(Lsha384, SHA384, SHA384_DIGEST_LENGTH)
+MAKE_HASH_FUNCTION(Lsha512, SHA512, SHA512_DIGEST_LENGTH)
+MAKE_HASH_FUNCTION(Lmd5, MD5, MD5_DIGEST_LENGTH)
+
+struct hash_desc {
+ int (*Init)(void*);
+ int (*Update)(void*, const void *, size_t);
+ int (*Final)(unsigned char*, void*);
+ size_t digestLength;
+ void *ctx, *ctxo;
+};
+
+static void hmac(struct hash_desc *desc, const char *key, size_t key_len,
+ const char *msg, size_t msg_len, unsigned char *result)
+{
+ union xory {
+ unsigned char bytes[64];
+ uint32_t quadbytes[16];
+ };
+
+ int i;
+ char hashedKey[64]; /* Maximum used digest length */
+ union xory k_ipad, k_opad;
+
+ if (key_len > 64) {
+ desc->Init(desc->ctx);
+ desc->Update(desc->ctx, key, key_len);
+ desc->Final(desc->ctx, hashedKey);
+ key = (const char*)hashedKey;
+ key_len = desc->digestLength;
+ }
+
+ memcpy(k_ipad.bytes, key, key_len);
+ memset(k_ipad.bytes + key_len, 0, 64 - key_len);
+ memcpy(k_opad.bytes, k_ipad.bytes, 64);
+
+ for (i = 0; i < 16; i++) {
+ k_ipad.quadbytes[i] ^= HMAC_IPAD;
+ k_opad.quadbytes[i] ^= HMAC_OPAD;
+ }
+
+ desc->Init(desc->ctx);
+ desc->Update(desc->ctx, k_ipad.bytes, 64);
+ desc->Init(desc->ctxo);
+ desc->Update(desc->ctxo, k_opad.bytes, 64);
+ desc->Update(desc->ctx, msg, msg_len);
+ desc->Final(result, desc->ctx);
+ desc->Update(desc->ctxo, result, desc->digestLength);
+ desc->Final(result, desc->ctxo);
+}
+
+#define MAKE_HMAC_FUNCTION(myFunc, func, size, type) \
+static int myFunc(lua_State *L) { \
+ type ctx, ctxo; \
+ unsigned char hash[size], result[2*size]; \
+ size_t key_len, msg_len; \
+ const char *key = luaL_checklstring(L, 1, &key_len); \
+ const char *msg = luaL_checklstring(L, 2, &msg_len); \
+ const int hex_out = lua_toboolean(L, 3); \
+ struct hash_desc desc; \
+ desc.Init = (int (*)(void*))func##_Init; \
+ desc.Update = (int (*)(void*, const void *, size_t))func##_Update; \
+ desc.Final = (int (*)(unsigned char*, void*))func##_Final; \
+ desc.digestLength = size; \
+ desc.ctx = &ctx; \
+ desc.ctxo = &ctxo; \
+ hmac(&desc, key, key_len, msg, msg_len, hash); \
+ if (hex_out) { \
+ toHex(hash, size, result); \
+ lua_pushlstring(L, (char*)result, size*2); \
+ } else { \
+ lua_pushlstring(L, (char*)hash, size); \
+ } \
+ return 1; \
+}
+
+MAKE_HMAC_FUNCTION(Lhmac_sha1, SHA1, SHA_DIGEST_LENGTH, SHA_CTX)
+MAKE_HMAC_FUNCTION(Lhmac_sha256, SHA256, SHA256_DIGEST_LENGTH, SHA256_CTX)
+MAKE_HMAC_FUNCTION(Lhmac_sha512, SHA512, SHA512_DIGEST_LENGTH, SHA512_CTX)
+MAKE_HMAC_FUNCTION(Lhmac_md5, MD5, MD5_DIGEST_LENGTH, MD5_CTX)
+
+static int LscramHi(lua_State *L) {
+ union xory {
+ unsigned char bytes[SHA_DIGEST_LENGTH];
+ uint32_t quadbytes[SHA_DIGEST_LENGTH/4];
+ };
+ int i;
+ SHA_CTX ctx, ctxo;
+ unsigned char Ust[SHA_DIGEST_LENGTH];
+ union xory Und;
+ union xory res;
+ size_t str_len, salt_len;
+ struct hash_desc desc;
+ const char *str = luaL_checklstring(L, 1, &str_len);
+ const char *salt = luaL_checklstring(L, 2, &salt_len);
+ char *salt2;
+ const int iter = luaL_checkinteger(L, 3);
+
+ desc.Init = (int (*)(void*))SHA1_Init;
+ desc.Update = (int (*)(void*, const void *, size_t))SHA1_Update;
+ desc.Final = (int (*)(unsigned char*, void*))SHA1_Final;
+ desc.digestLength = SHA_DIGEST_LENGTH;
+ desc.ctx = &ctx;
+ desc.ctxo = &ctxo;
+
+ salt2 = malloc(salt_len + 4);
+ if (salt2 == NULL)
+ luaL_error(L, "Out of memory in scramHi");
+ memcpy(salt2, salt, salt_len);
+ memcpy(salt2 + salt_len, "\0\0\0\1", 4);
+ hmac(&desc, str, str_len, salt2, salt_len + 4, Ust);
+ free(salt2);
+
+ memcpy(res.bytes, Ust, sizeof(res));
+ for (i = 1; i < iter; i++) {
+ int j;
+ hmac(&desc, str, str_len, (char*)Ust, sizeof(Ust), Und.bytes);
+ for (j = 0; j < SHA_DIGEST_LENGTH/4; j++)
+ res.quadbytes[j] ^= Und.quadbytes[j];
+ memcpy(Ust, Und.bytes, sizeof(Ust));
+ }
+
+ lua_pushlstring(L, (char*)res.bytes, SHA_DIGEST_LENGTH);
+
+ return 1;
+}
+
+static const luaL_Reg Reg[] =
+{
+ { "sha1", Lsha1 },
+ { "sha224", Lsha224 },
+ { "sha256", Lsha256 },
+ { "sha384", Lsha384 },
+ { "sha512", Lsha512 },
+ { "md5", Lmd5 },
+ { "hmac_sha1", Lhmac_sha1 },
+ { "hmac_sha256", Lhmac_sha256 },
+ { "hmac_sha512", Lhmac_sha512 },
+ { "hmac_md5", Lhmac_md5 },
+ { "scram_Hi_sha1", LscramHi },
+ { NULL, NULL }
+};
+
+LUALIB_API int luaopen_util_hashes(lua_State *L)
+{
+ luaL_register(L, "hashes", Reg);
+ lua_pushliteral(L, "version"); /** version */
+ lua_pushliteral(L, "-3.14");
+ lua_settable(L,-3);
+ return 1;
+}
diff --git a/util-src/make.bat b/util-src/make.bat
new file mode 100644
index 00000000..07858296
--- /dev/null
+++ b/util-src/make.bat
@@ -0,0 +1 @@
+@nmake /nologo /f Makefile.win %* \ No newline at end of file
diff --git a/util-src/pposix.c b/util-src/pposix.c
new file mode 100644
index 00000000..f5cc8270
--- /dev/null
+++ b/util-src/pposix.c
@@ -0,0 +1,761 @@
+/* Prosody IM
+-- Copyright (C) 2008-2010 Matthew Wild
+-- Copyright (C) 2008-2010 Waqas Hussain
+-- Copyright (C) 2009 Tobias Markmann
+--
+-- This project is MIT/X11 licensed. Please see the
+-- COPYING file in the source package for more information.
+--
+*/
+
+/*
+* pposix.c
+* POSIX support functions for Lua
+*/
+
+#define MODULE_VERSION "0.3.6"
+
+#include <stdlib.h>
+#include <math.h>
+#include <unistd.h>
+#include <libgen.h>
+#include <sys/resource.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/utsname.h>
+#include <fcntl.h>
+
+#include <syslog.h>
+#include <pwd.h>
+#include <grp.h>
+
+#include <string.h>
+#include <errno.h>
+#include "lua.h"
+#include "lualib.h"
+#include "lauxlib.h"
+
+#include <fcntl.h>
+#if defined(_GNU_SOURCE)
+#include <linux/falloc.h>
+#endif
+
+#if (defined(_SVID_SOURCE) && !defined(WITHOUT_MALLINFO))
+ #include <malloc.h>
+ #define WITH_MALLINFO
+#endif
+
+/* Daemonization support */
+
+static int lc_daemonize(lua_State *L)
+{
+
+ pid_t pid;
+
+ if ( getppid() == 1 )
+ {
+ lua_pushboolean(L, 0);
+ lua_pushstring(L, "already-daemonized");
+ return 2;
+ }
+
+ /* Attempt initial fork */
+ if((pid = fork()) < 0)
+ {
+ /* Forking failed */
+ lua_pushboolean(L, 0);
+ lua_pushstring(L, "fork-failed");
+ return 2;
+ }
+ else if(pid != 0)
+ {
+ /* We are the parent process */
+ lua_pushboolean(L, 1);
+ lua_pushnumber(L, pid);
+ return 2;
+ }
+
+ /* and we are the child process */
+ if(setsid() == -1)
+ {
+ /* We failed to become session leader */
+ /* (we probably already were) */
+ lua_pushboolean(L, 0);
+ lua_pushstring(L, "setsid-failed");
+ return 2;
+ }
+
+ /* Close stdin, stdout, stderr */
+ close(0);
+ close(1);
+ close(2);
+ /* Make sure accidental use of FDs 0, 1, 2 don't cause weirdness */
+ open("/dev/null", O_RDONLY);
+ open("/dev/null", O_WRONLY);
+ open("/dev/null", O_WRONLY);
+
+ /* Final fork, use it wisely */
+ if(fork())
+ exit(0);
+
+ /* Show's over, let's continue */
+ lua_pushboolean(L, 1);
+ lua_pushnil(L);
+ return 2;
+}
+
+/* Syslog support */
+
+const char * const facility_strings[] = {
+ "auth",
+#if !(defined(sun) || defined(__sun))
+ "authpriv",
+#endif
+ "cron",
+ "daemon",
+#if !(defined(sun) || defined(__sun))
+ "ftp",
+#endif
+ "kern",
+ "local0",
+ "local1",
+ "local2",
+ "local3",
+ "local4",
+ "local5",
+ "local6",
+ "local7",
+ "lpr",
+ "mail",
+ "syslog",
+ "user",
+ "uucp",
+ NULL
+ };
+int facility_constants[] = {
+ LOG_AUTH,
+#if !(defined(sun) || defined(__sun))
+ LOG_AUTHPRIV,
+#endif
+ LOG_CRON,
+ LOG_DAEMON,
+#if !(defined(sun) || defined(__sun))
+ LOG_FTP,
+#endif
+ LOG_KERN,
+ LOG_LOCAL0,
+ LOG_LOCAL1,
+ LOG_LOCAL2,
+ LOG_LOCAL3,
+ LOG_LOCAL4,
+ LOG_LOCAL5,
+ LOG_LOCAL6,
+ LOG_LOCAL7,
+ LOG_LPR,
+ LOG_MAIL,
+ LOG_NEWS,
+ LOG_SYSLOG,
+ LOG_USER,
+ LOG_UUCP,
+ -1
+ };
+
+/* "
+ The parameter ident in the call of openlog() is probably stored as-is.
+ Thus, if the string it points to is changed, syslog() may start
+ prepending the changed string, and if the string it points to ceases to
+ exist, the results are undefined. Most portable is to use a string
+ constant.
+ " -- syslog manpage
+*/
+char* syslog_ident = NULL;
+
+int lc_syslog_open(lua_State* L)
+{
+ int facility = luaL_checkoption(L, 2, "daemon", facility_strings);
+ facility = facility_constants[facility];
+
+ luaL_checkstring(L, 1);
+
+ if(syslog_ident)
+ free(syslog_ident);
+
+ syslog_ident = strdup(lua_tostring(L, 1));
+
+ openlog(syslog_ident, LOG_PID, facility);
+ return 0;
+}
+
+const char * const level_strings[] = {
+ "debug",
+ "info",
+ "notice",
+ "warn",
+ "error",
+ NULL
+ };
+int level_constants[] = {
+ LOG_DEBUG,
+ LOG_INFO,
+ LOG_NOTICE,
+ LOG_WARNING,
+ LOG_CRIT,
+ -1
+ };
+int lc_syslog_log(lua_State* L)
+{
+ int level = level_constants[luaL_checkoption(L, 1, "notice", level_strings)];
+
+ if(lua_gettop(L) == 3)
+ syslog(level, "%s: %s", luaL_checkstring(L, 2), luaL_checkstring(L, 3));
+ else
+ syslog(level, "%s", lua_tostring(L, 2));
+
+ return 0;
+}
+
+int lc_syslog_close(lua_State* L)
+{
+ closelog();
+ if(syslog_ident)
+ {
+ free(syslog_ident);
+ syslog_ident = NULL;
+ }
+ return 0;
+}
+
+int lc_syslog_setmask(lua_State* L)
+{
+ int level_idx = luaL_checkoption(L, 1, "notice", level_strings);
+ int mask = 0;
+ do
+ {
+ mask |= LOG_MASK(level_constants[level_idx]);
+ } while (++level_idx<=4);
+
+ setlogmask(mask);
+ return 0;
+}
+
+/* getpid */
+
+int lc_getpid(lua_State* L)
+{
+ lua_pushinteger(L, getpid());
+ return 1;
+}
+
+/* UID/GID functions */
+
+int lc_getuid(lua_State* L)
+{
+ lua_pushinteger(L, getuid());
+ return 1;
+}
+
+int lc_getgid(lua_State* L)
+{
+ lua_pushinteger(L, getgid());
+ return 1;
+}
+
+int lc_setuid(lua_State* L)
+{
+ int uid = -1;
+ if(lua_gettop(L) < 1)
+ return 0;
+ if(!lua_isnumber(L, 1) && lua_tostring(L, 1))
+ {
+ /* Passed UID is actually a string, so look up the UID */
+ struct passwd *p;
+ p = getpwnam(lua_tostring(L, 1));
+ if(!p)
+ {
+ lua_pushboolean(L, 0);
+ lua_pushstring(L, "no-such-user");
+ return 2;
+ }
+ uid = p->pw_uid;
+ }
+ else
+ {
+ uid = lua_tonumber(L, 1);
+ }
+
+ if(uid>-1)
+ {
+ /* Ok, attempt setuid */
+ errno = 0;
+ if(setuid(uid))
+ {
+ /* Fail */
+ lua_pushboolean(L, 0);
+ switch(errno)
+ {
+ case EINVAL:
+ lua_pushstring(L, "invalid-uid");
+ break;
+ case EPERM:
+ lua_pushstring(L, "permission-denied");
+ break;
+ default:
+ lua_pushstring(L, "unknown-error");
+ }
+ return 2;
+ }
+ else
+ {
+ /* Success! */
+ lua_pushboolean(L, 1);
+ return 1;
+ }
+ }
+
+ /* Seems we couldn't find a valid UID to switch to */
+ lua_pushboolean(L, 0);
+ lua_pushstring(L, "invalid-uid");
+ return 2;
+}
+
+int lc_setgid(lua_State* L)
+{
+ int gid = -1;
+ if(lua_gettop(L) < 1)
+ return 0;
+ if(!lua_isnumber(L, 1) && lua_tostring(L, 1))
+ {
+ /* Passed GID is actually a string, so look up the GID */
+ struct group *g;
+ g = getgrnam(lua_tostring(L, 1));
+ if(!g)
+ {
+ lua_pushboolean(L, 0);
+ lua_pushstring(L, "no-such-group");
+ return 2;
+ }
+ gid = g->gr_gid;
+ }
+ else
+ {
+ gid = lua_tonumber(L, 1);
+ }
+
+ if(gid>-1)
+ {
+ /* Ok, attempt setgid */
+ errno = 0;
+ if(setgid(gid))
+ {
+ /* Fail */
+ lua_pushboolean(L, 0);
+ switch(errno)
+ {
+ case EINVAL:
+ lua_pushstring(L, "invalid-gid");
+ break;
+ case EPERM:
+ lua_pushstring(L, "permission-denied");
+ break;
+ default:
+ lua_pushstring(L, "unknown-error");
+ }
+ return 2;
+ }
+ else
+ {
+ /* Success! */
+ lua_pushboolean(L, 1);
+ return 1;
+ }
+ }
+
+ /* Seems we couldn't find a valid GID to switch to */
+ lua_pushboolean(L, 0);
+ lua_pushstring(L, "invalid-gid");
+ return 2;
+}
+
+int lc_initgroups(lua_State* L)
+{
+ int ret;
+ gid_t gid;
+ struct passwd *p;
+
+ if(!lua_isstring(L, 1))
+ {
+ lua_pushnil(L);
+ lua_pushstring(L, "invalid-username");
+ return 2;
+ }
+ p = getpwnam(lua_tostring(L, 1));
+ if(!p)
+ {
+ lua_pushnil(L);
+ lua_pushstring(L, "no-such-user");
+ return 2;
+ }
+ if(lua_gettop(L) < 2)
+ lua_pushnil(L);
+ switch(lua_type(L, 2))
+ {
+ case LUA_TNIL:
+ gid = p->pw_gid;
+ break;
+ case LUA_TNUMBER:
+ gid = lua_tointeger(L, 2);
+ break;
+ default:
+ lua_pushnil(L);
+ lua_pushstring(L, "invalid-gid");
+ return 2;
+ }
+ ret = initgroups(lua_tostring(L, 1), gid);
+ if(ret)
+ {
+ switch(errno)
+ {
+ case ENOMEM:
+ lua_pushnil(L);
+ lua_pushstring(L, "no-memory");
+ break;
+ case EPERM:
+ lua_pushnil(L);
+ lua_pushstring(L, "permission-denied");
+ break;
+ default:
+ lua_pushnil(L);
+ lua_pushstring(L, "unknown-error");
+ }
+ }
+ else
+ {
+ lua_pushboolean(L, 1);
+ lua_pushnil(L);
+ }
+ return 2;
+}
+
+int lc_umask(lua_State* L)
+{
+ char old_mode_string[7];
+ mode_t old_mode = umask(strtoul(luaL_checkstring(L, 1), NULL, 8));
+
+ snprintf(old_mode_string, sizeof(old_mode_string), "%03o", old_mode);
+ old_mode_string[sizeof(old_mode_string)-1] = 0;
+ lua_pushstring(L, old_mode_string);
+
+ return 1;
+}
+
+int lc_mkdir(lua_State* L)
+{
+ int ret = mkdir(luaL_checkstring(L, 1), S_IRUSR | S_IWUSR | S_IXUSR
+ | S_IRGRP | S_IWGRP | S_IXGRP
+ | S_IROTH | S_IXOTH); /* mode 775 */
+
+ lua_pushboolean(L, ret==0);
+ if(ret)
+ {
+ lua_pushstring(L, strerror(errno));
+ return 2;
+ }
+ return 1;
+}
+
+/* Like POSIX's setrlimit()/getrlimit() API functions.
+ *
+ * Syntax:
+ * pposix.setrlimit( resource, soft limit, hard limit)
+ *
+ * Any negative limit will be replace with the current limit by an additional call of getrlimit().
+ *
+ * Example usage:
+ * pposix.setrlimit("NOFILE", 1000, 2000)
+ */
+int string2resource(const char *s) {
+ if (!strcmp(s, "CORE")) return RLIMIT_CORE;
+ if (!strcmp(s, "CPU")) return RLIMIT_CPU;
+ if (!strcmp(s, "DATA")) return RLIMIT_DATA;
+ if (!strcmp(s, "FSIZE")) return RLIMIT_FSIZE;
+ if (!strcmp(s, "NOFILE")) return RLIMIT_NOFILE;
+ if (!strcmp(s, "STACK")) return RLIMIT_STACK;
+#if !(defined(sun) || defined(__sun))
+ if (!strcmp(s, "MEMLOCK")) return RLIMIT_MEMLOCK;
+ if (!strcmp(s, "NPROC")) return RLIMIT_NPROC;
+ if (!strcmp(s, "RSS")) return RLIMIT_RSS;
+#endif
+#ifdef RLIMIT_NICE
+ if (!strcmp(s, "NICE")) return RLIMIT_NICE;
+#endif
+ return -1;
+}
+
+int lc_setrlimit(lua_State *L) {
+ int arguments = lua_gettop(L);
+ int softlimit = -1;
+ int hardlimit = -1;
+ const char *resource = NULL;
+ int rid = -1;
+ if(arguments < 1 || arguments > 3) {
+ lua_pushboolean(L, 0);
+ lua_pushstring(L, "incorrect-arguments");
+ }
+
+ resource = luaL_checkstring(L, 1);
+ softlimit = luaL_checkinteger(L, 2);
+ hardlimit = luaL_checkinteger(L, 3);
+
+ rid = string2resource(resource);
+ if (rid != -1) {
+ struct rlimit lim;
+ struct rlimit lim_current;
+
+ if (softlimit < 0 || hardlimit < 0) {
+ if (getrlimit(rid, &lim_current)) {
+ lua_pushboolean(L, 0);
+ lua_pushstring(L, "getrlimit-failed");
+ return 2;
+ }
+ }
+
+ if (softlimit < 0) lim.rlim_cur = lim_current.rlim_cur;
+ else lim.rlim_cur = softlimit;
+ if (hardlimit < 0) lim.rlim_max = lim_current.rlim_max;
+ else lim.rlim_max = hardlimit;
+
+ if (setrlimit(rid, &lim)) {
+ lua_pushboolean(L, 0);
+ lua_pushstring(L, "setrlimit-failed");
+ return 2;
+ }
+ } else {
+ /* Unsupported resoucrce. Sorry I'm pretty limited by POSIX standard. */
+ lua_pushboolean(L, 0);
+ lua_pushstring(L, "invalid-resource");
+ return 2;
+ }
+ lua_pushboolean(L, 1);
+ return 1;
+}
+
+int lc_getrlimit(lua_State *L) {
+ int arguments = lua_gettop(L);
+ const char *resource = NULL;
+ int rid = -1;
+ struct rlimit lim;
+
+ if (arguments != 1) {
+ lua_pushboolean(L, 0);
+ lua_pushstring(L, "invalid-arguments");
+ return 2;
+ }
+
+ resource = luaL_checkstring(L, 1);
+ rid = string2resource(resource);
+ if (rid != -1) {
+ if (getrlimit(rid, &lim)) {
+ lua_pushboolean(L, 0);
+ lua_pushstring(L, "getrlimit-failed.");
+ return 2;
+ }
+ } else {
+ /* Unsupported resoucrce. Sorry I'm pretty limited by POSIX standard. */
+ lua_pushboolean(L, 0);
+ lua_pushstring(L, "invalid-resource");
+ return 2;
+ }
+ lua_pushboolean(L, 1);
+ lua_pushnumber(L, lim.rlim_cur);
+ lua_pushnumber(L, lim.rlim_max);
+ return 3;
+}
+
+int lc_abort(lua_State* L)
+{
+ abort();
+ return 0;
+}
+
+int lc_uname(lua_State* L)
+{
+ struct utsname uname_info;
+ if(uname(&uname_info) != 0)
+ {
+ lua_pushnil(L);
+ lua_pushstring(L, strerror(errno));
+ return 2;
+ }
+ lua_newtable(L);
+ lua_pushstring(L, uname_info.sysname);
+ lua_setfield(L, -2, "sysname");
+ lua_pushstring(L, uname_info.nodename);
+ lua_setfield(L, -2, "nodename");
+ lua_pushstring(L, uname_info.release);
+ lua_setfield(L, -2, "release");
+ lua_pushstring(L, uname_info.version);
+ lua_setfield(L, -2, "version");
+ lua_pushstring(L, uname_info.machine);
+ lua_setfield(L, -2, "machine");
+ return 1;
+}
+
+int lc_setenv(lua_State* L)
+{
+ const char *var = luaL_checkstring(L, 1);
+ const char *value;
+
+ /* If the second argument is nil or nothing, unset the var */
+ if(lua_isnoneornil(L, 2))
+ {
+ if(unsetenv(var) != 0)
+ {
+ lua_pushnil(L);
+ lua_pushstring(L, strerror(errno));
+ return 2;
+ }
+ lua_pushboolean(L, 1);
+ return 1;
+ }
+
+ value = luaL_checkstring(L, 2);
+
+ if(setenv(var, value, 1) != 0)
+ {
+ lua_pushnil(L);
+ lua_pushstring(L, strerror(errno));
+ return 2;
+ }
+
+ lua_pushboolean(L, 1);
+ return 1;
+}
+
+#ifdef WITH_MALLINFO
+int lc_meminfo(lua_State* L)
+{
+ struct mallinfo info = mallinfo();
+ lua_newtable(L);
+ /* This is the total size of memory allocated with sbrk by malloc, in bytes. */
+ lua_pushinteger(L, info.arena);
+ lua_setfield(L, -2, "allocated");
+ /* This is the total size of memory allocated with mmap, in bytes. */
+ lua_pushinteger(L, info.hblkhd);
+ lua_setfield(L, -2, "allocated_mmap");
+ /* This is the total size of memory occupied by chunks handed out by malloc. */
+ lua_pushinteger(L, info.uordblks);
+ lua_setfield(L, -2, "used");
+ /* This is the total size of memory occupied by free (not in use) chunks. */
+ lua_pushinteger(L, info.fordblks);
+ lua_setfield(L, -2, "unused");
+ /* This is the size of the top-most releasable chunk that normally borders the
+ end of the heap (i.e., the high end of the virtual address space's data segment). */
+ lua_pushinteger(L, info.keepcost);
+ lua_setfield(L, -2, "returnable");
+ return 1;
+}
+#endif
+
+/* File handle extraction blatantly stolen from
+ * https://github.com/rrthomas/luaposix/blob/master/lposix.c#L631
+ * */
+
+#if _XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L || defined(_GNU_SOURCE)
+int lc_fallocate(lua_State* L)
+{
+ off_t offset, len;
+ FILE *f = *(FILE**) luaL_checkudata(L, 1, LUA_FILEHANDLE);
+
+ offset = luaL_checkinteger(L, 2);
+ len = luaL_checkinteger(L, 3);
+
+#if defined(_GNU_SOURCE)
+ if(fallocate(fileno(f), FALLOC_FL_KEEP_SIZE, offset, len) == 0)
+ {
+ lua_pushboolean(L, 1);
+ return 1;
+ }
+
+ if(errno != ENOSYS && errno != EOPNOTSUPP)
+ {
+ lua_pushnil(L);
+ lua_pushstring(L, strerror(errno));
+ return 2;
+ }
+#else
+#warning Only using posix_fallocate() fallback.
+#warning Linux fallocate() is strongly recommended if available: recompile with -D_GNU_SOURCE
+#warning Note that posix_fallocate() will still be used on filesystems that dont support fallocate()
+#endif
+
+ if(posix_fallocate(fileno(f), offset, len) == 0)
+ {
+ lua_pushboolean(L, 1);
+ return 1;
+ }
+ else
+ {
+ lua_pushnil(L);
+ lua_pushstring(L, strerror(errno));
+ /* posix_fallocate() can leave a bunch of NULs at the end, so we cut that
+ * this assumes that offset == length of the file */
+ ftruncate(fileno(f), offset);
+ return 2;
+ }
+}
+#endif
+
+/* Register functions */
+
+int luaopen_util_pposix(lua_State *L)
+{
+ luaL_Reg exports[] = {
+ { "abort", lc_abort },
+
+ { "daemonize", lc_daemonize },
+
+ { "syslog_open", lc_syslog_open },
+ { "syslog_close", lc_syslog_close },
+ { "syslog_log", lc_syslog_log },
+ { "syslog_setminlevel", lc_syslog_setmask },
+
+ { "getpid", lc_getpid },
+ { "getuid", lc_getuid },
+ { "getgid", lc_getgid },
+
+ { "setuid", lc_setuid },
+ { "setgid", lc_setgid },
+ { "initgroups", lc_initgroups },
+
+ { "umask", lc_umask },
+
+ { "mkdir", lc_mkdir },
+
+ { "setrlimit", lc_setrlimit },
+ { "getrlimit", lc_getrlimit },
+
+ { "uname", lc_uname },
+
+ { "setenv", lc_setenv },
+
+#ifdef WITH_MALLINFO
+ { "meminfo", lc_meminfo },
+#endif
+
+#if _XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L || defined(_GNU_SOURCE)
+ { "fallocate", lc_fallocate },
+#endif
+
+ { NULL, NULL }
+ };
+
+ luaL_register(L, "pposix", exports);
+
+ lua_pushliteral(L, "pposix");
+ lua_setfield(L, -2, "_NAME");
+
+ lua_pushliteral(L, MODULE_VERSION);
+ lua_setfield(L, -2, "_VERSION");
+
+ return 1;
+}
diff --git a/util-src/signal.c b/util-src/signal.c
new file mode 100644
index 00000000..961d2d3e
--- /dev/null
+++ b/util-src/signal.c
@@ -0,0 +1,412 @@
+/*
+ * signal.c -- Signal Handler Library for Lua
+ *
+ * Version: 1.000+changes
+ *
+ * Copyright (C) 2007 Patrick J. Donnelly (batrick@batbytes.com)
+ *
+ * This software is distributed under the same license as Lua 5.0:
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+*/
+
+#include <signal.h>
+#include <stdlib.h>
+
+#include "lua.h"
+#include "lauxlib.h"
+
+#ifndef lsig
+
+#define lsig
+
+struct lua_signal
+{
+ char *name; /* name of the signal */
+ int sig; /* the signal */
+};
+
+#endif
+
+#define LUA_SIGNAL "lua_signal"
+
+static const struct lua_signal lua_signals[] = {
+ /* ANSI C signals */
+#ifdef SIGABRT
+ {"SIGABRT", SIGABRT},
+#endif
+#ifdef SIGFPE
+ {"SIGFPE", SIGFPE},
+#endif
+#ifdef SIGILL
+ {"SIGILL", SIGILL},
+#endif
+#ifdef SIGINT
+ {"SIGINT", SIGINT},
+#endif
+#ifdef SIGSEGV
+ {"SIGSEGV", SIGSEGV},
+#endif
+#ifdef SIGTERM
+ {"SIGTERM", SIGTERM},
+#endif
+ /* posix signals */
+#ifdef SIGHUP
+ {"SIGHUP", SIGHUP},
+#endif
+#ifdef SIGQUIT
+ {"SIGQUIT", SIGQUIT},
+#endif
+#ifdef SIGTRAP
+ {"SIGTRAP", SIGTRAP},
+#endif
+#ifdef SIGKILL
+ {"SIGKILL", SIGKILL},
+#endif
+#ifdef SIGUSR1
+ {"SIGUSR1", SIGUSR1},
+#endif
+#ifdef SIGUSR2
+ {"SIGUSR2", SIGUSR2},
+#endif
+#ifdef SIGPIPE
+ {"SIGPIPE", SIGPIPE},
+#endif
+#ifdef SIGALRM
+ {"SIGALRM", SIGALRM},
+#endif
+#ifdef SIGCHLD
+ {"SIGCHLD", SIGCHLD},
+#endif
+#ifdef SIGCONT
+ {"SIGCONT", SIGCONT},
+#endif
+#ifdef SIGSTOP
+ {"SIGSTOP", SIGSTOP},
+#endif
+#ifdef SIGTTIN
+ {"SIGTTIN", SIGTTIN},
+#endif
+#ifdef SIGTTOU
+ {"SIGTTOU", SIGTTOU},
+#endif
+ /* some BSD signals */
+#ifdef SIGIOT
+ {"SIGIOT", SIGIOT},
+#endif
+#ifdef SIGBUS
+ {"SIGBUS", SIGBUS},
+#endif
+#ifdef SIGCLD
+ {"SIGCLD", SIGCLD},
+#endif
+#ifdef SIGURG
+ {"SIGURG", SIGURG},
+#endif
+#ifdef SIGXCPU
+ {"SIGXCPU", SIGXCPU},
+#endif
+#ifdef SIGXFSZ
+ {"SIGXFSZ", SIGXFSZ},
+#endif
+#ifdef SIGVTALRM
+ {"SIGVTALRM", SIGVTALRM},
+#endif
+#ifdef SIGPROF
+ {"SIGPROF", SIGPROF},
+#endif
+#ifdef SIGWINCH
+ {"SIGWINCH", SIGWINCH},
+#endif
+#ifdef SIGPOLL
+ {"SIGPOLL", SIGPOLL},
+#endif
+#ifdef SIGIO
+ {"SIGIO", SIGIO},
+#endif
+ /* add odd signals */
+#ifdef SIGSTKFLT
+ {"SIGSTKFLT", SIGSTKFLT}, /* stack fault */
+#endif
+#ifdef SIGSYS
+ {"SIGSYS", SIGSYS},
+#endif
+ {NULL, 0}
+};
+
+static lua_State *Lsig = NULL;
+static lua_Hook Hsig = NULL;
+static int Hmask = 0;
+static int Hcount = 0;
+
+static struct signal_event
+{
+ int Nsig;
+ struct signal_event *next_event;
+} *signal_queue = NULL;
+
+static struct signal_event *last_event = NULL;
+
+static void sighook(lua_State *L, lua_Debug *ar)
+{
+ struct signal_event *event;
+ /* restore the old hook */
+ lua_sethook(L, Hsig, Hmask, Hcount);
+
+ lua_pushstring(L, LUA_SIGNAL);
+ lua_gettable(L, LUA_REGISTRYINDEX);
+
+ while((event = signal_queue))
+ {
+ lua_pushnumber(L, event->Nsig);
+ lua_gettable(L, -2);
+ lua_call(L, 0, 0);
+ signal_queue = event->next_event;
+ free(event);
+ };
+
+ lua_pop(L, 1); /* pop lua_signal table */
+
+}
+
+static void handle(int sig)
+{
+ if(!signal_queue)
+ {
+ /* Store the existing debug hook (if any) and its parameters */
+ Hsig = lua_gethook(Lsig);
+ Hmask = lua_gethookmask(Lsig);
+ Hcount = lua_gethookcount(Lsig);
+
+ signal_queue = malloc(sizeof(struct signal_event));
+ signal_queue->Nsig = sig;
+ signal_queue->next_event = NULL;
+
+ last_event = signal_queue;
+
+ /* Set our new debug hook */
+ lua_sethook(Lsig, sighook, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
+ }
+ else
+ {
+ last_event->next_event = malloc(sizeof(struct signal_event));
+ last_event->next_event->Nsig = sig;
+ last_event->next_event->next_event = NULL;
+
+ last_event = last_event->next_event;
+ }
+}
+
+/*
+ * l_signal == signal(signal [, func [, chook]])
+ *
+ * signal = signal number or string
+ * func = Lua function to call
+ * chook = catch within C functions
+ * if caught, Lua function _must_
+ * exit, as the stack is most likely
+ * in an unstable state.
+*/
+
+static int l_signal(lua_State *L)
+{
+ int args = lua_gettop(L);
+ int t, sig; /* type, signal */
+
+ /* get type of signal */
+ luaL_checkany(L, 1);
+ t = lua_type(L, 1);
+ if (t == LUA_TNUMBER)
+ sig = (int) lua_tonumber(L, 1);
+ else if (t == LUA_TSTRING)
+ {
+ lua_pushstring(L, LUA_SIGNAL);
+ lua_gettable(L, LUA_REGISTRYINDEX);
+ lua_pushvalue(L, 1);
+ lua_gettable(L, -2);
+ if (!lua_isnumber(L, -1))
+ luaL_error(L, "invalid signal string");
+ sig = (int) lua_tonumber(L, -1);
+ lua_pop(L, 1); /* get rid of number we pushed */
+ } else
+ luaL_checknumber(L, 1); /* will always error, with good error msg */
+
+ /* set handler */
+ if (args == 1 || lua_isnil(L, 2)) /* clear handler */
+ {
+ lua_pushstring(L, LUA_SIGNAL);
+ lua_gettable(L, LUA_REGISTRYINDEX);
+ lua_pushnumber(L, sig);
+ lua_gettable(L, -2); /* return old handler */
+ lua_pushnumber(L, sig);
+ lua_pushnil(L);
+ lua_settable(L, -4);
+ lua_remove(L, -2); /* remove LUA_SIGNAL table */
+ signal(sig, SIG_DFL);
+ } else
+ {
+ luaL_checktype(L, 2, LUA_TFUNCTION);
+
+ lua_pushstring(L, LUA_SIGNAL);
+ lua_gettable(L, LUA_REGISTRYINDEX);
+
+ lua_pushnumber(L, sig);
+ lua_pushvalue(L, 2);
+ lua_settable(L, -3);
+
+ /* Set the state for the handler */
+ Lsig = L;
+
+ if (lua_toboolean(L, 3)) /* c hook? */
+ {
+ if (signal(sig, handle) == SIG_ERR)
+ lua_pushboolean(L, 0);
+ else
+ lua_pushboolean(L, 1);
+ } else /* lua_hook */
+ {
+ if (signal(sig, handle) == SIG_ERR)
+ lua_pushboolean(L, 0);
+ else
+ lua_pushboolean(L, 1);
+ }
+ }
+ return 1;
+}
+
+/*
+ * l_raise == raise(signal)
+ *
+ * signal = signal number or string
+*/
+
+static int l_raise(lua_State *L)
+{
+ /* int args = lua_gettop(L); */
+ int t = 0; /* type */
+ lua_Number ret;
+
+ luaL_checkany(L, 1);
+
+ t = lua_type(L, 1);
+ if (t == LUA_TNUMBER)
+ {
+ ret = (lua_Number) raise((int) lua_tonumber(L, 1));
+ lua_pushnumber(L, ret);
+ } else if (t == LUA_TSTRING)
+ {
+ lua_pushstring(L, LUA_SIGNAL);
+ lua_gettable(L, LUA_REGISTRYINDEX);
+ lua_pushvalue(L, 1);
+ lua_gettable(L, -2);
+ if (!lua_isnumber(L, -1))
+ luaL_error(L, "invalid signal string");
+ ret = (lua_Number) raise((int) lua_tonumber(L, -1));
+ lua_pop(L, 1); /* get rid of number we pushed */
+ lua_pushnumber(L, ret);
+ } else
+ luaL_checknumber(L, 1); /* will always error, with good error msg */
+
+ return 1;
+}
+
+#if defined(__unix__) || defined(__APPLE__)
+
+/* define some posix only functions */
+
+/*
+ * l_kill == kill(pid, signal)
+ *
+ * pid = process id
+ * signal = signal number or string
+*/
+
+static int l_kill(lua_State *L)
+{
+ int t; /* type */
+ lua_Number ret; /* return value */
+
+ luaL_checknumber(L, 1); /* must be int for pid */
+ luaL_checkany(L, 2); /* check for a second arg */
+
+ t = lua_type(L, 2);
+ if (t == LUA_TNUMBER)
+ {
+ ret = (lua_Number) kill((int) lua_tonumber(L, 1),
+ (int) lua_tonumber(L, 2));
+ lua_pushnumber(L, ret);
+ } else if (t == LUA_TSTRING)
+ {
+ lua_pushstring(L, LUA_SIGNAL);
+ lua_gettable(L, LUA_REGISTRYINDEX);
+ lua_pushvalue(L, 2);
+ lua_gettable(L, -2);
+ if (!lua_isnumber(L, -1))
+ luaL_error(L, "invalid signal string");
+ ret = (lua_Number) kill((int) lua_tonumber(L, 1),
+ (int) lua_tonumber(L, -1));
+ lua_pop(L, 1); /* get rid of number we pushed */
+ lua_pushnumber(L, ret);
+ } else
+ luaL_checknumber(L, 2); /* will always error, with good error msg */
+ return 1;
+}
+
+#endif
+
+static const struct luaL_Reg lsignal_lib[] = {
+ {"signal", l_signal},
+ {"raise", l_raise},
+#if defined(__unix__) || defined(__APPLE__)
+ {"kill", l_kill},
+#endif
+ {NULL, NULL}
+};
+
+int luaopen_util_signal(lua_State *L)
+{
+ int i = 0;
+
+ /* add the library */
+ luaL_register(L, "signal", lsignal_lib);
+
+ /* push lua_signals table into the registry */
+ /* put the signals inside the library table too,
+ * they are only a reference */
+ lua_pushstring(L, LUA_SIGNAL);
+ lua_createtable(L, 0, 0);
+
+ while (lua_signals[i].name != NULL)
+ {
+ /* registry table */
+ lua_pushstring(L, lua_signals[i].name);
+ lua_pushnumber(L, lua_signals[i].sig);
+ lua_settable(L, -3);
+ /* signal table */
+ lua_pushstring(L, lua_signals[i].name);
+ lua_pushnumber(L, lua_signals[i].sig);
+ lua_settable(L, -5);
+ i++;
+ }
+
+ /* add newtable to the registry */
+ lua_settable(L, LUA_REGISTRYINDEX);
+
+ return 1;
+}
diff --git a/util-src/windows.c b/util-src/windows.c
new file mode 100644
index 00000000..121cc471
--- /dev/null
+++ b/util-src/windows.c
@@ -0,0 +1,89 @@
+/* Prosody IM
+-- Copyright (C) 2008-2010 Matthew Wild
+-- Copyright (C) 2008-2010 Waqas Hussain
+--
+-- This project is MIT/X11 licensed. Please see the
+-- COPYING file in the source package for more information.
+--
+*/
+
+/*
+* windows.c
+* Windows support functions for Lua
+*/
+
+#include <stdio.h>
+#include <windows.h>
+#include <windns.h>
+
+#include "lua.h"
+#include "lauxlib.h"
+
+static int Lget_nameservers(lua_State *L) {
+ char stack_buffer[1024]; // stack allocated buffer
+ IP4_ARRAY* ips = (IP4_ARRAY*) stack_buffer;
+ DWORD len = sizeof(stack_buffer);
+ DNS_STATUS status;
+
+ status = DnsQueryConfig(DnsConfigDnsServerList, FALSE, NULL, NULL, ips, &len);
+ if (status == 0) {
+ DWORD i;
+ lua_createtable(L, ips->AddrCount, 0);
+ for (i = 0; i < ips->AddrCount; i++) {
+ DWORD ip = ips->AddrArray[i];
+ char ip_str[16] = "";
+ sprintf_s(ip_str, sizeof(ip_str), "%d.%d.%d.%d", (ip >> 0) & 255, (ip >> 8) & 255, (ip >> 16) & 255, (ip >> 24) & 255);
+ lua_pushstring(L, ip_str);
+ lua_rawseti(L, -2, i+1);
+ }
+ return 1;
+ } else {
+ lua_pushnil(L);
+ lua_pushfstring(L, "DnsQueryConfig returned %d", status);
+ return 2;
+ }
+}
+
+static int lerror(lua_State *L, char* string) {
+ lua_pushnil(L);
+ lua_pushfstring(L, "%s: %d", string, GetLastError());
+ return 2;
+}
+
+static int Lget_consolecolor(lua_State *L) {
+ HWND console = GetStdHandle(STD_OUTPUT_HANDLE);
+ WORD color; DWORD read_len;
+
+ CONSOLE_SCREEN_BUFFER_INFO info;
+
+ if (console == INVALID_HANDLE_VALUE) return lerror(L, "GetStdHandle");
+ if (!GetConsoleScreenBufferInfo(console, &info)) return lerror(L, "GetConsoleScreenBufferInfo");
+ if (!ReadConsoleOutputAttribute(console, &color, sizeof(WORD), info.dwCursorPosition, &read_len)) return lerror(L, "ReadConsoleOutputAttribute");
+
+ lua_pushnumber(L, color);
+ return 1;
+}
+static int Lset_consolecolor(lua_State *L) {
+ int color = luaL_checkint(L, 1);
+ HWND console = GetStdHandle(STD_OUTPUT_HANDLE);
+ if (console == INVALID_HANDLE_VALUE) return lerror(L, "GetStdHandle");
+ if (!SetConsoleTextAttribute(console, color)) return lerror(L, "SetConsoleTextAttribute");
+ lua_pushboolean(L, 1);
+ return 1;
+}
+
+static const luaL_Reg Reg[] =
+{
+ { "get_nameservers", Lget_nameservers },
+ { "get_consolecolor", Lget_consolecolor },
+ { "set_consolecolor", Lset_consolecolor },
+ { NULL, NULL }
+};
+
+LUALIB_API int luaopen_util_windows(lua_State *L) {
+ luaL_register(L, "windows", Reg);
+ lua_pushliteral(L, "version"); /** version */
+ lua_pushliteral(L, "-3.14");
+ lua_settable(L,-3);
+ return 1;
+}