Skip to content

Commit 7a285f2

Browse files
committed
http/client: Throw error if bind address is non-matching family
1 parent f65bd8f commit 7a285f2

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

http/client.lua

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,11 @@ local function dns_lookup(records, dns_resolver, host, query_type, filter_type,
122122
end
123123

124124
local function connect(options, timeout)
125+
local family = options.family
126+
if family == nil then
127+
family = cs.AF_UNSPEC
128+
end
129+
125130
local bind = options.bind
126131
if bind ~= nil then
127132
assert(type(bind) == "string")
@@ -133,22 +138,32 @@ local function connect(options, timeout)
133138
end
134139
local ipv6 = bind_address:match("^%[([:%x]+)%]$")
135140
if ipv6 then
141+
if family == cs.AF_UNSPEC then
142+
family = cs.AF_INET6
143+
elseif family ~= cs.AF_INET6 then
144+
error("cannot bind local IPv6 address when using other address family")
145+
end
136146
bind_address = ipv6
147+
else
148+
if family == cs.AF_UNSPEC then
149+
family = cs.AF_INET
150+
elseif family ~= cs.AF_INET then
151+
error("cannot bind local IPv4 address when using other address family")
152+
end
137153
end
138154
bind = {
139155
address = bind_address;
140156
port = bind_port;
141157
}
142158
end
143159

144-
local family = options.family
145160
local path = options.path
146161
local host = options.host
147162
if not path and not http_util.is_ip(host) then
148163
local dns_resolver = options.dns_resolver or cqueues_dns.getpool()
149164
local deadline = timeout and monotime()+timeout
150165
local records = {}
151-
if family == nil or family == cs.AF_UNSPEC then
166+
if family == cs.AF_UNSPEC then
152167
dns_lookup(records, dns_resolver, host, cqueues_dns_record.AAAA, nil, timeout)
153168
dns_lookup(records, dns_resolver, host, cqueues_dns_record.A, nil, deadline and deadline-monotime())
154169
elseif family == cs.AF_INET then

spec/client_spec.lua

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,14 @@ describe("http.client module", function()
1515
local openssl_pkey = require "openssl.pkey"
1616
local openssl_ctx = require "openssl.ssl.context"
1717
local openssl_x509 = require "openssl.x509"
18+
it("throws error on invalid family+bind combination", function()
19+
assert.has.errors(function()
20+
client.connect{family = cs.AF_INET, host = "example.com", port = 80, bind = "::1" }
21+
end)
22+
assert.has.errors(function()
23+
client.connect{family = cs.AF_INET6, host = "example.com", port = 80, bind = "127.0.0.1" }
24+
end)
25+
end)
1826
it("invalid network parameters return nil, err, errno", function()
1927
-- Invalid network parameters will return nil, err, errno
2028
local ok, err, errno = client.connect{host="127.0.0.1", port="invalid"}

0 commit comments

Comments
 (0)