Skip to content

Commit 6db7d4a

Browse files
fix: don't trust libmagic charset recognition (ietf-tools#9815)
1 parent f4307c7 commit 6db7d4a

1 file changed

Lines changed: 13 additions & 4 deletions

File tree

ietf/meeting/views.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,7 @@ def materials_document(request, document, num=None, ext=None):
329329
old_proceedings_format = meeting.number.isdigit() and int(meeting.number) <= 96
330330
if settings.MEETING_MATERIALS_SERVE_LOCALLY or old_proceedings_format:
331331
bytes = filename.read_bytes()
332-
mtype, chset = get_mime_type(bytes)
332+
mtype, chset = get_mime_type(bytes) # chset does not consider entire file!
333333
content_type = "%s; charset=%s" % (mtype, chset)
334334

335335
if filename.suffix == ".md" and mtype == "text/plain":
@@ -339,15 +339,24 @@ def materials_document(request, document, num=None, ext=None):
339339
content_type = content_type.replace("plain", "markdown", 1)
340340
break
341341
elif atype[0] == "text/html":
342+
# Render markdown, allowing that charset may be inaccurate.
343+
try:
344+
md_src = bytes.decode(
345+
"utf-8" if chset in ["ascii", "us-ascii"] else chset
346+
)
347+
except UnicodeDecodeError:
348+
# latin-1, aka iso8859-1, accepts all 8-bit code points
349+
md_src = bytes.decode("latin-1")
350+
content = markdown.markdown(md_src) # a string
342351
bytes = render_to_string(
343352
"minimal.html",
344353
{
345-
"content": markdown.markdown(bytes.decode(encoding=chset)),
354+
"content": content,
346355
"title": filename.name,
347356
"static_ietf_org": settings.STATIC_IETF_ORG,
348357
},
349-
)
350-
content_type = content_type.replace("plain", "html", 1)
358+
).encode("utf-8")
359+
content_type = "text/html; charset=utf-8"
351360
break
352361
elif atype[0] == "text/plain":
353362
break

0 commit comments

Comments
 (0)