• Stars
    star
    321
  • Rank 130,752 (Top 3 %)
  • Language
    Lua
  • Created over 12 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

DNS resolver for the nginx lua module

Name

lua-resty-dns - Lua DNS resolver for the ngx_lua based on the cosocket API

Table of Contents

Status

This library is considered production ready.

Description

This Lua library provides a DNS resolver for the ngx_lua nginx module:

https://github.com/openresty/lua-nginx-module/#readme

This Lua library takes advantage of ngx_lua's cosocket API, which ensures 100% nonblocking behavior.

Note that at least ngx_lua 0.5.12 or OpenResty 1.2.1.11 is required.

Also, the bit library is also required. If you're using LuaJIT 2.0 with ngx_lua, then the bit library is already available by default.

Note that, this library is bundled and enabled by default in the OpenResty bundle.

IMPORTANT: to be able to generate unique ids, the random generator must be properly seeded using math.randomseed prior to using this module.

Synopsis

lua_package_path "/path/to/lua-resty-dns/lib/?.lua;;";

server {
    location = /dns {
        content_by_lua_block {
            local resolver = require "resty.dns.resolver"
            local r, err = resolver:new{
                nameservers = {"8.8.8.8", {"8.8.4.4", 53} },
                retrans = 5,  -- 5 retransmissions on receive timeout
                timeout = 2000,  -- 2 sec
                no_random = true, -- always start with first nameserver
            }

            if not r then
                ngx.say("failed to instantiate the resolver: ", err)
                return
            end

            local answers, err, tries = r:query("www.google.com", nil, {})
            if not answers then
                ngx.say("failed to query the DNS server: ", err)
                ngx.say("retry historie:\n  ", table.concat(tries, "\n  "))
                return
            end

            if answers.errcode then
                ngx.say("server returned error code: ", answers.errcode,
                        ": ", answers.errstr)
            end

            for i, ans in ipairs(answers) do
                ngx.say(ans.name, " ", ans.address or ans.cname,
                        " type:", ans.type, " class:", ans.class,
                        " ttl:", ans.ttl)
            end
        }
    }
}

Back to TOC

Methods

Back to TOC

new

syntax: r, err = class:new(opts)

Creates a dns.resolver object. Returns nil and a message string on error.

It accepts a opts table argument. The following options are supported:

  • nameservers

    a list of nameservers to be used. Each nameserver entry can be either a single hostname string or a table holding both the hostname string and the port number. The nameserver is picked up by a simple round-robin algorithm for each query method call. This option is required.

  • retrans

    the total number of times of retransmitting the DNS request when receiving a DNS response times out according to the timeout setting. Defaults to 5 times. When trying to retransmit the query, the next nameserver according to the round-robin algorithm will be picked up.

  • timeout

    the time in milliseconds for waiting for the response for a single attempt of request transmission. note that this is ''not'' the maximal total waiting time before giving up, the maximal total waiting time can be calculated by the expression timeout x retrans. The timeout setting can also be changed by calling the set_timeout method. The default timeout setting is 2000 milliseconds, or 2 seconds.

  • no_recurse

    a boolean flag controls whether to disable the "recursion desired" (RD) flag in the UDP request. Defaults to false.

  • no_random

    a boolean flag controls whether to randomly pick the nameserver to query first, if true will always start with the first nameserver listed. Defaults to false.

Back to TOC

destroy

syntax: r:destroy()

Destroy the dns.resolver object by releasing all the internal occupied resources.

Back to TOC

query

syntax: answers, err, tries? = r:query(name, options?, tries?)

Performs a DNS standard query to the nameservers specified by the new method, and returns all the answer records in an array-like Lua table. In case of errors, it will return nil and a string describing the error instead.

If the server returns a non-zero error code, the fields errcode and errstr will be set accordingly in the Lua table returned.

Each entry in the answers returned table value is also a hash-like Lua table which usually takes some of the following fields:

  • name

    The resource record name.

  • type

    The current resource record type, possible values are 1 (TYPE_A), 5 (TYPE_CNAME), 28 (TYPE_AAAA), and any other values allowed by RFC 1035.

  • address

    The IPv4 or IPv6 address in their textual representations when the resource record type is either 1 (TYPE_A) or 28 (TYPE_AAAA), respectively. Successive 16-bit zero groups in IPv6 addresses will not be compressed by default, if you want that, you need to call the compress_ipv6_addr static method instead.

  • section

    The identifier of the section that the current answer record belongs to. Possible values are 1 (SECTION_AN), 2 (SECTION_NS), and 3 (SECTION_AR).

  • cname

    The (decoded) record data value for CNAME resource records. Only present for CNAME records.

  • ttl

    The time-to-live (TTL) value in seconds for the current resource record.

  • class

    The current resource record class, possible values are 1 (CLASS_IN) or any other values allowed by RFC 1035.

  • preference

    The preference integer number for MX resource records. Only present for MX type records.

  • exchange

    The exchange domain name for MX resource records. Only present for MX type records.

  • nsdname

    A domain-name which specifies a host which should be authoritative for the specified class and domain. Usually present for NS type records.

  • rdata

    The raw resource data (RDATA) for resource records that are not recognized.

  • txt

    The record value for TXT records. When there is only one character string in this record, then this field takes a single Lua string. Otherwise this field takes a Lua table holding all the strings.

  • ptrdname

    The record value for PTR records.

This method also takes an optional options argument table, which takes the following fields:

  • qtype

    The type of the question. Possible values are 1 (TYPE_A), 5 (TYPE_CNAME), 28 (TYPE_AAAA), or any other QTYPE value specified by RFC 1035 and RFC 3596. Default to 1 (TYPE_A).

  • authority_section

    When set to a true value, the answers return value includes the Authority section of the DNS response. Default to false.

  • additional_section

    When set to a true value, the answers return value includes the Additional section of the DNS response. Default to false.

The optional parameter tries can be provided as an empty table, and will be returned as a third result. The table will be an array with the error message for each (if any) failed try.

When data truncation happens, the resolver will automatically retry using the TCP transport mode to query the current nameserver. All TCP connections are short lived.

Back to TOC

tcp_query

syntax: answers, err = r:tcp_query(name, options?)

Just like the query method, but enforce the TCP transport mode instead of UDP.

All TCP connections are short lived.

Here is an example:

    local resolver = require "resty.dns.resolver"

    local r, err = resolver:new{
        nameservers = { "8.8.8.8" }
    }
    if not r then
        ngx.say("failed to instantiate resolver: ", err)
        return
    end

    local ans, err = r:tcp_query("www.google.com", { qtype = r.TYPE_A })
    if not ans then
        ngx.say("failed to query: ", err)
        return
    end

    local cjson = require "cjson"
    ngx.say("records: ", cjson.encode(ans))

Back to TOC

set_timeout

syntax: r:set_timeout(time)

Overrides the current timeout setting by the time argument in milliseconds for all the nameserver peers.

Back to TOC

compress_ipv6_addr

syntax: compressed = resty.dns.resolver.compress_ipv6_addr(address)

Compresses the successive 16-bit zero groups in the textual format of the IPv6 address.

For example,

    local resolver = require "resty.dns.resolver"
    local compress = resolver.compress_ipv6_addr
    local new_addr = compress("FF01:0:0:0:0:0:0:101")

will yield FF01::101 in the new_addr return value.

Back to TOC

expand_ipv6_addr

syntax: expanded = resty.dns.resolver.expand_ipv6_addr(address)

Expands the successive 16-bit zero groups in the textual format of the IPv6 address.

For example,

    local resolver = require "resty.dns.resolver"
    local expand = resolver.expand_ipv6_addr
    local new_addr = expand("FF01::101")

will yield FF01:0:0:0:0:0:0:101 in the new_addr return value.

Back to TOC

arpa_str

syntax: arpa_record = resty.dns.resolver.arpa_str(address)

Generates the reverse domain name for PTR lookups for both IPv4 and IPv6 addresses. Compressed IPv6 addresses will be automatically expanded.

For example,

    local resolver = require "resty.dns.resolver"
    local ptr4 = resolver.arpa_str("1.2.3.4")
    local ptr6 = resolver.arpa_str("FF01::101")

will yield 4.3.2.1.in-addr.arpa for ptr4 and 1.0.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.0.F.F.ip6.arpa for ptr6.

Back to TOC

reverse_query

syntax: answers, err = r:reverse_query(address)

Performs a PTR lookup for both IPv4 and IPv6 addresses. This function is basically a wrapper for the query command which uses the arpa_str command to convert the IP address on the fly.

Back to TOC

Constants

Back to TOC

TYPE_A

The A resource record type, equal to the decimal number 1.

Back to TOC

TYPE_NS

The NS resource record type, equal to the decimal number 2.

Back to TOC

TYPE_CNAME

The CNAME resource record type, equal to the decimal number 5.

Back to TOC

TYPE_SOA

The SOA resource record type, equal to the decimal number 6.

Back to TOC

TYPE_PTR

The PTR resource record type, equal to the decimal number 12.

Back to TOC

TYPE_MX

The MX resource record type, equal to the decimal number 15.

Back to TOC

TYPE_TXT

The TXT resource record type, equal to the decimal number 16.

Back to TOC

TYPE_AAAA

syntax: typ = r.TYPE_AAAA

The AAAA resource record type, equal to the decimal number 28.

Back to TOC

TYPE_SRV

syntax: typ = r.TYPE_SRV

The SRV resource record type, equal to the decimal number 33.

See RFC 2782 for details.

Back to TOC

TYPE_SPF

syntax: typ = r.TYPE_SPF

The SPF resource record type, equal to the decimal number 99.

See RFC 4408 for details.

Back to TOC

CLASS_IN

syntax: class = r.CLASS_IN

The Internet resource record type, equal to the decimal number 1.

Back to TOC

SECTION_AN

syntax: stype = r.SECTION_AN

Identifier of the Answer section in the DNS response. Equal to decimal number 1.

Back to TOC

SECTION_NS

syntax: stype = r.SECTION_NS

Identifier of the Authority section in the DNS response. Equal to the decimal number 2.

Back to TOC

SECTION_AR

syntax: stype = r.SECTION_AR

Identifier of the Additional section in the DNS response. Equal to the decimal number 3.

Back to TOC

Automatic Error Logging

By default, the underlying ngx_lua module does error logging when socket errors happen. If you are already doing proper error handling in your own Lua code, then you are recommended to disable this automatic error logging by turning off ngx_lua's lua_socket_log_errors directive, that is,

    lua_socket_log_errors off;

Back to TOC

Limitations

  • This library cannot be used in code contexts like set_by_lua*, log_by_lua*, and header_filter_by_lua* where the ngx_lua cosocket API is not available.
  • The resty.dns.resolver object instance cannot be stored in a Lua variable at the Lua module level, because it will then be shared by all the concurrent requests handled by the same nginx worker process (see https://github.com/openresty/lua-nginx-module/#data-sharing-within-an-nginx-worker ) and result in bad race conditions when concurrent requests are trying to use the same resty.dns.resolver instance. You should always initiate resty.dns.resolver objects in function local variables or in the ngx.ctx table. These places all have their own data copies for each request.

Back to TOC

TODO

  • Concurrent (or parallel) query mode
  • Better support for other resource record types like TLSA.

Back to TOC

Author

Yichun "agentzh" Zhang (章亦春) [email protected], OpenResty Inc.

Back to TOC

Copyright and License

This module is licensed under the BSD license.

Copyright (C) 2012-2019, by Yichun "agentzh" Zhang (章亦春) [email protected], OpenResty Inc.

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Back to TOC

See Also

Back to TOC

More Repositories

1

openresty

High Performance Web Platform Based on Nginx and LuaJIT
C
12,431
star
2

lua-nginx-module

Embed the Power of Lua into NGINX HTTP servers
C
11,224
star
3

nginx-tutorials

Nginx Tutorials
Perl
2,864
star
4

lua-resty-redis

Lua redis client driver for the ngx_lua based on the cosocket API
Lua
1,893
star
5

openresty-systemtap-toolkit

Real-time analysis and diagnostics tools for OpenResty (including NGINX, LuaJIT, ngx_lua, and more) based on SystemTap
Perl
1,653
star
6

headers-more-nginx-module

Set, add, and clear arbitrary output headers in NGINX http servers
C
1,636
star
7

openresty.org

Code and data for the openresty.org site
HTML
1,262
star
8

luajit2

OpenResty's Branch of LuaJIT 2
C
1,229
star
9

echo-nginx-module

An Nginx module for bringing the power of "echo", "sleep", "time" and more to Nginx's config file
C
1,162
star
10

docker-openresty

Docker tooling for OpenResty
Dockerfile
934
star
11

redis2-nginx-module

Nginx upstream module for the Redis 2.0 protocol
C
902
star
12

lua-resty-limit-traffic

Lua library for limiting and controlling traffic in OpenResty/ngx_lua
Lua
815
star
13

lua-resty-core

New FFI-based API for lua-nginx-module
Lua
797
star
14

stream-lua-nginx-module

Embed the power of Lua into NGINX TCP/UDP servers
C
723
star
15

lua-resty-mysql

Nonblocking Lua MySQL driver library for ngx_lua or OpenResty
Lua
703
star
16

stapxx

Simple macro language extentions to systemtap
Perl
692
star
17

sregex

A non-backtracking NFA/DFA-based Perl-compatible regex engine matching on large data streams
C
616
star
18

lua-resty-upstream-healthcheck

Health Checker for Nginx Upstream Servers in Pure Lua
Lua
513
star
19

lua-resty-websocket

WebSocket support for the ngx_lua module (and OpenResty)
Lua
503
star
20

lua-upstream-nginx-module

Nginx C module to expose Lua API to ngx_lua for Nginx upstreams
C
499
star
21

srcache-nginx-module

Transparent subrequest-based caching layout for arbitrary nginx locations.
C
474
star
22

opm

OpenResty Package Manager
Lua
458
star
23

test-nginx

Data-driven test scaffold for Nginx C module and OpenResty Lua library development
Perl
438
star
24

lua-resty-lrucache

Lua-land LRU Cache based on LuaJIT FFI
Lua
437
star
25

lua-resty-string

String utilities and common hash functions for ngx_lua and LuaJIT
Lua
426
star
26

lua-resty-upload

Streaming reader and parser for http file uploading based on ngx_lua cosocket
Lua
401
star
27

set-misc-nginx-module

Various set_xxx directives added to nginx's rewrite module (md5/sha1, sql/json quoting, and many more)
C
388
star
28

drizzle-nginx-module

an nginx upstream module that talks to mysql and drizzle by libdrizzle
C
336
star
29

openresty-gdb-utils

GDB Utilities for OpenResty (including Nginx, ngx_lua, LuaJIT, and more)
Python
335
star
30

lua-resty-balancer

A generic consistent hash implementation for OpenResty/Lua
Lua
325
star
31

programming-openresty

Programming OpenResty Book
Perl
317
star
32

lua-resty-lock

Simple nonblocking lock API for ngx_lua based on shared memory dictionaries
Lua
304
star
33

openresty-devel-utils

Utilities for nginx module development
Perl
266
star
34

resty-cli

Fancy command-line utilities for OpenResty
Perl
263
star
35

replace-filter-nginx-module

Streaming regular expression replacement in response bodies
C
258
star
36

memc-nginx-module

An extended version of the standard memcached module that supports set, add, delete, and many more memcached commands.
C
213
star
37

lua-resty-memcached

Lua memcached client driver for the ngx_lua based on the cosocket API
Lua
210
star
38

encrypted-session-nginx-module

encrypt and decrypt nginx variable values
C
198
star
39

openresty-packaging

Official OpenResty packaging source and scripts for various Linux distributions and other systems
Makefile
176
star
40

rds-json-nginx-module

An nginx output filter that formats Resty DBD Streams generated by ngx_drizzle and others to JSON
C
153
star
41

xss-nginx-module

Native support for cross-site scripting (XSS) in an nginx
C
148
star
42

mockeagain

Mocking ideally slow network that only allows reading and/or writing one byte at a time
C
129
star
43

lua-resty-shell

Lua module for nonblocking system shell command executions
Perl
124
star
44

lua-tablepool

Lua table recycling pools for LuaJIT
Perl
112
star
45

lua-redis-parser

Lua module for parsing raw redis responses
C
93
star
46

openresty-survey

OpenResty Web App for OpenResty User Survey
HTML
90
star
47

lua-ssl-nginx-module

NGINX C module that extends ngx_http_lua_module for enhanced SSL/TLS capabilities
Lua
86
star
48

opsboy

A rule-based sysadmin tool that helps setting up complex environment for blank machines
Perl
85
star
49

no-pool-nginx

replace nginx's pool mechanism with plain malloc & free to help tools like valgrind
Shell
77
star
50

stream-echo-nginx-module

TCP/stream echo module for NGINX (a port of ngx_http_echo_module)
C
69
star
51

meta-lua-nginx-module

Meta Lua Nginx Module supporting both Http Lua Module and Stream Lua Module
C
66
star
52

array-var-nginx-module

Add support for array-typed variables to nginx config files
C
66
star
53

lemplate

OpenResty/Lua template framework implementing Perl's TT2 templating language
Perl
54
star
54

openresty-con

JavaScript
48
star
55

nginx-dtrace

An nginx fork that adds dtrace USDT probes
C
44
star
56

orbpf-ko

The orbpf (eBPF+) Linux kernel module from OpenResty Inc.
C
37
star
57

lua-resty-memcached-shdict

Powerful memcached client with a shdict caching layer and many other features
Lua
33
star
58

lua-resty-signal

Lua library for killing or sending signals to UNIX processes
Perl
32
star
59

lua-resty-shdict-simple

Simple applicaton-oriented interface to the OpenResty shared dictionary API
Perl
32
star
60

luajit2-test-suite

OpenResty's LuaJIT test suite based on Mike Pall's LuaJIT tests
Lua
29
star
61

ngx_postgres

OpenResty's fork of FRiCKLE/ngx_postgres
C
26
star
62

rds-csv-nginx-module

Nginx output filter module to convert Resty-DBD-Streams (RDS) to Comma-Separated Values (CSV)
C
22
star
63

showman-samples

Sample screenplay files for generating our public video tutorials using OpenResty Showman
20
star
64

lua-rds-parser

Resty DBD Stream (RDS) parser for Lua written in C
C
19
star
65

redis-nginx-module

8
star
66

AB-test-http

test http requests between two systems.
Perl
5
star
67

transparency

2
star