Correcly handle message headers when gatewaying. Closes #4322 and #4447.