Fix crashes that could occur when detecting file mimetypes.

Review Request #14197 — Created Oct. 11, 2024 and submitted — Latest diff uploaded

Information

Review Board
release-7.x

Reviewers

We had a few issues that occurred in some environments when trying to
detect the mimetype of a file from its contents. These were rare,
dependent on Python version behavior and the implementation of file on
the system, but have been verified with one customer in particular:

  1. Some versions of Python break if you try to close an already-closed
    pipe, and this had happened on one customer's machine. file may
    close the input stream once it's read enough data to make a
    determination, and our attempt to close would then fail.

  2. We didn't set the mimetype variable if file returned a non-0 exit
    code, which resulted in later usage of an undefined variable.

  3. Errors executing or communicating with file would crash, and even
    if caught higher up it'd leave the uploaded file truncated (the file
    pointer wouldn't be at 0).

This change fixes all these through enhanged exception handlers and
checks, an unconditional reset of the uploaded file's file pointer, and
a fallback value for the mimetype.

All unit tests pass.

Notably, I cannot reproduce this bug in my environment, but I can verify
the cause in the affected customer's environment and that this would
address what we know about that crash.

Commits

Files