util.windows: Initial commit. Adds support for querying the windows DNS API for names...
[prosody.git] / util-src / windows.c
1 \r
2 #include <stdio.h>\r
3 #include <windows.h>\r
4 #include <windns.h>\r
5 \r
6 #include "lua.h"\r
7 #include "lauxlib.h"\r
8 \r
9 static int Lget_nameservers(lua_State *L) {\r
10         char stack_buffer[1024]; // stack allocated buffer\r
11         IP4_ARRAY* ips = (IP4_ARRAY*) stack_buffer;\r
12         DWORD len = sizeof(stack_buffer);\r
13         DNS_STATUS status;\r
14 \r
15         status = DnsQueryConfig(DnsConfigDnsServerList, FALSE, NULL, NULL, ips, &len);\r
16         if (status == 0) {\r
17                 DWORD i;\r
18                 lua_createtable(L, ips->AddrCount, 0);\r
19                 for (i = 0; i < ips->AddrCount; i++) {\r
20                         DWORD ip = ips->AddrArray[i];\r
21                         char ip_str[16] = "";\r
22                         sprintf_s(ip_str, sizeof(ip_str), "%d.%d.%d.%d", (ip >> 0) & 255, (ip >> 8) & 255, (ip >> 16) & 255, (ip >> 24) & 255);\r
23                         lua_pushstring(L, ip_str);\r
24                         lua_rawseti(L, -2, i+1);\r
25                 }\r
26                 return 1;\r
27         } else {\r
28                 luaL_error(L, "DnsQueryConfig returned %d", status);\r
29                 return 0; // unreachable, but prevents a compiler warning\r
30         }\r
31 }\r
32 \r
33 static const luaL_Reg Reg[] =\r
34 {\r
35         { "get_nameservers",    Lget_nameservers        },\r
36         { NULL,         NULL    }\r
37 };\r
38 \r
39 LUALIB_API int luaopen_util_windows(lua_State *L) {\r
40         luaL_register(L, "windows", Reg);\r
41         lua_pushliteral(L, "version");                  /** version */\r
42         lua_pushliteral(L, "-3.14");\r
43         lua_settable(L,-3);\r
44         return 1;\r
45 }\r