Canonicalize hostname following MIT-krb5 behavior.
(hostname: str, option: str | bool)
| 176 | |
| 177 | |
| 178 | def _canonicalize_hostname(hostname: str, option: str | bool) -> str: |
| 179 | """Canonicalize hostname following MIT-krb5 behavior.""" |
| 180 | # https://github.com/krb5/krb5/blob/d406afa363554097ac48646a29249c04f498c88e/src/util/k5test.py#L505-L520 |
| 181 | if option in [False, "none"]: |
| 182 | return hostname |
| 183 | |
| 184 | af, socktype, proto, canonname, sockaddr = ( |
| 185 | _getaddrinfo( |
| 186 | hostname, |
| 187 | None, |
| 188 | family=0, |
| 189 | type=0, |
| 190 | proto=socket.IPPROTO_TCP, |
| 191 | flags=socket.AI_CANONNAME, |
| 192 | ) |
| 193 | )[0] # type: ignore[index] |
| 194 | |
| 195 | # For forward just to resolve the cname as dns.lookup() will not return it. |
| 196 | if option == "forward": |
| 197 | return canonname.lower() |
| 198 | |
| 199 | try: |
| 200 | name = socket.getnameinfo(sockaddr, socket.NI_NAMEREQD) |
| 201 | except socket.gaierror: |
| 202 | return canonname.lower() |
| 203 | |
| 204 | return name[0].lower() |
| 205 | |
| 206 | |
| 207 | def _authenticate_gssapi(credentials: MongoCredential, conn: Connection) -> None: |