#!/usr/local/bin/luajit --[[ async DNS test using getaddrinfo_a LuaJIT head, x86_64, Linux 2.6.38 1) for every hostname in tquery table - use calloc to allocate gaicb_t - issue 1 async DNS request using getaddrinfo_a (the hostp parameter in getaddrinfo_a is an array of pointers to structures of type gaicb) 2) read replies in a loop - using blocking signalfd file descriptor - for every reply, free gaicb_t allocated with calloc --]] local tquery = {"www.lua.org", "lua-users.org"} if #arg > 0 then tquery = arg end local ffi = require "ffi" local C = ffi.C local anl = ffi.load "anl" local file = io.open'gaia.cdef' ffi.cdef(file:read'*a') file:close() -- constants local SIGRTMIN = 34 local SIGEV_SIGNAL = 0 local SIG_BLOCK = 0 local GAI_NOWAIT = 1 --local O_NONBLOCK = 2048 -- types local sigset_t = ffi.typeof"sigset_t" local gaicb_t = ffi.typeof"struct gaicb" local sigevent_t = ffi.typeof"struct sigevent" local sigevent_tp = ffi.typeof"struct sigevent*" local sfd_si_t = ffi.typeof"struct signalfd_siginfo" local sfd_si_tp = ffi.typeof"struct signalfd_siginfo*" -- setup the mechanism for asynch notification local ev = sigevent_t( {sigev_signo = SIGRTMIN, sigev_notify = SIGEV_SIGNAL} ) -- setup the signalfd file descriptor (blocking) to get the replies local mask = ffi.new("sigset_t[1]") C.sigemptyset(mask) C.sigaddset(mask, SIGRTMIN) if -1 == C.sigprocmask(SIG_BLOCK, mask, nil) then print("error: sigprocmask") end local sfd = C.signalfd(-1, mask, 0) if sfd == -1 then print("error: signalfd:", ffi.string(C.strerror(ffi.errno()))) end local host, host2, hostp -- make requests for i=1, #tquery do local query = tquery[i] host = C.calloc(1, ffi.sizeof(gaicb_t)) host2 = ffi.cast("struct gaicb*", host) host2.ar_name = ffi.new("char[?]", #query+1, query) hostp = ffi.new("struct gaicb*[1]", {host2} ) ev.sigev_value.sival_ptr = hostp local ret = anl.getaddrinfo_a(GAI_NOWAIT, hostp, 1, sigevent_tp(ev) ) if ret ~= 0 then print("error: get_addrinfo_a:", ret) end end local nqueries = #tquery local nresolved = 0 -- note: "declaration indentifier expected" when using sfd_si_t in ffi.new local fdsi = ffi.new("struct signalfd_siginfo[1]") local fdsip = sfd_si_tp(fdsi) -- get replies local outp while true do if nqueries == nresolved then break end local s = C.read(sfd, fdsi, ffi.sizeof(sfd_si_t)) nresolved = nresolved + 1 if s ~= ffi.sizeof(sfd_si_t) then print("error: read:", s) break end if fdsip.ssi_signo ~= SIGRTMIN then print("received signal:", fdsip.ssi_signo) break end outp = ffi.cast("struct gaicb**", fdsip.ssi_ptr) if not ffi.cast("struct addrinfo*", outp[0].ar_result) then print("error: cannot resolve:", ffi.string(ffi.cast("const char*", outp[0].ar_name))) end -- ai_addr: struct sockaddr* ap = ffi.cast("struct sockaddr_in*", outp[0].ar_result.ai_addr) name = outp[0].ar_name ip = C.inet_ntoa(ap.sin_addr) print(ffi.string(name), ffi.string(ip)) io.flush() if outp[0] ~= nil then C.free(outp[0]) end end