Skip to content

Commit 3c74890

Browse files
willbcardiff
authored andcommittedMar 27, 2017
Fix TCPSocket segfault on missing host and 0 port (#4177)
Prior to this patch, `TCPSocket.new("whatever", 0)` would cause Invalid memory access (signal 11) at address 0x0
1 parent 917971d commit 3c74890

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed
 

‎spec/std/socket_spec.cr

+6
Original file line numberDiff line numberDiff line change
@@ -542,6 +542,12 @@ describe TCPSocket do
542542
TCPSocket.new("localhostttttt", 12345)
543543
end
544544
end
545+
546+
it "fails (rather than segfault on darwin) when host doesn't exist and port is 0" do
547+
expect_raises(Socket::Error, /No address found for localhostttttt:0/) do
548+
TCPSocket.new("localhostttttt", 0)
549+
end
550+
end
545551
end
546552

547553
describe UDPSocket do

‎src/socket/addrinfo.cr

+9
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,15 @@ class Socket
8686
hints.ai_flags |= LibC::AI_NUMERICSERV
8787
end
8888

89+
# On OS X < 10.12, the libsystem implementation of getaddrinfo segfaults
90+
# if AI_NUMERICSERV is set, and servname is NULL or 0.
91+
{% if flag?(:darwin) %}
92+
if (service == 0 || service == nil) && (hints.ai_flags & LibC::AI_NUMERICSERV)
93+
hints.ai_flags |= LibC::AI_NUMERICSERV
94+
service = "00"
95+
end
96+
{% end %}
97+
8998
case ret = LibC.getaddrinfo(domain, service.to_s, pointerof(hints), out ptr)
9099
when 0
91100
# success

0 commit comments

Comments
 (0)
Please sign in to comment.