Extract the host and port from host header/authority information Raises: ValueError, if check is True and the authority information is malformed.
(authority: AnyStr, check: bool)
| 163 | |
| 164 | |
| 165 | def parse_authority(authority: AnyStr, check: bool) -> tuple[str, int | None]: |
| 166 | """Extract the host and port from host header/authority information |
| 167 | |
| 168 | Raises: |
| 169 | ValueError, if check is True and the authority information is malformed. |
| 170 | """ |
| 171 | try: |
| 172 | if isinstance(authority, bytes): |
| 173 | m = _authority_re.match(authority.decode("utf-8")) |
| 174 | if not m: |
| 175 | raise ValueError |
| 176 | host = m["host"].encode("utf-8").decode("idna") |
| 177 | else: |
| 178 | m = _authority_re.match(authority) |
| 179 | if not m: |
| 180 | raise ValueError |
| 181 | host = m.group("host") |
| 182 | |
| 183 | if host.startswith("[") and host.endswith("]"): |
| 184 | host = host[1:-1] |
| 185 | if not is_valid_host(host): |
| 186 | raise ValueError |
| 187 | |
| 188 | if m.group("port"): |
| 189 | port = int(m.group("port")) |
| 190 | if not is_valid_port(port): |
| 191 | raise ValueError |
| 192 | return host, port |
| 193 | else: |
| 194 | return host, None |
| 195 | |
| 196 | except ValueError: |
| 197 | if check: |
| 198 | raise |
| 199 | else: |
| 200 | return always_str(authority, "utf-8", "surrogateescape"), None |
searching dependent graphs…