diff --git a/docs/scripting.xml b/docs/scripting.xml index ec21aa0d8..fd299b080 100644 --- a/docs/scripting.xml +++ b/docs/scripting.xml @@ -4040,5 +4040,94 @@ The mainloop function will work on each runlevel grouping of threads in order. repeated until no threads exist in either waiting or running. + + Adding C Modules to Nselib + Nmap Scripting Engine (NSE)C modules + + + Some of the modules included in nselib are not written in Lua but + in C or C++. bit and pcre + are two examples. This section describes how to write your own + compiled extensions to nselib. + + + + The C API of Lua is described at length in + Programming in Lua, Second Edition, + Programming in Lua, Second Edition, + so this is a short summary. C modules consist of functions that + follow the protocol of the + lua_CFunction + type. The functions are registered with Lua and assembled into a + library by calling the + luaL_registerluaL_register + function. A special initialization function provides the interface + between the module and the rest of the NSE code. By convention the + initialization function has a name of the form + luaopen_module. + + + + Two of the smaller compiled modules that come with NSE are + bitbit NSE module + and hash,hash NSE module + and they serve as good examples of how to write such modules. The + source code for bit is in the files + nse_bit.cc and + nse_bit.h, and likewise the source for + hash is in nse_hash.cc and + nse_hash.h. The other compiled modules follow + this naming convention. + + + + Let us look at the hash module. One of the + functions in nse_hash.cc is + l_md5, which calculates an MD5 digest. Its + function prototype is + +static int l_md5(lua_State *L); + + The prototype shows that l_md5 matches the + lua_CFunction type. The function is static because it + does not have to be visible to other compiled code, it just needs + an address so it can be registered with Lua. Later in the file we + see l_md5 entered into an array of type + luaL_reg and associated with the name + md5, the name it will be known by to NSE: + +static const luaL_reg hashlib[] = +{ + {"md5", l_md5}, + {NULL, NULL} +}; + + Then the library is registered with a call to + luaL_register inside the initialization + function luaopen_hashlib: + +LUALIB_API int luaopen_hashlib (lua_State *L) { + luaL_register(L, NSE_HASHLIBNAME, hashlib); + return 1; +} + + (NSE_HASHLIBNAME is just the string + "hash".) luaopen_hashlib + is the only function in the file that is exposed in + nse_hash.h. + + + + Once a compiled module is written, it is added to NSE by including + it in the list of standard libraries in + nse_init.cc. Just follow the example of the + modules that are already there. Then the names of the module's + source files of the must be added to + Makefile.in in the appropriate places. Again + it is easiest to follow the example of the other modules. For the + Windows build the new source files must be added to the + mswin32/nmap.vcproj project file. + +