1"""Hostname."""
2
3# standard
4from functools import lru_cache
5import re
6from typing import Optional
7
8from .domain import domain
9
10# local
11from .ip_address import ipv4, ipv6
12from .utils import validator
13
14
15@lru_cache
16def _port_regex():
17 """Port validation regex."""
18 return re.compile(
19 r"^\:(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|"
20 + r"6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{0,3})$",
21 )
22
23
24@lru_cache
25def _simple_hostname_regex():
26 """Simple hostname validation regex."""
27 # {0,59} because two characters are already matched at
28 # the beginning and at the end, making the range {1, 61}
29 return re.compile(r"^(?!-)[a-z0-9](?:[a-z0-9-]{0,59}[a-z0-9])?(?<!-)$", re.IGNORECASE)
30
31
32def _port_validator(value: str):
33 """Returns host segment if port is valid."""
34 if value.count("]:") == 1:
35 # with ipv6
36 host_seg, port_seg = value.rsplit(":", 1)
37 if _port_regex().match(f":{port_seg}"):
38 return host_seg.lstrip("[").rstrip("]")
39
40 if value.count(":") == 1:
41 # with ipv4 or simple hostname
42 host_seg, port_seg = value.rsplit(":", 1)
43 if _port_regex().match(f":{port_seg}"):
44 return host_seg
45
46 return None
47
48
49@validator
50def hostname(
51 value: str,
52 /,
53 *,
54 skip_ipv6_addr: bool = False,
55 skip_ipv4_addr: bool = False,
56 may_have_port: bool = True,
57 maybe_simple: bool = True,
58 consider_tld: bool = False,
59 private: Optional[bool] = None, # only for ip-addresses
60 rfc_1034: bool = False,
61 rfc_2782: bool = False,
62):
63 """Return whether or not given value is a valid hostname.
64
65 Examples:
66 >>> hostname("ubuntu-pc:443")
67 True
68 >>> hostname("this-pc")
69 True
70 >>> hostname("xn----gtbspbbmkef.xn--p1ai:65535")
71 True
72 >>> hostname("_example.com")
73 ValidationError(func=hostname, args={'value': '_example.com'})
74 >>> hostname("123.5.77.88:31000")
75 True
76 >>> hostname("12.12.12.12")
77 True
78 >>> hostname("[::1]:22")
79 True
80 >>> hostname("dead:beef:0:0:0:0000:42:1")
81 True
82 >>> hostname("[0:0:0:0:0:ffff:1.2.3.4]:-65538")
83 ValidationError(func=hostname, args={'value': '[0:0:0:0:0:ffff:1.2.3.4]:-65538'})
84 >>> hostname("[0:&:b:c:@:e:f::]:9999")
85 ValidationError(func=hostname, args={'value': '[0:&:b:c:@:e:f::]:9999'})
86
87 Args:
88 value:
89 Hostname string to validate.
90 skip_ipv6_addr:
91 When hostname string cannot be an IPv6 address.
92 skip_ipv4_addr:
93 When hostname string cannot be an IPv4 address.
94 may_have_port:
95 Hostname string may contain port number.
96 maybe_simple:
97 Hostname string maybe only hyphens and alpha-numerals.
98 consider_tld:
99 Restrict domain to TLDs allowed by IANA.
100 private:
101 Embedded IP address is public if `False`, private/local if `True`.
102 rfc_1034:
103 Allow trailing dot in domain/host name.
104 Ref: [RFC 1034](https://www.rfc-editor.org/rfc/rfc1034).
105 rfc_2782:
106 Domain/Host name is of type service record.
107 Ref: [RFC 2782](https://www.rfc-editor.org/rfc/rfc2782).
108
109 Returns:
110 (Literal[True]): If `value` is a valid hostname.
111 (ValidationError): If `value` is an invalid hostname.
112 """
113 if not value:
114 return False
115
116 if may_have_port and (host_seg := _port_validator(value)):
117 return (
118 (_simple_hostname_regex().match(host_seg) if maybe_simple else False)
119 or domain(host_seg, consider_tld=consider_tld, rfc_1034=rfc_1034, rfc_2782=rfc_2782)
120 or (False if skip_ipv4_addr else ipv4(host_seg, cidr=False, private=private))
121 or (False if skip_ipv6_addr else ipv6(host_seg, cidr=False))
122 )
123
124 return (
125 (_simple_hostname_regex().match(value) if maybe_simple else False)
126 or domain(value, consider_tld=consider_tld, rfc_1034=rfc_1034, rfc_2782=rfc_2782)
127 or (False if skip_ipv4_addr else ipv4(value, cidr=False, private=private))
128 or (False if skip_ipv6_addr else ipv6(value, cidr=False))
129 )