python / python/cpython

mimetypes raises UnicodeDecodeError when map files are not unicode encoded

Aperta
#117,807 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

stdlib type-bug
Lingua principale
Python
Stelle
77.2k
Fork
35.9k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Iniziate in Lib/mimetypes.py, nel percorso readfp() indicato dal traceback, e nel comportamento di apertura dei file utilizzato da mimetypes.init(files=["mimefile"]). Riproducete il problema con un file mime.types contenente un commento non UTF-8, quindi verificate che tali commenti non causino più UnicodeDecodeError mentre le mappature MIME rimangono leggibili.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
tooling
Tipo di issue
Bug
Difficoltà
3/5
Tempo stimato
1-2 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.