Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 65 additions & 50 deletions src/hypercorn/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,61 +225,76 @@ def _create_sockets(
self, binds: list[str], type_: int = socket.SOCK_STREAM
) -> list[socket.socket]:
sockets: list[socket.socket] = []
for bind in binds:
binding: Any = None
if bind.startswith("unix:"):
sock = socket.socket(socket.AF_UNIX, type_)
binding = bind[5:]
try:
if stat.S_ISSOCK(os.stat(binding).st_mode):
os.remove(binding)
except FileNotFoundError:
pass
elif bind.startswith("fd://"):
sock = socket.socket(fileno=int(bind[5:]))
actual_type = sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)
if actual_type != type_:
raise SocketTypeError(type_, actual_type)
else:
bind = bind.replace("[", "").replace("]", "")
try:
value = bind.rsplit(":", 1)
host, port = value[0], int(value[1])
except (ValueError, IndexError):
host, port = bind, 8000
sock = socket.socket(socket.AF_INET6 if ":" in host else socket.AF_INET, type_)
try:
for bind in binds:
binding: Any = None
if bind.startswith("unix:"):
sock = socket.socket(socket.AF_UNIX, type_)
binding = bind[5:]
try:
if stat.S_ISSOCK(os.stat(binding).st_mode):
os.remove(binding)
except FileNotFoundError:
pass
elif bind.startswith("fd://"):
sock = socket.socket(fileno=int(bind[5:]))
actual_type = sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)
if actual_type != type_:
sock.detach()
raise SocketTypeError(type_, actual_type)
else:
bind = bind.replace("[", "").replace("]", "")
try:
value = bind.rsplit(":", 1)
host, port = value[0], int(value[1])
except (ValueError, IndexError):
host, port = bind, 8000
sock = socket.socket(
socket.AF_INET6 if ":" in host else socket.AF_INET, type_
)

if type_ == socket.SOCK_STREAM:
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

if self.workers > 1:
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
except AttributeError:
pass
binding = (host, port)

if type_ == socket.SOCK_STREAM:
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

if bind.startswith("unix:"):
if self.umask is not None:
current_umask = os.umask(self.umask)
sock.bind(binding)
if self.user is not None and self.group is not None:
os.chown(binding, self.user, self.group)
if self.umask is not None:
os.umask(current_umask)
elif bind.startswith("fd://"):
pass
else:
sock.bind(binding)

if self.workers > 1:
sock.setblocking(False)
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
sock.set_inheritable(True)
except AttributeError:
pass
binding = (host, port)

sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

if bind.startswith("unix:"):
if self.umask is not None:
current_umask = os.umask(self.umask)
sock.bind(binding)
if self.user is not None and self.group is not None:
os.chown(binding, self.user, self.group)
if self.umask is not None:
os.umask(current_umask)
elif bind.startswith("fd://"):
pass
else:
sock.bind(binding)

sock.setblocking(False)
try:
sock.set_inheritable(True)
except AttributeError:
pass
sockets.append(sock)
except BaseException:
if bind.startswith("fd://"):
sock.detach()
else:
sock.close()
raise
sockets.append(sock)
except BaseException:
for sock in sockets:
sock.close()
raise
return sockets

def response_headers(self, protocol: str) -> list[tuple[bytes, bytes]]:
Expand Down
35 changes: 35 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from __future__ import annotations

import gc
import os
import socket
import ssl
import sys
import warnings
from unittest.mock import Mock, NonCallableMock

import pytest
Expand Down Expand Up @@ -143,6 +145,39 @@ def test_create_sockets_multiple(monkeypatch: MonkeyPatch) -> None:
assert len(sockets.insecure_sockets) == 2


def test_create_sockets_closes_on_bind_failure() -> None:
occupied = socket.create_server(("127.0.0.1", 0))
config = Config()
config.bind = [f"127.0.0.1:{occupied.getsockname()[1]}"]
try:
with pytest.raises(OSError):
config.create_sockets()
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always", ResourceWarning)
gc.collect()
assert not any(issubclass(w.category, ResourceWarning) for w in caught)
finally:
occupied.close()


def test_create_sockets_closes_earlier_binds_on_later_failure() -> None:
occupied = socket.create_server(("127.0.0.1", 0))
free = socket.create_server(("127.0.0.1", 0))
free_port = free.getsockname()[1]
free.close()
config = Config()
config.bind = [f"127.0.0.1:{free_port}", f"127.0.0.1:{occupied.getsockname()[1]}"]
try:
with pytest.raises(OSError):
config.create_sockets()
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always", ResourceWarning)
gc.collect()
assert not any(issubclass(w.category, ResourceWarning) for w in caught)
finally:
occupied.close()


def test_response_headers(monkeypatch: MonkeyPatch) -> None:
monkeypatch.setattr(hypercorn.config, "time", lambda: 1_512_229_395)
config = Config()
Expand Down