Note that this pull request also includes my fix for #27315 (closed). This is because I use some of the refactoring I did for this fix. As such, this fix should be applied after #27315 (closed).
Github PR: https://github.com/torproject/tor/pull/2013