Escape the characters in label which need it. @returns: the escaped string @rtype: string
(label: bytes | str)
| 144 | |
| 145 | |
| 146 | def _escapify(label: bytes | str) -> str: |
| 147 | """Escape the characters in label which need it. |
| 148 | @returns: the escaped string |
| 149 | @rtype: string""" |
| 150 | if isinstance(label, bytes): |
| 151 | # Ordinary DNS label mode. Escape special characters and values |
| 152 | # < 0x20 or > 0x7f. |
| 153 | text = "" |
| 154 | for c in label: |
| 155 | if c in _escaped: |
| 156 | text += "\\" + chr(c) |
| 157 | elif c > 0x20 and c < 0x7F: |
| 158 | text += chr(c) |
| 159 | else: |
| 160 | text += f"\\{c:03d}" |
| 161 | return text |
| 162 | |
| 163 | # Unicode label mode. Escape only special characters and values < 0x20 |
| 164 | text = "" |
| 165 | for uc in label: |
| 166 | if uc in _escaped_text: |
| 167 | text += "\\" + uc |
| 168 | elif uc <= "\x20": |
| 169 | text += f"\\{ord(uc):03d}" |
| 170 | else: |
| 171 | text += uc |
| 172 | return text |
| 173 | |
| 174 | |
| 175 | class IDNACodec: |