Skip to content

Commit

Permalink
Fix TCPSocket segfault on missing host and 0 port (#4177)
Browse files Browse the repository at this point in the history
Prior to this patch, `TCPSocket.new("whatever", 0)` would cause
    Invalid memory access (signal 11) at address 0x0
  • Loading branch information
will authored and bcardiff committed Mar 27, 2017
1 parent 917971d commit 3c74890
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
6 changes: 6 additions & 0 deletions spec/std/socket_spec.cr
Expand Up @@ -542,6 +542,12 @@ describe TCPSocket do
TCPSocket.new("localhostttttt", 12345)
end
end

it "fails (rather than segfault on darwin) when host doesn't exist and port is 0" do
expect_raises(Socket::Error, /No address found for localhostttttt:0/) do
TCPSocket.new("localhostttttt", 0)
end
end
end

describe UDPSocket do
Expand Down
9 changes: 9 additions & 0 deletions src/socket/addrinfo.cr
Expand Up @@ -86,6 +86,15 @@ class Socket
hints.ai_flags |= LibC::AI_NUMERICSERV
end

# On OS X < 10.12, the libsystem implementation of getaddrinfo segfaults
# if AI_NUMERICSERV is set, and servname is NULL or 0.
{% if flag?(:darwin) %}
if (service == 0 || service == nil) && (hints.ai_flags & LibC::AI_NUMERICSERV)
hints.ai_flags |= LibC::AI_NUMERICSERV
service = "00"
end
{% end %}

case ret = LibC.getaddrinfo(domain, service.to_s, pointerof(hints), out ptr)
when 0
# success
Expand Down

0 comments on commit 3c74890

Please sign in to comment.