-
-
Save cclgroupltd/127429c719938ed49c7450acb63d6d80 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Copyright 2021, CCL Forensics | |
Permission is hereby granted, free of charge, to any person obtaining a copy of | |
this software and associated documentation files (the "Software"), to deal in | |
the Software without restriction, including without limitation the rights to | |
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies | |
of the Software, and to permit persons to whom the Software is furnished to do | |
so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. | |
""" | |
def utf8_in_extended_ascii(input_string, *, raise_on_unexpected=False): | |
"""Returns a tuple of bool (whether mis-encoded utf-8 is present) and str (the converted string)""" | |
output = [] # individual characters, join at the end | |
is_in_multibyte = False # True if we're currently inside a utf-8 multibyte character | |
multibytes_expected = 0 | |
multibyte_buffer = [] | |
mis_encoded_utf8_present = False | |
def handle_bad_data(index, character): | |
if not raise_on_unexpected: # not raising, so we dump the buffer into output and append this character | |
output.extend(multibyte_buffer) | |
multibyte_buffer.clear() | |
output.append(character) | |
nonlocal is_in_multibyte | |
is_in_multibyte = False | |
nonlocal multibytes_expected | |
multibytes_expected = 0 | |
else: | |
raise ValueError(f"Expected multibyte continuation at index: {index}") | |
for idx, c in enumerate(input_string): | |
code_point = ord(c) | |
if code_point <= 0x7f or code_point > 0xf4: # ASCII Range data or higher than you get for mis-encoded utf-8: | |
if not is_in_multibyte: | |
output.append(c) # not in a multibyte, valid ascii-range data, so we append | |
else: | |
handle_bad_data(idx, c) | |
else: # potentially utf-8 | |
if (code_point & 0xc0) == 0x80: # continuation byte | |
if is_in_multibyte: | |
multibyte_buffer.append(c) | |
else: | |
handle_bad_data(idx, c) | |
else: # start-byte | |
if not is_in_multibyte: | |
assert multibytes_expected == 0 | |
assert len(multibyte_buffer) == 0 | |
while (code_point & 0x80) != 0: | |
multibytes_expected += 1 | |
code_point <<= 1 | |
multibyte_buffer.append(c) | |
is_in_multibyte = True | |
else: | |
handle_bad_data(idx, c) | |
if is_in_multibyte and len(multibyte_buffer) == multibytes_expected: # output utf-8 character if complete | |
utf_8_character = bytes(ord(x) for x in multibyte_buffer).decode("utf-8") | |
output.append(utf_8_character) | |
multibyte_buffer.clear() | |
is_in_multibyte = False | |
multibytes_expected = 0 | |
mis_encoded_utf8_present = True | |
if multibyte_buffer: # if we have left-over data | |
handle_bad_data(len(input_string), "") | |
return mis_encoded_utf8_present, "".join(output) | |
if __name__ == "__main__": | |
# Some tests | |
tests = [ | |
"Heart emoji: ❤", | |
"Heart emoji, incorrectly encoded as latin-1: \u00e2\u009d\u00a4", | |
"Heart emoji, incorrectly encoded as latin-1 and truncated: \u00e2\u009d", | |
"Just some latin-1: drinking coffee in a caf\u00e9 from a cafeti\u00e8re", | |
] | |
for test in tests: | |
print(utf8_in_extended_ascii(test, raise_on_unexpected=False)) | |
for test in tests: | |
try: | |
print(utf8_in_extended_ascii(test, raise_on_unexpected=True)) | |
except ValueError as ex: | |
print(ex) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment