Skip to content

gh-135500: Use ipaddress.ip_address instead of regex to detect IPv4 string in http.cookiejar #135502

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
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
19 changes: 13 additions & 6 deletions Lib/http/cookiejar.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import threading as _threading
import http.client # only for the default HTTP port
from calendar import timegm
from ipaddress import ip_address

debug = False # set to True to enable debugging via the logging module
logger = None
Expand Down Expand Up @@ -532,15 +533,21 @@ def parse_ns_headers(ns_headers):
return result


IPV4_RE = re.compile(r"\.\d+$", re.ASCII)
def is_ip(text):
"""Return True if text is a valid IP address."""
# This function is a replacement of regex `IPV4_RE` in previous versions.
try:
ip_address(text)
return True
except ValueError:
return False
def is_HDN(text):
"""Return True if text is a host domain name."""
# XXX
# This may well be wrong. Which RFC is HDN defined in, if any (for
# the purposes of RFC 2965)?
# For the current implementation, what about IPv6? Remember to look
# at other uses of IPV4_RE also, if change this.
if IPV4_RE.search(text):
# Now we support both IPv4 and IPv6.
if is_ip(text):
return False
if text == "":
return False
Expand Down Expand Up @@ -593,7 +600,7 @@ def liberal_is_HDN(text):
For accepting/blocking domains.

"""
if IPV4_RE.search(text):
if is_ip(text):
return False
return True

Expand Down Expand Up @@ -1067,7 +1074,7 @@ def set_ok_domain(self, cookie, request):
(self.strict_ns_domain & self.DomainStrictNoDots)):
host_prefix = req_host[:-len(domain)]
if (host_prefix.find(".") >= 0 and
not IPV4_RE.search(req_host)):
not is_ip(req_host)):
_debug(" host prefix %s for domain %s contains a dot",
host_prefix, domain)
return False
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
:mod:`http.cookiejar`: use :func:`~ipaddress.ip_address` instead of regex to check if a string is a HDN or a ipaddress.
Loading