# Buggy code
def run(self):
    r = self.flow.request
    first_line_format_backup = r.first_line_format
    server = None
    try:
        self.flow.response = None

        # If we have a channel, run script hooks.
        if self.channel:
            request_reply = self.channel.ask("request", self.flow)
            if isinstance(request_reply, models.HTTPResponse):
                self.flow.response = request_reply

        if not self.flow.response:
            # In all modes, we directly connect to the server displayed
            if self.config.options.mode == "upstream":
                server_address = self.config.upstream_server.address
                server = models.ServerConnection(
                    server_address, (self.config.options.listen_host, 0)
                )
                server.connect()
                if r.scheme == "https":
                    connect_request = models.make_connect_request((r.data.host, r.port))
                    server.wfile.write(http1.assemble_request(connect_request))
                    server.wfile.flush()
                    resp = http1.read_response(
                        server.rfile,
                        connect_request,
                        body_size_limit=self.config.options.body_size_limit,
                    )
                    if resp.status_code != 200:
                        raise exceptions.ReplayException(
                            "Upstream server refuses CONNECT request"
                        )
                    server.establish_ssl(
                        self.config.clientcerts, sni=self.flow.server_conn.sni
                    )
                    r.first_line_format = "relative"
                else:
                    r.first_line_format = "absolute"
            else:
                server_address = (r.host, r.port)
                server = models.ServerConnection(
                    server_address, (self.config.options.listen_host, 0)
                )
                server.connect()
                if r.scheme == "https":
                    server.establish_ssl(
                        self.config.clientcerts, sni=self.flow.server_conn.sni
                    )
                r.first_line_format = "relative"

            server.wfile.write(http1.assemble_request(r))
            server.wfile.flush()
            self.flow.server_conn = server
            self.flow.response = models.HTTPResponse.wrap(
                http1.read_response(
                    server.rfile, r, body_size_limit=self.config.options.body_size_limit
                )
            )
        if self.channel:
            response_reply = self.channel.ask("response", self.flow)
            if response_reply == exceptions.Kill:
                raise exceptions.Kill()
    except (exceptions.ReplayException, netlib.exceptions.NetlibException) as e:
        self.flow.error = models.Error(str(e))
        if self.channel:
            self.channel.ask("error", self.flow)
    except exceptions.Kill:
        # Kill should only be raised if there's a channel in the
        # first place.
        from ..proxy.root_context import Log

        self.channel.tell("log", Log("Connection killed", "info"))
    except Exception:
        from ..proxy.root_context import Log

        self.channel.tell("log", Log(traceback.format_exc(), "error"))
    finally:
        r.first_line_format = first_line_format_backup
        if server:
            server.finish()


# Traceback (AttributeError)
user@user-ubuntu:~$ mitmproxy
Exception ignored in: <bound method Reply.__del__ of <mitmproxy.controller.Reply object at 0x7f69de8646a0>>
Traceback (most recent call last):
File "/media/sf_git/mitmproxy/mitmproxy/controller.py", line 269, in __del__
raise exceptions.ControlException("Un-acked message: %s" % self.obj)
mitmproxy.exceptions.ControlException: Un-acked message: <HTTPFlow
request = Request(GET www.example.com:80/)
server_conn = <ServerConnection: www.example.com:80>>
Exception ignored in: <bound method Reply.__del__ of <mitmproxy.controller.Reply object at 0x7f69de864da0>>
Traceback (most recent call last):
File "/media/sf_git/mitmproxy/mitmproxy/controller.py", line 269, in __del__
raise exceptions.ControlException("Un-acked message: %s" % self.obj)
mitmproxy.exceptions.ControlException: Un-acked message: <HTTPFlow
request = Request(GET www.example.com:80/)
response = Response(200 OK, text/html, 1.24k)
server_conn = <ServerConnection: www.example.com:80>>
rTraceback (most recent call last):
File "/media/sf_git/mitmproxy/mitmproxy/console/master.py", line 502, in run
self.loop.run()
File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 278, in run
self._run()
File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 376, in _run
self.event_loop.run()
File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 682, in run
self._loop()
File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 715, in _loop
alarm_callback()
File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 164, in cb
callback(self, user_data)
File "/media/sf_git/mitmproxy/mitmproxy/console/master.py", line 448, in ticker
changed = self.tick(timeout=0)
File "/media/sf_git/mitmproxy/mitmproxy/flow/master.py", line 140, in tick
return super(FlowMaster, self).tick(timeout)
File "/media/sf_git/mitmproxy/mitmproxy/controller.py", line 136, in tick
handle_func(obj)
File "/media/sf_git/mitmproxy/mitmproxy/controller.py", line 219, in wrapper
master.addons(f.__name__, message)
File "/media/sf_git/mitmproxy/mitmproxy/addons.py", line 64, in __call__
self.invoke(i, name, *args, **kwargs)
File "/media/sf_git/mitmproxy/mitmproxy/addons.py", line 60, in invoke
func(*args, **kwargs)
File "/media/sf_git/mitmproxy/mitmproxy/builtins/setheaders.py", line 39, in response
self.run(flow, flow.response.headers)
AttributeError: 'NoneType' object has no attribute 'headers'

mitmproxy has crashed!
Please lodge a bug report at:
https://github.com/mitmproxy/mitmproxy
Shutting down...
rrrrrrrrrrException ignored in: <bound method Reply.__del__ of <mitmproxy.controller.Reply object at 0x7f69df0c2c18>>
Traceback (most recent call last):
File "/media/sf_git/mitmproxy/mitmproxy/controller.py", line 269, in __del__
mitmproxy.exceptions.ControlException: Un-acked message: <HTTPFlow
request = Request(GET www.example.com:80/)
response = Response(200 OK, text/html, 1.24k)
error = Connection killed
server_conn = <ServerConnection: www.example.com:80>>
user@user-ubuntu:~$ mitmproxy
rException ignored in: <bound method Reply.__del__ of <mitmproxy.controller.Reply object at 0x7f17c5270ac8>>
Traceback (most recent call last):
File "/media/sf_git/mitmproxy/mitmproxy/controller.py", line 269, in __del__
raise exceptions.ControlException("Un-acked message: %s" % self.obj)
mitmproxy.exceptions.ControlException: Un-acked message: <HTTPFlow
request = Request(GET www.example.com:80/)
response = Response(200 OK, text/html, 1.24k)
server_conn = <ServerConnection: www.example.com:80>>
rException ignored in: <bound method Reply.__del__ of <mitmproxy.controller.Reply object at 0x7f17c5291908>>
Traceback (most recent call last):
File "/media/sf_git/mitmproxy/mitmproxy/controller.py", line 269, in __del__
raise exceptions.ControlException("Un-acked message: %s" % self.obj)
mitmproxy.exceptions.ControlException: Un-acked message: <HTTPFlow
request = Request(GET www.example.com:80/)
response = Response(200 OK, text/html, 1.24k)
server_conn = <ServerConnection: www.example.com:80>>
Traceback (most recent call last):
File "/media/sf_git/mitmproxy/mitmproxy/console/master.py", line 502, in run
self.loop.run()
File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 278, in run
self._run()
File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 376, in _run
self.event_loop.run()
File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 682, in run
self._loop()
File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 715, in _loop
alarm_callback()
File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 164, in cb
callback(self, user_data)
File "/media/sf_git/mitmproxy/mitmproxy/console/master.py", line 448, in ticker
changed = self.tick(timeout=0)
File "/media/sf_git/mitmproxy/mitmproxy/flow/master.py", line 140, in tick
return super(FlowMaster, self).tick(timeout)
File "/media/sf_git/mitmproxy/mitmproxy/controller.py", line 136, in tick
handle_func(obj)
File "/media/sf_git/mitmproxy/mitmproxy/controller.py", line 219, in wrapper
master.addons(f.__name__, message)
File "/media/sf_git/mitmproxy/mitmproxy/addons.py", line 64, in __call__
self.invoke(i, name, *args, **kwargs)
File "/media/sf_git/mitmproxy/mitmproxy/addons.py", line 60, in invoke
func(*args, **kwargs)
File "/media/sf_git/mitmproxy/mitmproxy/builtins/setheaders.py", line 39, in response
self.run(flow, flow.response.headers)
AttributeError: 'NoneType' object has no attribute 'headers'

mitmproxy has crashed!
Please lodge a bug report at:
https://github.com/mitmproxy/mitmproxy
Shutting down...

# Fixed code
def run(self):
    r = self.flow.request
    first_line_format_backup = r.first_line_format
    server = None
    try:
        self.flow.response = None

        # If we have a channel, run script hooks.
        if self.channel:
            request_reply = self.channel.ask("request", self.flow)
            if isinstance(request_reply, models.HTTPResponse):
                self.flow.response = request_reply

        if not self.flow.response:
            # In all modes, we directly connect to the server displayed
            if self.config.options.mode == "upstream":
                server_address = self.config.upstream_server.address
                server = models.ServerConnection(
                    server_address, (self.config.options.listen_host, 0)
                )
                server.connect()
                if r.scheme == "https":
                    connect_request = models.make_connect_request((r.data.host, r.port))
                    server.wfile.write(http1.assemble_request(connect_request))
                    server.wfile.flush()
                    resp = http1.read_response(
                        server.rfile,
                        connect_request,
                        body_size_limit=self.config.options.body_size_limit,
                    )
                    if resp.status_code != 200:
                        raise exceptions.ReplayException(
                            "Upstream server refuses CONNECT request"
                        )
                    server.establish_ssl(
                        self.config.clientcerts, sni=self.flow.server_conn.sni
                    )
                    r.first_line_format = "relative"
                else:
                    r.first_line_format = "absolute"
            else:
                server_address = (r.host, r.port)
                server = models.ServerConnection(
                    server_address, (self.config.options.listen_host, 0)
                )
                server.connect()
                if r.scheme == "https":
                    server.establish_ssl(
                        self.config.clientcerts, sni=self.flow.server_conn.sni
                    )
                r.first_line_format = "relative"

            server.wfile.write(http1.assemble_request(r))
            server.wfile.flush()
            self.flow.server_conn = server
            self.flow.response = models.HTTPResponse.wrap(
                http1.read_response(
                    server.rfile, r, body_size_limit=self.config.options.body_size_limit
                )
            )
        if self.channel:
            response_reply = self.channel.ask("response", self.flow)
            if response_reply == exceptions.Kill:
                raise exceptions.Kill()
    except (exceptions.ReplayException, netlib.exceptions.NetlibException) as e:
        self.flow.error = models.Error(str(e))
        if self.channel:
            self.channel.ask("error", self.flow)
    except exceptions.Kill:
        # Kill should only be raised if there's a channel in the
        # first place.
        from ..proxy.root_context import Log

        self.channel.tell("log", Log("Connection killed", "info"))
    except Exception:
        from ..proxy.root_context import Log

        self.channel.tell("log", Log(traceback.format_exc(), "error"))
    finally:
        r.first_line_format = first_line_format_backup
        self.flow.live = False
        if server:
            server.finish()