gurudesh/pytracebugs huggingface dataset:
# Buggy code
def keypress(self, size, key):
    key = common.shortcuts(key)
    if key == "z":
        self.master.clear_events()
        key = None
    elif key == "G":
        self.set_focus(len(self.master.logbuffer) - 1)
    elif key == "g":
        self.set_focus(0)
    elif key == "F":
        o = self.master.options
        o.focus_follow = not o.focus_follow
    return urwid.ListBox.keypress(self, size, key)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/mitmproxy/tools/console/master.py", line 281, in run
self.loop.run()
File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/urwid/main_loop.py", line 278, in run
self._run()
File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/urwid/main_loop.py", line 376, in _run
self.event_loop.run()
File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/urwid/main_loop.py", line 682, in run
self._loop()
File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/urwid/main_loop.py", line 719, in _loop
self._watch_files[fd]()
File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/urwid/raw_display.py", line 393, in <lambda>
event_loop, callback, self.get_available_raw_input())
File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/urwid/raw_display.py", line 493, in parse_input
callback(processed, processed_codes)
File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/urwid/main_loop.py", line 403, in _update
self.process_input(keys)
File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/urwid/main_loop.py", line 503, in process_input
k = self._topmost_widget.keypress(self.screen_size, k)
File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/mitmproxy/tools/console/window.py", line 84, in keypress
k = super().keypress(size, k)
File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/urwid/container.py", line 1128, in keypress
return self.body.keypress( (maxcol, remaining), key )
File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/mitmproxy/tools/console/flowlist.py", line 116, in keypress
return self.focus_item.keypress(tsize, key)
File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/urwid/container.py", line 1128, in keypress
return self.body.keypress( (maxcol, remaining), key )
File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/mitmproxy/tools/console/flowlist.py", line 71, in keypress
o.focus_follow = not o.focus_follow
File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/mitmproxy/optmanager.py", line 107, in __getattr__
raise AttributeError("No such option: %s" % attr)
AttributeError: No such option: focus_follow

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

# Fixed code
def keypress(self, size, key):
    key = common.shortcuts(key)
    if key == "z":
        self.master.clear_events()
        key = None
    elif key == "G":
        self.set_focus(len(self.master.logbuffer) - 1)
    elif key == "g":
        self.set_focus(0)
    elif key == "F":
        o = self.master.options
        o.console_focus_follow = not o.console_focus_follow
    return urwid.ListBox.keypress(self, size, key)
# Buggy code
def mkopt(name):
    return select.Option(
        i,
        None,
        lambda: self.master.options.console_palette == name,
        lambda: setattr(self.master.options, "palette", name),
    )


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/mitmproxy/tools/console/master.py", line 281, in run
self.loop.run()
File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 278, in run
self._run()
File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 376, in _run
self.event_loop.run()
File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 682, in run
self._loop()
File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 719, in _loop
self._watch_files[fd]()
File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/urwid/raw_display.py", line 393, in <lambda>
event_loop, callback, self.get_available_raw_input())
File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/urwid/raw_display.py", line 493, in parse_input
callback(processed, processed_codes)
File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 403, in _update
self.process_input(keys)
File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 503, in process_input
k = self._topmost_widget.keypress(self.screen_size, k)
File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/mitmproxy/tools/console/window.py", line 84, in keypress
k = super().keypress(size, k)
File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/urwid/container.py", line 1128, in keypress
return self.body.keypress( (maxcol, remaining), key )
File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/urwid/container.py", line 1128, in keypress
return self.body.keypress( (maxcol, remaining), key )
File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/mitmproxy/tools/console/select.py", line 114, in keypress
self.get_focus()[0].option.activate()
File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/mitmproxy/tools/console/palettepicker.py", line 46, in <lambda>
lambda: setattr(self.master.options, "palette", name)
File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/mitmproxy/optmanager.py", line 114, in __setattr__
self.update(**{attr: value})
File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/mitmproxy/optmanager.py", line 141, in update
raise KeyError("No such option: %s" % k)
KeyError: 'No such option: palette'

# Fixed code
def mkopt(name):
    return select.Option(
        i,
        None,
        lambda: self.master.options.console_palette == name,
        lambda: setattr(self.master.options, "console_palette", name),
    )
# Buggy code
def encode_callback(self, key, conn):
    encoding_map = {
        "z": "gzip",
        "d": "deflate",
        "b": "brotli",
    }
    conn.encode(encoding_map[key])
    signals.flow_change.send(self, flow=self.flow)


# Traceback (ValueError)
Traceback (most recent call last):
File "/home/whackashoe/code/mitmproxy/mitmproxy/tools/console/master.py", line 281, in run
self.loop.run()
File "/home/whackashoe/code/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 278, in run
self._run()
File "/home/whackashoe/code/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 376, in _run
self.event_loop.run()
File "/home/whackashoe/code/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 682, in run
self._loop()
File "/home/whackashoe/code/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 719, in _loop
self._watch_files[fd]()
File "/home/whackashoe/code/mitmproxy/venv/lib/python3.5/site-packages/urwid/raw_display.py", line 393, in <lambda>
event_loop, callback, self.get_available_raw_input())
File "/home/whackashoe/code/mitmproxy/venv/lib/python3.5/site-packages/urwid/raw_display.py", line 493, in parse_input
callback(processed, processed_codes)
File "/home/whackashoe/code/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 403, in _update
self.process_input(keys)
File "/home/whackashoe/code/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 503, in process_input
k = self._topmost_widget.keypress(self.screen_size, k)
File "/home/whackashoe/code/mitmproxy/mitmproxy/tools/console/window.py", line 84, in keypress
k = super().keypress(size, k)
File "/home/whackashoe/code/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1116, in keypress
return self.footer.keypress((maxcol,),key)
File "/home/whackashoe/code/mitmproxy/mitmproxy/tools/console/statusbar.py", line 155, in keypress
return self.master.ab.keypress(*args, **kwargs)
File "/home/whackashoe/code/mitmproxy/mitmproxy/tools/console/statusbar.py", line 108, in keypress
self.prompt_execute(k)
File "/home/whackashoe/code/mitmproxy/mitmproxy/tools/console/statusbar.py", line 133, in prompt_execute
msg = p(txt)
File "/home/whackashoe/code/mitmproxy/mitmproxy/tools/console/statusbar.py", line 31, in __call__
return self.callback(txt, *self.args)
File "/home/whackashoe/code/mitmproxy/mitmproxy/tools/console/flowview.py", line 686, in encode_callback
conn.encode(encoding_map[key])
File "/home/whackashoe/code/mitmproxy/mitmproxy/net/http/message.py", line 245, in encode
raise ValueError("Invalid content encoding {}".format(repr(e)))
ValueError: Invalid content encoding 'brotli'

# Fixed code
def encode_callback(self, key, conn):
    encoding_map = {
        "z": "gzip",
        "d": "deflate",
        "b": "br",
    }
    conn.encode(encoding_map[key])
    signals.flow_change.send(self, flow=self.flow)
# Buggy code
def change_this_display_mode(self, t):
    name = contentviews.get_by_shortcut(t).name
    self.view.settings[self.flow][(self.tab_offset, "prettyview")] = name
    signals.flow_change.send(self, flow=self.flow)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/media/sf_git/mitmproxy/mitmproxy/tools/console/master.py", line 290, in run
self.loop.run()
File "/home/user/venv/lib64/python3.5/site-packages/urwid/main_loop.py", line 278, in run
self._run()
File "/home/user/venv/lib64/python3.5/site-packages/urwid/main_loop.py", line 376, in _run
self.event_loop.run()
File "/home/user/venv/lib64/python3.5/site-packages/urwid/main_loop.py", line 682, in run
self._loop()
File "/home/user/venv/lib64/python3.5/site-packages/urwid/main_loop.py", line 719, in _loop
self._watch_files[fd]()
File "/home/user/venv/lib64/python3.5/site-packages/urwid/raw_display.py", line 393, in <lambda>
event_loop, callback, self.get_available_raw_input())
File "/home/user/venv/lib64/python3.5/site-packages/urwid/raw_display.py", line 493, in parse_input
callback(processed, processed_codes)
File "/home/user/venv/lib64/python3.5/site-packages/urwid/main_loop.py", line 403, in _update
self.process_input(keys)
File "/home/user/venv/lib64/python3.5/site-packages/urwid/main_loop.py", line 503, in process_input
k = self._topmost_widget.keypress(self.screen_size, k)
File "/media/sf_git/mitmproxy/mitmproxy/tools/console/window.py", line 84, in keypress
k = super().keypress(size, k)
File "/home/user/venv/lib64/python3.5/site-packages/urwid/container.py", line 1116, in keypress
return self.footer.keypress((maxcol,),key)
File "/media/sf_git/mitmproxy/mitmproxy/tools/console/statusbar.py", line 132, in keypress
return self.master.ab.keypress(*args, **kwargs)
File "/media/sf_git/mitmproxy/mitmproxy/tools/console/statusbar.py", line 85, in keypress
self.prompt_execute(k)
File "/media/sf_git/mitmproxy/mitmproxy/tools/console/statusbar.py", line 110, in prompt_execute
msg = p(txt, *args)
File "/media/sf_git/mitmproxy/mitmproxy/tools/console/flowview.py", line 486, in change_this_display_mode
name = contentviews.get_by_shortcut(t).name
AttributeError: 'NoneType' object has no attribute 'name'

# Fixed code
def change_this_display_mode(self, t):
    view = contentviews.get_by_shortcut(t)
    if view:
        self.view.settings[self.flow][(self.tab_offset, "prettyview")] = view.name
    else:
        self.view.settings[self.flow][(self.tab_offset, "prettyview")] = None
    signals.flow_change.send(self, flow=self.flow)
# Buggy code
def inbounds(self, index: int) -> bool:
    """
    Is this index >= 0 and < len(self)
    """
    return index >= 0 and index < len(self)


# Traceback (ValueError)
Traceback (most recent call last):
File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/master.py", line 290, 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 719, in _loop
self._watch_files[fd]()
File "/usr/local/lib/python3.5/dist-packages/urwid/raw_display.py", line 393, in <lambda>
event_loop, callback, self.get_available_raw_input())
File "/usr/local/lib/python3.5/dist-packages/urwid/raw_display.py", line 493, in parse_input
callback(processed, processed_codes)
File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 403, in _update
self.process_input(keys)
File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 503, in process_input
k = self._topmost_widget.keypress(self.screen_size, k)
File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/window.py", line 84, in keypress
k = super().keypress(size, k)
File "/usr/local/lib/python3.5/dist-packages/urwid/container.py", line 1128, in keypress
return self.body.keypress( (maxcol, remaining), key )
File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/flowlist.py", line 360, in keypress
self.master.view.focus.index = len(self.master.view) - 1
File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/addons/view.py", line 364, in index
raise ValueError("Index out of view bounds")
ValueError: Index out of view bounds

# Fixed code
def inbounds(self, index: int) -> bool:
    """
    Is this 0 <= index < len(self)
    """
    return 0 <= index < len(self)
# Buggy code
def index(self, idx) -> typing.Optional[int]:
    if idx < 0 or idx > len(self.view) - 1:
        raise ValueError("Index out of view bounds")
    self.flow = self.view[idx]


# Traceback (ValueError)
Traceback (most recent call last):
File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/master.py", line 290, 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 719, in _loop
self._watch_files[fd]()
File "/usr/local/lib/python3.5/dist-packages/urwid/raw_display.py", line 393, in <lambda>
event_loop, callback, self.get_available_raw_input())
File "/usr/local/lib/python3.5/dist-packages/urwid/raw_display.py", line 493, in parse_input
callback(processed, processed_codes)
File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 403, in _update
self.process_input(keys)
File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 503, in process_input
k = self._topmost_widget.keypress(self.screen_size, k)
File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/window.py", line 84, in keypress
k = super().keypress(size, k)
File "/usr/local/lib/python3.5/dist-packages/urwid/container.py", line 1128, in keypress
return self.body.keypress( (maxcol, remaining), key )
File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/flowlist.py", line 360, in keypress
self.master.view.focus.index = len(self.master.view) - 1
File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/addons/view.py", line 364, in index
raise ValueError("Index out of view bounds")
ValueError: Index out of view bounds

# Fixed code
def index(self, idx):
    if idx < 0 or idx > len(self.view) - 1:
        raise ValueError("Index out of view bounds")
    self.flow = self.view[idx]
# Buggy code
def convert_to_ssl(self, *args, **kwargs):
    super().convert_to_ssl(*args, **kwargs)
    self.timestamp_ssl_setup = time.time()
    self.sni = self.connection.get_servername()
    self.cipher_name = self.connection.get_cipher_name()
    self.tls_version = self.connection.get_protocol_version_name()


# Traceback (TypeError)
Traceback (most recent call last):
File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/tornado/ioloop.py", line 1041, in _run
return self.callback()
File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/tools/web/master.py", line 172, in <lambda>
tornado.ioloop.PeriodicCallback(lambda: self.tick(timeout=0), 5).start()
File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/master.py", line 105, in tick
handle_func(obj)
File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/controller.py", line 70, in wrapper
master.addons(f.__name__, message)
File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/addonmanager.py", line 90, in __call__
self.invoke(i, name, *args, **kwargs)
File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/addonmanager.py", line 85, in invoke
func(*args, **kwargs)
File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/addons/state.py", line 285, in request
self.add_flow(f)
File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/addons/state.py", line 205, in add_flow
self.flows._add(f)
File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/addons/state.py", line 112, in _add
view._add(f)
File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/tools/web/master.py", line 33, in _add
data=app.convert_flow_to_json_dict(f)
File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/tools/web/app.py", line 174, in broadcast
message = json.dumps(kwargs, ensure_ascii=False)
File "/Users/han-pc/.pyenv/versions/3.5.2/lib/python3.5/json/__init__.py", line 237, in dumps
**kw).encode(obj)
File "/Users/han-pc/.pyenv/versions/3.5.2/lib/python3.5/json/encoder.py", line 198, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/Users/han-pc/.pyenv/versions/3.5.2/lib/python3.5/json/encoder.py", line 256, in iterencode
return _iterencode(o, 0)
File "/Users/han-pc/.pyenv/versions/3.5.2/lib/python3.5/json/encoder.py", line 179, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: b'example.com' is not JSON serializable

# Fixed code
def convert_to_ssl(self, *args, **kwargs):
    super().convert_to_ssl(*args, **kwargs)
    self.timestamp_ssl_setup = time.time()
    sni = self.connection.get_servername()
    if sni:
        self.sni = sni.decode("idna")
    else:
        self.sni = None
    self.cipher_name = self.connection.get_cipher_name()
    self.tls_version = self.connection.get_protocol_version_name()
# Buggy code
def __init__(
    self,
    type: str,
    client_conn: connections.ClientConnection,
    server_conn: connections.ServerConnection,
    live=None,
):
    self.type = type
    self.id = str(uuid.uuid4())
    self.client_conn = client_conn
    self.server_conn = server_conn
    self.live = live

    self.error = None  # type: Optional[Error]
    self.intercepted = False  # type: bool
    self._backup = None  # type: Optional[Flow]
    self.reply = None
    self.marked = False  # type: bool


# Traceback (mitmproxy.exceptions.ControlException)
Traceback (most recent call last):
File "/Users/manish/Work/mitmproxy/venv/bin/mitmproxy", line 11, in <module>
load_entry_point('mitmproxy', 'console_scripts', 'mitmproxy')()
File "/Users/manish/Work/mitmproxy/mitmproxy/main.py", line 80, in mitmproxy
m.run()
File "/Users/manish/Work/mitmproxy/mitmproxy/console/master.py", line 495, in run
self.shutdown()
File "/Users/manish/Work/mitmproxy/mitmproxy/console/master.py", line 647, in shutdown
self.state.killall(self)
File "/Users/manish/Work/mitmproxy/mitmproxy/flow/state.py", line 269, in killall
self.flows.kill_all(master)
File "/Users/manish/Work/mitmproxy/mitmproxy/flow/state.py", line 182, in kill_all
f.kill(master)
File "/Users/manish/Work/mitmproxy/mitmproxy/models/flow.py", line 176, in kill
master.error(self)
File "/Users/manish/Work/mitmproxy/mitmproxy/controller.py", line 238, in wrapper
ret = f(master, message)
File "/Users/manish/Work/mitmproxy/mitmproxy/console/master.py", line 692, in error
self.process_flow(f)
File "/Users/manish/Work/mitmproxy/mitmproxy/console/master.py", line 681, in process_flow
f.intercept(self)
File "/Users/manish/Work/mitmproxy/mitmproxy/models/flow.py", line 186, in intercept
self.reply.take()
File "/Users/manish/Work/mitmproxy/mitmproxy/controller.py", line 314, in take
raise exceptions.ControlException("Reply is {}, but expected it to be handled.".format(self.state))
mitmproxy.exceptions.ControlException: Reply is committed, but expected it to be handled.

# Fixed code
def __init__(
    self,
    type: str,
    client_conn: connections.ClientConnection,
    server_conn: connections.ServerConnection,
    live=None,
):
    self.type = type
    self.id = str(uuid.uuid4())
    self.client_conn = client_conn
    self.server_conn = server_conn
    self.live = live

    self.error = None  # type: Optional[Error]
    self.intercepted = False  # type: bool
    self._backup = None  # type: Optional[Flow]
    self.reply = None  # type: Optional[controller.Reply]
    self.marked = False  # type: bool
# Buggy code
def process_flow(self, f):
    should_intercept = any(
        [
            self.state.intercept
            and flowfilter.match(self.state.intercept, f)
            and not f.request.is_replay,
            f.intercepted,
        ]
    )
    if should_intercept:
        f.intercept(self)
    signals.flowlist_change.send(self)
    signals.flow_change.send(self, flow=f)


# Traceback (mitmproxy.exceptions.ControlException)
Traceback (most recent call last):
File "/Users/manish/Work/mitmproxy/venv/bin/mitmproxy", line 11, in <module>
load_entry_point('mitmproxy', 'console_scripts', 'mitmproxy')()
File "/Users/manish/Work/mitmproxy/mitmproxy/main.py", line 80, in mitmproxy
m.run()
File "/Users/manish/Work/mitmproxy/mitmproxy/console/master.py", line 495, in run
self.shutdown()
File "/Users/manish/Work/mitmproxy/mitmproxy/console/master.py", line 647, in shutdown
self.state.killall(self)
File "/Users/manish/Work/mitmproxy/mitmproxy/flow/state.py", line 269, in killall
self.flows.kill_all(master)
File "/Users/manish/Work/mitmproxy/mitmproxy/flow/state.py", line 182, in kill_all
f.kill(master)
File "/Users/manish/Work/mitmproxy/mitmproxy/models/flow.py", line 176, in kill
master.error(self)
File "/Users/manish/Work/mitmproxy/mitmproxy/controller.py", line 238, in wrapper
ret = f(master, message)
File "/Users/manish/Work/mitmproxy/mitmproxy/console/master.py", line 692, in error
self.process_flow(f)
File "/Users/manish/Work/mitmproxy/mitmproxy/console/master.py", line 681, in process_flow
f.intercept(self)
File "/Users/manish/Work/mitmproxy/mitmproxy/models/flow.py", line 186, in intercept
self.reply.take()
File "/Users/manish/Work/mitmproxy/mitmproxy/controller.py", line 314, in take
raise exceptions.ControlException("Reply is {}, but expected it to be handled.".format(self.state))
mitmproxy.exceptions.ControlException: Reply is committed, but expected it to be handled.

# Fixed code
def process_flow(self, f):
    should_intercept = (
        self.state.intercept
        and flowfilter.match(self.state.intercept, f)
        and not f.request.is_replay
        and f.reply.state == "handled"
    )
    if should_intercept:
        f.intercept(self)
    signals.flowlist_change.send(self)
    signals.flow_change.send(self, flow=f)
# Buggy code
def _process_flow(self, f):
    if self.state.intercept and self.state.intercept(f) and not f.request.is_replay:
        f.intercept(self)
    return f


# Traceback (mitmproxy.exceptions.ControlException)
Traceback (most recent call last):
File "/Users/manish/Work/mitmproxy/venv/bin/mitmproxy", line 11, in <module>
load_entry_point('mitmproxy', 'console_scripts', 'mitmproxy')()
File "/Users/manish/Work/mitmproxy/mitmproxy/main.py", line 80, in mitmproxy
m.run()
File "/Users/manish/Work/mitmproxy/mitmproxy/console/master.py", line 495, in run
self.shutdown()
File "/Users/manish/Work/mitmproxy/mitmproxy/console/master.py", line 647, in shutdown
self.state.killall(self)
File "/Users/manish/Work/mitmproxy/mitmproxy/flow/state.py", line 269, in killall
self.flows.kill_all(master)
File "/Users/manish/Work/mitmproxy/mitmproxy/flow/state.py", line 182, in kill_all
f.kill(master)
File "/Users/manish/Work/mitmproxy/mitmproxy/models/flow.py", line 176, in kill
master.error(self)
File "/Users/manish/Work/mitmproxy/mitmproxy/controller.py", line 238, in wrapper
ret = f(master, message)
File "/Users/manish/Work/mitmproxy/mitmproxy/console/master.py", line 692, in error
self.process_flow(f)
File "/Users/manish/Work/mitmproxy/mitmproxy/console/master.py", line 681, in process_flow
f.intercept(self)
File "/Users/manish/Work/mitmproxy/mitmproxy/models/flow.py", line 186, in intercept
self.reply.take()
File "/Users/manish/Work/mitmproxy/mitmproxy/controller.py", line 314, in take
raise exceptions.ControlException("Reply is {}, but expected it to be handled.".format(self.state))
mitmproxy.exceptions.ControlException: Reply is committed, but expected it to be handled.

# Fixed code
def _process_flow(self, f):
    should_intercept = (
        self.state.intercept
        and flowfilter.match(self.state.intercept, f)
        and not f.request.is_replay
        and f.reply.state == "handled"
    )
    if should_intercept:
        f.intercept(self)
    return f
# Buggy code
def server_sni(self):
    """
    The Server Name Indication we want to send with the next server TLS handshake.
    """
    if self._custom_server_sni is False:
        return None
    else:
        return self._custom_server_sni or self._client_hello.sni


# Traceback (AttributeError)
192.168.6.179:49564: clientconnect
Traceback (most recent call last):
File "/home/hynguyen/mitmproxy/mitmproxy/proxy/server.py", line 119, in handle
root_layer()
File "/home/hynguyen/mitmproxy/mitmproxy/proxy/modes/reverse_proxy.py", line 15, in __call__
layer()
File "/home/hynguyen/mitmproxy/mitmproxy/protocol/tls.py", line 372, in __call__
self._client_hello.alpn_protocols or
AttributeError: 'NoneType' object has no attribute 'alpn_protocols'

mitmproxy has crashed!
Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy
192.168.6.179:49564: Traceback (most recent call last):
File "/home/myname/mitmproxy/mitmproxy/proxy/server.py", line 119, in handle
root_layer()
File "/home/myname/mitmproxy/mitmproxy/proxy/modes/reverse_proxy.py", line 15, in __call__
layer()
File "/home/hynguyen/mitmproxy/mitmproxy/protocol/tls.py", line 372, in __call__
self._client_hello.alpn_protocols or
AttributeError: 'NoneType' object has no attribute 'alpn_protocols'

# Fixed code
def server_sni(self):
    """
    The Server Name Indication we want to send with the next server TLS handshake.
    """
    if self._custom_server_sni is False:
        return None
    else:
        return self._custom_server_sni or self._client_hello and self._client_hello.sni
# Buggy code
def __call__(self, data, **metadata):
    data = data.decode("utf-8")
    h = html2text.HTML2Text(baseurl="")
    h.ignore_images = True
    h.body_width = 0
    outline = h.handle(data)
    return "HTML Outline", format_text(outline)


# Traceback (TypeError)
Content viewer failed:
Traceback (most recent call last):
File "/Users/cortesi/mitmproxy/mitmproxy/mitmproxy/contentviews.py", line 634, in get_content_view
ret = viewmode(data, **metadata)
File "/Users/cortesi/mitmproxy/mitmproxy/mitmproxy/contentviews.py", line 151, in __call__
return content_types_map[ct][0](data, **metadata)
File "/Users/cortesi/mitmproxy/mitmproxy/mitmproxy/contentviews.py", line 401, in __call__
res = jsbeautifier.beautify(data, opts)
File "/Users/cortesi/mitmproxy/mitmproxy/mitmproxy/contrib/jsbeautifier/__init__.py", line 93, in beautify
return b.beautify(string, opts)
File "/Users/cortesi/mitmproxy/mitmproxy/mitmproxy/contrib/jsbeautifier/__init__.py", line 218, in beautify
token_text, token_type = self.get_next_token()
File "/Users/cortesi/mitmproxy/mitmproxy/mitmproxy/contrib/jsbeautifier/__init__.py", line 443, in
get_next_token
if c in self.wordchar:
TypeError: 'in <string>' requires string as left operand, not int

# Fixed code
def __call__(self, data, **metadata):
    data = data.decode("utf-8", "replace")
    h = html2text.HTML2Text(baseurl="")
    h.ignore_images = True
    h.body_width = 0
    outline = h.handle(data)
    return "HTML Outline", format_text(outline)
# Buggy code
def __call__(self, data, **metadata):
    if cssutils:
        sheet = cssutils.parseString(data)
        beautified = sheet.cssText
    else:
        beautified = data

    return "CSS", format_text(beautified)


# Traceback (TypeError)
Content viewer failed:
Traceback (most recent call last):
File "/Users/cortesi/mitmproxy/mitmproxy/mitmproxy/contentviews.py", line 634, in get_content_view
ret = viewmode(data, **metadata)
File "/Users/cortesi/mitmproxy/mitmproxy/mitmproxy/contentviews.py", line 151, in __call__
return content_types_map[ct][0](data, **metadata)
File "/Users/cortesi/mitmproxy/mitmproxy/mitmproxy/contentviews.py", line 401, in __call__
res = jsbeautifier.beautify(data, opts)
File "/Users/cortesi/mitmproxy/mitmproxy/mitmproxy/contrib/jsbeautifier/__init__.py", line 93, in beautify
return b.beautify(string, opts)
File "/Users/cortesi/mitmproxy/mitmproxy/mitmproxy/contrib/jsbeautifier/__init__.py", line 218, in beautify
token_text, token_type = self.get_next_token()
File "/Users/cortesi/mitmproxy/mitmproxy/mitmproxy/contrib/jsbeautifier/__init__.py", line 443, in
get_next_token
if c in self.wordchar:
TypeError: 'in <string>' requires string as left operand, not int

# Fixed code
def __call__(self, data, **metadata):
    cssutils.log.setLevel(logging.CRITICAL)
    cssutils.ser.prefs.keepComments = True
    cssutils.ser.prefs.omitLastSemicolon = False
    cssutils.ser.prefs.indentClosingBrace = False
    cssutils.ser.prefs.validOnly = False

    sheet = cssutils.parseString(data)
    beautified = sheet.cssText

    return "CSS", format_text(beautified)
# Buggy code
def clear(self):
    marked_flows = [f for f in self.state.view if f.marked]
    super(ConsoleState, self).clear()

    for f in marked_flows:
        self.add_flow(f)
        f.marked = True

    if len(self.flows.views) == 0:
        self.focus = None
    else:
        self.focus = 0
    self.set_focus(self.focus)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/media/sf_git/mitmproxy/mitmproxy/console/master.py", line 515, 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 719, in _loop
self._watch_files[fd]()
File "/usr/local/lib/python3.5/dist-packages/urwid/raw_display.py", line 393, in <lambda>
event_loop, callback, self.get_available_raw_input())
File "/usr/local/lib/python3.5/dist-packages/urwid/raw_display.py", line 493, in parse_input
callback(processed, processed_codes)
File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 403, in _update
self.process_input(keys)
File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 503, in process_input
k = self._topmost_widget.keypress(self.screen_size, k)
File "/media/sf_git/mitmproxy/mitmproxy/console/window.py", line 42, in keypress
k = super(self.__class__, self).keypress(size, k)
File "/usr/local/lib/python3.5/dist-packages/urwid/container.py", line 1128, in keypress
return self.body.keypress( (maxcol, remaining), key )
File "/media/sf_git/mitmproxy/mitmproxy/console/flowlist.py", line 361, in keypress
self.master.clear_flows()
File "/media/sf_git/mitmproxy/mitmproxy/console/master.py", line 686, in clear_flows
self.state.clear()
File "/media/sf_git/mitmproxy/mitmproxy/console/master.py", line 185, in clear
marked_flows = [f for f in self.state.view if f.marked]
AttributeError: 'ConsoleState' object has no attribute 'state'

# Fixed code
def clear(self):
    marked_flows = [f for f in self.view if f.marked]
    super(ConsoleState, self).clear()

    for f in marked_flows:
        self.add_flow(f)
        f.marked = True

    if len(self.flows.views) == 0:
        self.focus = None
    else:
        self.focus = 0
    self.set_focus(self.focus)
# Buggy code
def delete(self, flow_id):
    self.flow.kill(self.master)
    self.state.delete_flow(self.flow)


# Traceback (mitmproxy.exceptions.ControlException)
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 719, in _loop
self._watch_files[fd]()
File "/usr/local/lib/python3.5/dist-packages/urwid/raw_display.py", line 393, in <lambda>
event_loop, callback, self.get_available_raw_input())
File "/usr/local/lib/python3.5/dist-packages/urwid/raw_display.py", line 493, in parse_input
callback(processed, processed_codes)
File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 403, in _update
self.process_input(keys)
File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 503, in process_input
k = self._topmost_widget.keypress(self.screen_size, k)
File "/media/sf_git/mitmproxy/mitmproxy/console/window.py", line 42, in keypress
k = super(self.__class__, self).keypress(size, k)
File "/usr/local/lib/python3.5/dist-packages/urwid/container.py", line 1128, in keypress
return self.body.keypress( (maxcol, remaining), key )
File "/media/sf_git/mitmproxy/mitmproxy/console/flowlist.py", line 408, in keypress
return urwid.ListBox.keypress(self, size, key)
File "/usr/local/lib/python3.5/dist-packages/urwid/listbox.py", line 985, in keypress
key = focus_widget.keypress((maxcol,),key)
File "/media/sf_git/mitmproxy/mitmproxy/console/flowlist.py", line 258, in keypress
self.flow.kill(self.master)
File "/media/sf_git/mitmproxy/mitmproxy/models/flow.py", line 154, in kill
self.reply.kill()
File "/media/sf_git/mitmproxy/mitmproxy/controller.py", line 255, in kill
self.send(exceptions.Kill)
File "/media/sf_git/mitmproxy/mitmproxy/controller.py", line 262, in send
raise exceptions.ControlException("Message already acked.")
mitmproxy.exceptions.ControlException: Message already acked.

# Fixed code
def delete(self, flow_id):
    if not self.flow.reply.acked:
        self.flow.kill(self.master)
    self.state.delete_flow(self.flow)
# Buggy code
def set_focus(self, idx):
    if self.view:
        if idx >= len(self.view):
            idx = len(self.view) - 1
        elif idx < 0:
            idx = 0
        self.focus = idx
    else:
        self.focus = None


# Traceback (TypeError)
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 719, in _loop
self._watch_files[fd]()
File "/usr/local/lib/python3.5/dist-packages/urwid/raw_display.py", line 393, in <lambda>
event_loop, callback, self.get_available_raw_input())
File "/usr/local/lib/python3.5/dist-packages/urwid/raw_display.py", line 493, in parse_input
callback(processed, processed_codes)
File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 403, in _update
self.process_input(keys)
File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 503, in process_input
k = self._topmost_widget.keypress(self.screen_size, k)
File "/media/sf_git/mitmproxy/mitmproxy/console/window.py", line 42, in keypress
k = super(self.__class__, self).keypress(size, k)
File "/usr/local/lib/python3.5/dist-packages/urwid/container.py", line 1116, in keypress
return self.footer.keypress((maxcol,),key)
File "/media/sf_git/mitmproxy/mitmproxy/console/statusbar.py", line 134, in keypress
return self.master.ab.keypress(*args, **kwargs)
File "/media/sf_git/mitmproxy/mitmproxy/console/statusbar.py", line 89, in keypress
self.prompt_execute(self._w.get_edit_text())
File "/media/sf_git/mitmproxy/mitmproxy/console/statusbar.py", line 112, in prompt_execute
msg = p(txt, *args)
File "/media/sf_git/mitmproxy/mitmproxy/console/master.py", line 648, in set_limit
v = self.state.set_limit(txt)
File "/media/sf_git/mitmproxy/mitmproxy/console/master.py", line 79, in set_limit
self.set_focus(self.focus)
File "/media/sf_git/mitmproxy/mitmproxy/console/master.py", line 89, in set_focus
if idx >= len(self.view):
TypeError: unorderable types: NoneType() >= int()

# Fixed code
def set_focus(self, idx):
    if self.view:
        if idx is None or idx < 0:
            idx = 0
        elif idx >= len(self.view):
            idx = len(self.view) - 1
        self.focus = idx
    else:
        self.focus = None
# Buggy code
def request(self, f):
    flow.FlowMaster.request(self, f)
    self.state.delete_flow(f)
    if f:
        f.reply()
    return f


# Traceback (mitmproxy.exceptions.ControlException)
Traceback (most recent call last):
File "/mnt/storage/mitm/mitmproxy/venv/bin/mitmdump", line 9, in <module>
load_entry_point('mitmproxy', 'console_scripts', 'mitmdump')()
File "/mnt/storage/mitm/mitmproxy/mitmproxy/main.py", line 100, in mitmdump
master.run()
File "/mnt/storage/mitm/mitmproxy/mitmproxy/dump.py", line 355, in run
super(DumpMaster, self).run()
File "/mnt/storage/mitm/mitmproxy/mitmproxy/controller.py", line 61, in run
self.tick(0.1)
File "/mnt/storage/mitm/mitmproxy/mitmproxy/flow/master.py", line 228, in tick
return super(FlowMaster, self).tick(timeout)
File "/mnt/storage/mitm/mitmproxy/mitmproxy/controller.py", line 83, in tick
handle_func(obj)
File "/mnt/storage/mitm/mitmproxy/mitmproxy/controller.py", line 190, in wrapper
ret = f(*args, **kwargs)
File "/mnt/storage/mitm/mitmproxy/mitmproxy/dump.py", line 331, in request
self.state.delete_flow(f)
File "/mnt/storage/mitm/mitmproxy/mitmproxy/flow/state.py", line 220, in delete_flow
self.flows._remove(f)
File "/mnt/storage/mitm/mitmproxy/mitmproxy/flow/state.py", line 132, in _remove
self._list.remove(f)
Exception ValueError: list.remove(x): x not in list
mitmproxy.exceptions.ControlException: ControlException('Un-acked message',) in <bound method Reply.__del__ of <mitmproxy.controller.Reply object at 0x957c4f30>> ignored

# Fixed code
def request(self, f):
    f = flow.FlowMaster.request(self, f)
    if f:
        self.state.delete_flow(f)
    return f
# Buggy code
def response(self, f):
    flow.FlowMaster.response(self, f)
    if f:
        f.reply()
        self._process_flow(f)
    return f


# Traceback (mitmproxy.exceptions.ControlException)
Traceback (most recent call last):
File "/mnt/storage/mitm/mitmproxy/venv/bin/mitmdump", line 9, in <module>
load_entry_point('mitmproxy', 'console_scripts', 'mitmdump')()
File "/mnt/storage/mitm/mitmproxy/mitmproxy/main.py", line 100, in mitmdump
master.run()
File "/mnt/storage/mitm/mitmproxy/mitmproxy/dump.py", line 355, in run
super(DumpMaster, self).run()
File "/mnt/storage/mitm/mitmproxy/mitmproxy/controller.py", line 61, in run
self.tick(0.1)
File "/mnt/storage/mitm/mitmproxy/mitmproxy/flow/master.py", line 228, in tick
return super(FlowMaster, self).tick(timeout)
File "/mnt/storage/mitm/mitmproxy/mitmproxy/controller.py", line 83, in tick
handle_func(obj)
File "/mnt/storage/mitm/mitmproxy/mitmproxy/controller.py", line 190, in wrapper
ret = f(*args, **kwargs)
File "/mnt/storage/mitm/mitmproxy/mitmproxy/dump.py", line 331, in request
self.state.delete_flow(f)
File "/mnt/storage/mitm/mitmproxy/mitmproxy/flow/state.py", line 220, in delete_flow
self.flows._remove(f)
File "/mnt/storage/mitm/mitmproxy/mitmproxy/flow/state.py", line 132, in _remove
self._list.remove(f)
Exception ValueError: list.remove(x): x not in list
mitmproxy.exceptions.ControlException: ControlException('Un-acked message',) in <bound method Reply.__del__ of <mitmproxy.controller.Reply object at 0x957c4f30>> ignored

# Fixed code
def response(self, f):
    f = flow.FlowMaster.response(self, f)
    if f:
        self._process_flow(f)
    return f
# Buggy code
def ticker(self, *userdata):
    changed = self.tick(self.masterq, timeout=0)
    if changed:
        self.loop.draw_screen()
        signals.update_settings.send()
    self.loop.set_alarm_in(0.01, self.ticker)


# Traceback (AttributeError)
./mitmdump.run.sh: line 2: 14504 Segmentation fault      mitmdump -p 59873 > network
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/libmproxy/proxy/server.py", line 120, in handle
root_layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/proxy/modes/http_proxy.py", line 10, in __call__
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/tls.py", line 272, in __call__
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 130, in __call__
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 323, in __call__
self.handle_regular_mode_connect(request)
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 409, in handle_regular_mode_connect
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/tls.py", line 272, in __call__
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 130, in __call__
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 340, in __call__
self.get_response_from_server(flow)
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 471, in get_response_from_server
if flow.response.stream:
AttributeError: 'NoneType' object has no attribute 'response'

# Fixed code
def ticker(self, *userdata):
    changed = self.tick(timeout=0)
    if changed:
        self.loop.draw_screen()
        signals.update_settings.send()
    self.loop.set_alarm_in(0.01, self.ticker)
# Buggy code
def __init__(self, server):
    """
    server may be None if no server is needed.
    """
    self.server = server
    self.masterq = queue.Queue()
    self.should_exit = threading.Event()


# Traceback (AttributeError)
./mitmdump.run.sh: line 2: 14504 Segmentation fault      mitmdump -p 59873 > network
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/libmproxy/proxy/server.py", line 120, in handle
root_layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/proxy/modes/http_proxy.py", line 10, in __call__
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/tls.py", line 272, in __call__
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 130, in __call__
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 323, in __call__
self.handle_regular_mode_connect(request)
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 409, in handle_regular_mode_connect
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/tls.py", line 272, in __call__
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 130, in __call__
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 340, in __call__
self.get_response_from_server(flow)
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 471, in get_response_from_server
if flow.response.stream:
AttributeError: 'NoneType' object has no attribute 'response'

# Fixed code
def __init__(self):
    self.event_queue = queue.Queue()
    self.should_exit = threading.Event()
# Buggy code
def run(self):
    self.should_exit.clear()
    self.server.start_slave(Slave, Channel(self.masterq, self.should_exit))
    while not self.should_exit.is_set():
        # Don't choose a very small timeout in Python 2:
        # https://github.com/mitmproxy/mitmproxy/issues/443
        # TODO: Lower the timeout value if we move to Python 3.
        self.tick(self.masterq, 0.1)
    self.shutdown()


# Traceback (AttributeError)
./mitmdump.run.sh: line 2: 14504 Segmentation fault      mitmdump -p 59873 > network
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/libmproxy/proxy/server.py", line 120, in handle
root_layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/proxy/modes/http_proxy.py", line 10, in __call__
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/tls.py", line 272, in __call__
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 130, in __call__
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 323, in __call__
self.handle_regular_mode_connect(request)
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 409, in handle_regular_mode_connect
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/tls.py", line 272, in __call__
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 130, in __call__
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 340, in __call__
self.get_response_from_server(flow)
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 471, in get_response_from_server
if flow.response.stream:
AttributeError: 'NoneType' object has no attribute 'response'

# Fixed code
def run(self):
    self.start()
    try:
        while not self.should_exit.is_set():
            # Don't choose a very small timeout in Python 2:
            # https://github.com/mitmproxy/mitmproxy/issues/443
            # TODO: Lower the timeout value if we move to Python 3.
            self.tick(0.1)
    finally:
        self.shutdown()
# Buggy code
def tick(self, q, timeout):
    changed = False
    try:
        # This endless loop runs until the 'Queue.Empty'
        # exception is thrown. If more than one request is in
        # the queue, this speeds up every request by 0.1 seconds,
        # because get_input(..) function is not blocking.
        while True:
            msg = q.get(timeout=timeout)
            self.handle(*msg)
            q.task_done()
            changed = True
    except queue.Empty:
        pass
    return changed


# Traceback (AttributeError)
./mitmdump.run.sh: line 2: 14504 Segmentation fault      mitmdump -p 59873 > network
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/libmproxy/proxy/server.py", line 120, in handle
root_layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/proxy/modes/http_proxy.py", line 10, in __call__
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/tls.py", line 272, in __call__
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 130, in __call__
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 323, in __call__
self.handle_regular_mode_connect(request)
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 409, in handle_regular_mode_connect
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/tls.py", line 272, in __call__
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 130, in __call__
layer()
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 340, in __call__
self.get_response_from_server(flow)
File "/usr/local/lib/python2.7/site-packages/libmproxy/protocol/http.py", line 471, in get_response_from_server
if flow.response.stream:
AttributeError: 'NoneType' object has no attribute 'response'

# Fixed code
def tick(self, timeout):
    changed = False
    try:
        # This endless loop runs until the 'Queue.Empty'
        # exception is thrown.
        while True:
            mtype, obj = self.event_queue.get(timeout=timeout)
            handle_func = getattr(self, "handle_" + mtype)
            handle_func(obj)
            self.event_queue.task_done()
            changed = True
    except queue.Empty:
        pass
    return changed