python / python/cpython

mimetypes raises UnicodeDecodeError when map files are not unicode encoded

オープン
#117,807 コメント 2 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

stdlib type-bug
主要言語
Python
スター
77.2k
フォーク
36k
PR マージ指標
PR 指標を取得中

説明

Bug report

Bug description:

Hi, when I use the mimetypes module and one of the known mime.types files include a non utf-8 encoded comment, the operation fails with UnicodeDecodeError:

......
  File "/usr/lib/python3.9/urllib/request.py", line 1506, in open_local_file
    mtype = mimetypes.guess_type(filename)[0]
  File "/usr/lib/python3.9/mimetypes.py", line 289, in guess_type
    init()
  File "/usr/lib/python3.9/mimetypes.py", line 362, in init
    db.read(file)
  File "/usr/lib/python3.9/mimetypes.py", line 204, in read
    self.readfp(fp, strict)
  File "/usr/lib/python3.9/mimetypes.py", line 215, in readfp
    line = fp.readline()
  File "/usr/lib/python3.9/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x83 in position 168: invalid start byte

The same can be forced with:

import mimetypes
mimetypes.init(files=["mimefile"]) 

and occurs because the file is opened in text mode expecting unicode encoding: https://github.com/python/cpython/blob/2e098abf95fc50f0d9a747140f8e17c5d8b65bce/Lib/mimetypes.py#L215

I am not sure whether there is a convention for which encoding the mime.types file will use, but I feel that at least comments should be allowed in any encoding?

CPython versions tested on:

3.9, 3.11

Operating systems tested on:

Linux, Other

Linked PRs
  • gh-151216
  • gh-155183
  • gh-155184
  • gh-155185

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

Lib/mimetypes.py の traceback で参照されている readfp() のパスと、mimetypes.init(files=["mimefile"]) で使用されるファイルオープンの動作から始めます。UTF-8 ではないコメントを含む mime.types ファイルで失敗を再現し、そのようなコメントが MIME マッピングを引き続き読み取り可能にしたまま、UnicodeDecodeError を引き起こさなくなっていることを確認します。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
tooling
issue の種類
バグ
難易度
3/5
見積もり時間
1〜2日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。