gurudesh/pytracebugs huggingface dataset:
# Buggy code
def CompressShares(self, sharestype):
    if sharestype == "normal":
        streams = self.config.sections["transfers"]["sharedfilesstreams"]
    elif sharestype == "buddy":
        streams = self.config.sections["transfers"]["bsharedfilesstreams"]

    if streams is None:
        message = _("ERROR: No %(type)s shares database available") % {
            "type": sharestype
        }
        print(message)
        self.logMessage(message, None)
        return

    m = slskmessages.SharedFileList(None, streams)
    m.makeNetworkMessage(nozlib=0, rebuild=True)

    if sharestype == "normal":
        self.CompressedSharesNormal = m
    elif sharestype == "buddy":
        self.CompressedSharesBuddy = m


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'Klassiek\\Jean Sibelius\\Two Serenades for Violin and Orchestra, Op.69'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 2039, in _RescanFinished
self.np.shares.sendNumSharedFoldersFiles()
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 105, in sendNumSharedFoldersFiles
sharedfiles = sum([len(x) for x in list(conf["transfers"][shared_db].values())])
File "/usr/local/lib/python3.7/_collections_abc.py", line 762, in __iter__
yield self._mapping[key]
File "/usr/local/lib/python3.7/shelve.py", line 113, in __getitem__
f = BytesIO(self.dict[key.encode(self.keyencoding)])
File "/usr/local/lib/python3.7/shelve.py", line 70, in closed
raise ValueError('invalid operation on closed shelf')
ValueError: invalid operation on closed shelf

# Fixed code
def CompressShares(self, sharestype):
    if sharestype == "normal":
        streams = self.config.sections["transfers"]["sharedfilesstreams"]
    elif sharestype == "buddy":
        streams = self.config.sections["transfers"]["bsharedfilesstreams"]

    if streams is None:
        message = _("ERROR: No %(type)s shares database available") % {
            "type": sharestype
        }
        print(message)
        self.logMessage(message, None)
        return

    m = slskmessages.SharedFileList(None, streams)
    _thread.start_new_thread(m.makeNetworkMessage, (0, True))

    if sharestype == "normal":
        self.CompressedSharesNormal = m
    elif sharestype == "buddy":
        self.CompressedSharesBuddy = m
# Buggy code
def getFileInfo(self, name, pathname):
    try:
        size = os.path.getsize(pathname)
        info = metadata.detect(pathname)

        if info:
            # Sometimes the duration (time) or the bitrate of the file is unknown
            if info["time"] is None or info["bitrate"] is None:
                fileinfo = (name, size, None, None)
            else:
                bitrateinfo = (int(info["bitrate"]), int(info["vbr"]))
                fileinfo = (name, size, bitrateinfo, int(info["time"]))
        else:
            fileinfo = (name, size, None, None)

        return fileinfo

    except Exception as errtuple:
        message = _("Scanning File Error: %(error)s Path: %(path)s") % {
            "error": errtuple,
            "path": pathname,
        }
        self.logMessage(message)
        displayTraceback(sys.exc_info()[2])


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'Klassiek\\Jean Sibelius\\Two Serenades for Violin and Orchestra, Op.69'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 2039, in _RescanFinished
self.np.shares.sendNumSharedFoldersFiles()
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 105, in sendNumSharedFoldersFiles
sharedfiles = sum([len(x) for x in list(conf["transfers"][shared_db].values())])
File "/usr/local/lib/python3.7/_collections_abc.py", line 762, in __iter__
yield self._mapping[key]
File "/usr/local/lib/python3.7/shelve.py", line 113, in __getitem__
f = BytesIO(self.dict[key.encode(self.keyencoding)])
File "/usr/local/lib/python3.7/shelve.py", line 70, in closed
raise ValueError('invalid operation on closed shelf')
ValueError: invalid operation on closed shelf

# Fixed code
def getFileInfo(self, name, pathname):
    try:
        size = os.stat(pathname).st_size
        info = metadata.detect(pathname)

        if info:
            # Sometimes the duration (time) or the bitrate of the file is unknown
            if info["time"] is None or info["bitrate"] is None:
                fileinfo = (name, size, None, None)
            else:
                bitrateinfo = (int(info["bitrate"]), int(info["vbr"]))
                fileinfo = (name, size, bitrateinfo, int(info["time"]))
        else:
            fileinfo = (name, size, None, None)

        return fileinfo

    except Exception as errtuple:
        message = _("Scanning File Error: %(error)s Path: %(path)s") % {
            "error": errtuple,
            "path": pathname,
        }
        self.logMessage(message)
        displayTraceback(sys.exc_info()[2])
# Buggy code
def getDirStream(self, dir):
    msg = slskmessages.SlskMessage()
    stream = msg.packObject(NetworkIntType(len(dir)))

    for file_and_meta in dir:
        stream += self.getByteStream(file_and_meta)

    return stream


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'Klassiek\\Jean Sibelius\\Two Serenades for Violin and Orchestra, Op.69'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 2039, in _RescanFinished
self.np.shares.sendNumSharedFoldersFiles()
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 105, in sendNumSharedFoldersFiles
sharedfiles = sum([len(x) for x in list(conf["transfers"][shared_db].values())])
File "/usr/local/lib/python3.7/_collections_abc.py", line 762, in __iter__
yield self._mapping[key]
File "/usr/local/lib/python3.7/shelve.py", line 113, in __getitem__
f = BytesIO(self.dict[key.encode(self.keyencoding)])
File "/usr/local/lib/python3.7/shelve.py", line 70, in closed
raise ValueError('invalid operation on closed shelf')
ValueError: invalid operation on closed shelf

# Fixed code
def getDirStream(self, dir):
    stream = bytearray()
    stream.extend(slskmessages.SlskMessage().packObject(NetworkIntType(len(dir))))

    for file_and_meta in dir:
        stream.extend(self.getByteStream(file_and_meta))

    return stream
# Buggy code
def addToIndex(self, wordindex, fileindex, words, dir, fileinfo):
    index = len(list(fileindex.keys()))
    for i in words:
        if i not in wordindex:
            wordindex[i] = [index]
        else:
            wordindex[i] = wordindex[i] + [index]
    fileindex[str(index)] = (os.path.join(dir, fileinfo[0]),) + fileinfo[1:]


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'Klassiek\\Jean Sibelius\\Two Serenades for Violin and Orchestra, Op.69'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 2039, in _RescanFinished
self.np.shares.sendNumSharedFoldersFiles()
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 105, in sendNumSharedFoldersFiles
sharedfiles = sum([len(x) for x in list(conf["transfers"][shared_db].values())])
File "/usr/local/lib/python3.7/_collections_abc.py", line 762, in __iter__
yield self._mapping[key]
File "/usr/local/lib/python3.7/shelve.py", line 113, in __getitem__
f = BytesIO(self.dict[key.encode(self.keyencoding)])
File "/usr/local/lib/python3.7/shelve.py", line 70, in closed
raise ValueError('invalid operation on closed shelf')
ValueError: invalid operation on closed shelf

# Fixed code
def addToIndex(self, wordindex, fileindex, words, dir, fileinfo):
    index = len(fileindex)
    for i in words:
        if i not in wordindex:
            wordindex[i] = [index]
        else:
            wordindex[i] = wordindex[i] + [index]
    fileindex.append((os.path.join(dir, fileinfo[0]),) + fileinfo[1:])
# Buggy code
def OnSelectUserResults(self, widget):
    if len(self.selected_users) == 0:
        return

    selected_user = widget.get_parent().user

    sel = self.ResultsList.get_selection()
    fmodel = self.ResultsList.get_model()
    sel.unselect_all()
    iter = self.resultsmodel.get_iter_first()

    self.UserRowIter(fmodel, sel, selected_user, iter)

    self.select_results()


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/user/projects/nicotine-plus/pynicotine/gtkgui/frame.py", line 1297, in OnNetworkEvent
self.np.events[i.__class__](i)
File "/home/user/projects/nicotine-plus/pynicotine/pynicotine.py", line 1556, in QueueUpload
self.transfers.QueueUpload(msg)
File "/home/user/projects/nicotine-plus/pynicotine/transfers.py", line 700, in QueueUpload
self._updateOrAppendUpload(user, msg.file, newupload)
File "/home/user/projects/nicotine-plus/pynicotine/transfers.py", line 614, in _updateOrAppendUpload
self.uploadspanel.replace(i, transferobj)
File "/home/user/projects/nicotine-plus/pynicotine/gtkgui/transferlist.py", line 293, in replace
for i in self.transfers:
AttributeError: 'Uploads' object has no attribute 'transfers'
Traceback (most recent call last):
File "/home/user/projects/nicotine-plus/pynicotine/gtkgui/frame.py", line 1297, in OnNetworkEvent
self.np.events[i.__class__](i)
File "/home/user/projects/nicotine-plus/pynicotine/pynicotine.py", line 1556, in QueueUpload
self.transfers.QueueUpload(msg)
File "/home/user/projects/nicotine-plus/pynicotine/transfers.py", line 700, in QueueUpload
self._updateOrAppendUpload(user, msg.file, newupload)
File "/home/user/projects/nicotine-plus/pynicotine/transfers.py", line 614, in _updateOrAppendUpload
self.uploadspanel.replace(i, transferobj)
File "/home/user/projects/nicotine-plus/pynicotine/gtkgui/transferlist.py", line 293, in replace
for i in self.transfers:
AttributeError: 'Uploads' object has no attribute 'transfers'

# Fixed code
def OnSelectUserResults(self, widget):
    if len(self.selected_users) == 0:
        return

    selected_user = widget.get_parent().user

    sel = self.ResultsList.get_selection()
    fmodel = self.ResultsList.get_model()
    sel.unselect_all()

    iter = fmodel.get_iter_first()

    SelectUserRowIter(fmodel, sel, 1, selected_user, iter)

    self.select_results()
# Buggy code
def _storeObjects(self, storable_objects):
    for source, destination, filename in storable_objects:
        self.sections["transfers"][destination].close()
        self.sections["transfers"][destination] = shelve.open(
            os.path.join(self.data_dir, filename), flag="n"
        )

        for key, value in source.items():
            self.sections["transfers"][destination][key] = value


# Traceback (SystemError)
Thu 07:58 Nicotine+ supports a country code blocker. This requires a (GPL'ed) library called GeoIP. You can find it here: C library:       https://github.com/maxmind/geoip-api-c Python
bindings: https://github.com/maxmind/geoip-api-python (the python bindings require the C library)
Traceback (most recent call last):
File "/usr/local/bin/nicotine", line 255, in <module>
run()
File "/usr/local/bin/nicotine", line 231, in run
app = frame.MainApp(data_dir, config, plugins, trayicon, hidden, bindip, port)
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 3595, in __init__
self.frame = NicotineFrame(data_dir, config, plugins, trayicon, start_hidden, bindip, port)
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 273, in __init__
config
File "/usr/local/lib/python3.7/site-packages/pynicotine/pynicotine.py", line 130, in __init__
self.shares = Shares(self)
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 75, in __init__
self.CompressShares("normal")
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 201, in CompressShares
m.makeNetworkMessage(nozlib=0, rebuild=True)
File "/usr/local/lib/python3.7/site-packages/pynicotine/slskmessages.py", line 1709, in makeNetworkMessage
msg = msg + self.packObject(len(list(self.list.keys())))
File "/usr/local/lib/python3.7/_collections_abc.py", line 720, in __iter__
yield from self._mapping
File "/usr/local/lib/python3.7/shelve.py", line 95, in __iter__
for k in self.dict.keys():
SystemError: Negative size passed to PyBytes_FromStringAndSize

# Fixed code
def _storeObjects(self, storable_objects):
    for source, destination, filename in storable_objects:
        self.sections["transfers"][destination].close()
        self.sections["transfers"][destination] = shelve.open(
            os.path.join(self.data_dir, filename),
            flag="n",
            protocol=pickle.HIGHEST_PROTOCOL,
        )

        for key, value in source.items():
            self.sections["transfers"][destination][key] = value
# Buggy code
def writeAliases(self):
    self.config_lock.acquire()
    f = open(self.filename + ".alias", "wb")
    pickle.dump(self.aliases, f, 1)
    f.close()
    self.config_lock.release()


# Traceback (SystemError)
Thu 07:58 Nicotine+ supports a country code blocker. This requires a (GPL'ed) library called GeoIP. You can find it here: C library:       https://github.com/maxmind/geoip-api-c Python
bindings: https://github.com/maxmind/geoip-api-python (the python bindings require the C library)
Traceback (most recent call last):
File "/usr/local/bin/nicotine", line 255, in <module>
run()
File "/usr/local/bin/nicotine", line 231, in run
app = frame.MainApp(data_dir, config, plugins, trayicon, hidden, bindip, port)
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 3595, in __init__
self.frame = NicotineFrame(data_dir, config, plugins, trayicon, start_hidden, bindip, port)
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 273, in __init__
config
File "/usr/local/lib/python3.7/site-packages/pynicotine/pynicotine.py", line 130, in __init__
self.shares = Shares(self)
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 75, in __init__
self.CompressShares("normal")
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 201, in CompressShares
m.makeNetworkMessage(nozlib=0, rebuild=True)
File "/usr/local/lib/python3.7/site-packages/pynicotine/slskmessages.py", line 1709, in makeNetworkMessage
msg = msg + self.packObject(len(list(self.list.keys())))
File "/usr/local/lib/python3.7/_collections_abc.py", line 720, in __iter__
yield from self._mapping
File "/usr/local/lib/python3.7/shelve.py", line 95, in __iter__
for k in self.dict.keys():
SystemError: Negative size passed to PyBytes_FromStringAndSize

# Fixed code
def writeAliases(self):
    self.config_lock.acquire()
    f = open(self.filename + ".alias", "wb")
    pickle.dump(self.aliases, f, protocol=pickle.HIGHEST_PROTOCOL)
    f.close()
    self.config_lock.release()
# Buggy code
def OnPrevious(self, widget):
    if len(list(self.data.keys())) > 1:
        _list = list(self.data.keys())

        if self.current not in _list:
            ix -= 1  # noqa: F821
        else:
            ix = _list.index(self.current)
            ix -= 1

            if ix < 0:
                ix = -1
            elif ix >= len(_list):
                ix = 0

        if ix is not None:
            self.current = _list[ix]

    if self.current is None:
        return

    self.Display(self.current)


# Traceback (SystemError)
Thu 07:58 Nicotine+ supports a country code blocker. This requires a (GPL'ed) library called GeoIP. You can find it here: C library:       https://github.com/maxmind/geoip-api-c Python
bindings: https://github.com/maxmind/geoip-api-python (the python bindings require the C library)
Traceback (most recent call last):
File "/usr/local/bin/nicotine", line 255, in <module>
run()
File "/usr/local/bin/nicotine", line 231, in run
app = frame.MainApp(data_dir, config, plugins, trayicon, hidden, bindip, port)
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 3595, in __init__
self.frame = NicotineFrame(data_dir, config, plugins, trayicon, start_hidden, bindip, port)
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 273, in __init__
config
File "/usr/local/lib/python3.7/site-packages/pynicotine/pynicotine.py", line 130, in __init__
self.shares = Shares(self)
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 75, in __init__
self.CompressShares("normal")
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 201, in CompressShares
m.makeNetworkMessage(nozlib=0, rebuild=True)
File "/usr/local/lib/python3.7/site-packages/pynicotine/slskmessages.py", line 1709, in makeNetworkMessage
msg = msg + self.packObject(len(list(self.list.keys())))
File "/usr/local/lib/python3.7/_collections_abc.py", line 720, in __iter__
yield from self._mapping
File "/usr/local/lib/python3.7/shelve.py", line 95, in __iter__
for k in self.dict.keys():
SystemError: Negative size passed to PyBytes_FromStringAndSize

# Fixed code
def OnPrevious(self, widget):
    if len(self.data) > 1:
        _list = list(self.data.keys())

        if self.current not in _list:
            ix -= 1  # noqa: F821
        else:
            ix = _list.index(self.current)
            ix -= 1

            if ix < 0:
                ix = -1
            elif ix >= len(_list):
                ix = 0

        if ix is not None:
            self.current = _list[ix]

    if self.current is None:
        return

    self.Display(self.current)
# Buggy code
def OnNext(self, widget):
    if len(list(self.data.keys())) > 1:
        _list = list(self.data.keys())

        if self.current not in _list:
            ix += 1  # noqa: F821
        else:
            ix = _list.index(self.current)
            ix += 1

            if ix < 0:
                ix = -1
            elif ix >= len(_list):
                ix = 0

        if ix is not None:
            self.current = _list[ix]

    if self.current is None:
        return

    self.Display(self.current)


# Traceback (SystemError)
Thu 07:58 Nicotine+ supports a country code blocker. This requires a (GPL'ed) library called GeoIP. You can find it here: C library:       https://github.com/maxmind/geoip-api-c Python
bindings: https://github.com/maxmind/geoip-api-python (the python bindings require the C library)
Traceback (most recent call last):
File "/usr/local/bin/nicotine", line 255, in <module>
run()
File "/usr/local/bin/nicotine", line 231, in run
app = frame.MainApp(data_dir, config, plugins, trayicon, hidden, bindip, port)
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 3595, in __init__
self.frame = NicotineFrame(data_dir, config, plugins, trayicon, start_hidden, bindip, port)
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 273, in __init__
config
File "/usr/local/lib/python3.7/site-packages/pynicotine/pynicotine.py", line 130, in __init__
self.shares = Shares(self)
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 75, in __init__
self.CompressShares("normal")
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 201, in CompressShares
m.makeNetworkMessage(nozlib=0, rebuild=True)
File "/usr/local/lib/python3.7/site-packages/pynicotine/slskmessages.py", line 1709, in makeNetworkMessage
msg = msg + self.packObject(len(list(self.list.keys())))
File "/usr/local/lib/python3.7/_collections_abc.py", line 720, in __iter__
yield from self._mapping
File "/usr/local/lib/python3.7/shelve.py", line 95, in __iter__
for k in self.dict.keys():
SystemError: Negative size passed to PyBytes_FromStringAndSize

# Fixed code
def OnNext(self, widget):
    if len(self.data) > 1:
        _list = list(self.data.keys())

        if self.current not in _list:
            ix += 1  # noqa: F821
        else:
            ix = _list.index(self.current)
            ix += 1

            if ix < 0:
                ix = -1
            elif ix >= len(_list):
                ix = 0

        if ix is not None:
            self.current = _list[ix]

    if self.current is None:
        return

    self.Display(self.current)
# Buggy code
def makeNetworkMessage(self, nozlib=0, rebuild=False):
    # Elaborate hack, to save CPU
    # Store packed message contents in self.built, and use
    # instead of repacking it, unless rebuild is True
    if not rebuild and self.built is not None:
        return self.built
    msg = b""
    msg = msg + self.packObject(len(list(self.list.keys())))
    for key, value in self.list.items():
        msg = msg + self.packObject(key.replace(os.sep, "\\")) + value
    if not nozlib:
        self.built = zlib.compress(msg)
    else:
        self.built = msg
    return self.built


# Traceback (SystemError)
Thu 07:58 Nicotine+ supports a country code blocker. This requires a (GPL'ed) library called GeoIP. You can find it here: C library:       https://github.com/maxmind/geoip-api-c Python
bindings: https://github.com/maxmind/geoip-api-python (the python bindings require the C library)
Traceback (most recent call last):
File "/usr/local/bin/nicotine", line 255, in <module>
run()
File "/usr/local/bin/nicotine", line 231, in run
app = frame.MainApp(data_dir, config, plugins, trayicon, hidden, bindip, port)
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 3595, in __init__
self.frame = NicotineFrame(data_dir, config, plugins, trayicon, start_hidden, bindip, port)
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 273, in __init__
config
File "/usr/local/lib/python3.7/site-packages/pynicotine/pynicotine.py", line 130, in __init__
self.shares = Shares(self)
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 75, in __init__
self.CompressShares("normal")
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 201, in CompressShares
m.makeNetworkMessage(nozlib=0, rebuild=True)
File "/usr/local/lib/python3.7/site-packages/pynicotine/slskmessages.py", line 1709, in makeNetworkMessage
msg = msg + self.packObject(len(list(self.list.keys())))
File "/usr/local/lib/python3.7/_collections_abc.py", line 720, in __iter__
yield from self._mapping
File "/usr/local/lib/python3.7/shelve.py", line 95, in __iter__
for k in self.dict.keys():
SystemError: Negative size passed to PyBytes_FromStringAndSize

# Fixed code
def makeNetworkMessage(self, nozlib=0, rebuild=False):
    # Elaborate hack, to save CPU
    # Store packed message contents in self.built, and use
    # instead of repacking it, unless rebuild is True
    if not rebuild and self.built is not None:
        return self.built
    msg = b""
    msg = msg + self.packObject(len(self.list))
    for key, value in self.list.items():
        msg = msg + self.packObject(key.replace(os.sep, "\\")) + value
    if not nozlib:
        self.built = zlib.compress(msg)
    else:
        self.built = msg
    return self.built
# Buggy code
def masscan_post_http(self, script):
    header = re.search(
        re.escape("\nServer:") + "[ \\\t]*([^\\\r\\\n]+)\\\r?(?:\\\n|$)",
        script["masscan"]["raw"],
    )
    if header is None:
        return
    header = header.groups()[0]
    self._curport.setdefault("scripts", []).append(
        {
            "id": "http-server-header",
            "output": utils.nmap_encode_data(header),
            "masscan": {
                "raw": self._to_binary(header),
            },
        }
    )
    self._curport["service_product"] = utils.nmap_encode_data(header)


# Traceback (UnicodeDecodeError)
user@workstation:~/masscan/bin$ ivre nmap2db --archive --c MASSCAN-BANNER -s SCANNER BANNER.xml
WARNING:ivre:Exception (file 'BANNER.xml')
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/ivre/tools/scan2db.py", line 122, in main
merge=args.merge, masscan_probes=args.masscan_probes,
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 362, in store_scan
return store_scan_function(fname, filehash=scanid, **kargs)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 383, in store_scan_xml
parser.parse(utils.open_file(fname))
File "/usr/lib/python2.7/xml/sax/expatreader.py", line 107, in parse
xmlreader.IncrementalParser.parse(self, source)
File "/usr/lib/python2.7/xml/sax/xmlreader.py", line 123, in parse
self.feed(buffer)
File "/usr/lib/python2.7/xml/sax/expatreader.py", line 210, in feed
self._parser.Parse(data, isFinal)
File "/usr/lib/python2.7/xml/sax/expatreader.py", line 304, in start_element
self._cont_handler.startElement(name, AttributesImpl(attrs))
File "/usr/local/lib/python2.7/dist-packages/ivre/xmlnmap.py", line 1109, in startElement
probe=probe,
File "/usr/local/lib/python2.7/dist-packages/ivre/utils.py", line 843, in get_nmap_svc_fp
_read_nmap_probes()
File "/usr/local/lib/python2.7/dist-packages/ivre/utils.py", line 832, in _read_nmap_probes
parse_line(line[:-1])
File "/usr/local/lib/python2.7/dist-packages/ivre/utils.py", line 825, in parse_line
value = value.decode()
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2: ordinal not in range(128)
0 results imported.

# Fixed code
def masscan_post_http(self, script):
    header = re.search(
        re.escape(b"\nServer:") + b"[ \\\t]*([^\\\r\\\n]+)\\\r?(?:\\\n|$)",
        script["masscan"]["raw"],
    )
    if header is None:
        return
    header = header.groups()[0]
    self._curport.setdefault("scripts", []).append(
        {
            "id": "http-server-header",
            "output": utils.nmap_encode_data(header),
            "masscan": {
                "raw": self._to_binary(header),
            },
        }
    )
    self._curport["service_product"] = utils.nmap_encode_data(header)
# Buggy code
def feed_all(self, masterid):
    for scanid in self.get_scans():
        self.feed(masterid, scanid)


# Traceback (TypeError)
root@ivreclient:~# ivre runscansagentdb --daemon
Traceback (most recent call last):
File "/usr/local/bin/ivre", line 78, in <module>
main()
File "/usr/local/bin/ivre", line 51, in main
tools.get_command(possible_commands[0])()
File "/usr/local/lib/python2.7/dist-packages/ivre/tools/runscansagentdb.py", line 231, in main
ivre.db.db.agent.feed_all(masterid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1351, in feed_all
self.feed(masterid, scanid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1354, in feed
scan = self.lock_scan(scanid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1486, in lock_scan
scan = self._lock_scan(scanid, None, lockid.bytes)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/mongo.py", line 3372, in _lock_scan
if "target_info" not in scan:
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def feed_all(self, masterid):
    for scanid in self.get_scans():
        try:
            self.feed(masterid, scanid)
        except LockError:
            utils.LOGGER.error(
                "Lock error - is another daemon process running?",
                exc_info=True,
            )
# Buggy code
def feed(self, masterid, scanid):
    scan = self.lock_scan(scanid)
    if scan is None:
        raise StandardError("Could not acquire lock for scan %s" % scanid)
    # TODO: handle "onhold" targets
    target = self.get_scan_target(scanid)
    try:
        for agentid in scan["agents"]:
            if self.get_agent(agentid)["master"] == masterid:
                for _ in range(self.may_receive(agentid)):
                    self.add_target(agentid, scanid, next(target))
    except StopIteration:
        # This scan is over, let's free its agents
        for agentid in scan["agents"]:
            self.unassign_agent(agentid)
    self.update_scan_target(scanid, target)
    self.unlock_scan(scan)


# Traceback (TypeError)
root@ivreclient:~# ivre runscansagentdb --daemon
Traceback (most recent call last):
File "/usr/local/bin/ivre", line 78, in <module>
main()
File "/usr/local/bin/ivre", line 51, in main
tools.get_command(possible_commands[0])()
File "/usr/local/lib/python2.7/dist-packages/ivre/tools/runscansagentdb.py", line 231, in main
ivre.db.db.agent.feed_all(masterid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1351, in feed_all
self.feed(masterid, scanid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1354, in feed
scan = self.lock_scan(scanid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1486, in lock_scan
scan = self._lock_scan(scanid, None, lockid.bytes)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/mongo.py", line 3372, in _lock_scan
if "target_info" not in scan:
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def feed(self, masterid, scanid):
    scan = self.lock_scan(scanid)
    # TODO: handle "onhold" targets
    target = self.get_scan_target(scanid)
    try:
        for agentid in scan["agents"]:
            if self.get_agent(agentid)["master"] == masterid:
                for _ in range(self.may_receive(agentid)):
                    self.add_target(agentid, scanid, next(target))
    except StopIteration:
        # This scan is over, let's free its agents
        for agentid in scan["agents"]:
            self.unassign_agent(agentid)
    self.update_scan_target(scanid, target)
    self.unlock_scan(scan)
# Buggy code
def lock_scan(self, scanid):
    lockid = uuid.uuid1()
    scan = self._lock_scan(scanid, None, lockid.bytes)
    if scan["lock"] is not None:
        # This might be a bug in uuid module, Python 2 only
        ##  File "/opt/python/2.6.9/lib/python2.6/uuid.py", line 145, in __init__
        ##    int = long(('%02x'*16) % tuple(map(ord, bytes)), 16)
        # scan['lock'] = uuid.UUID(bytes=scan['lock'])
        scan["lock"] = uuid.UUID(hex=utils.encode_hex(scan["lock"]).decode())
    if scan["lock"] == lockid:
        return scan


# Traceback (TypeError)
root@ivreclient:~# ivre runscansagentdb --daemon
Traceback (most recent call last):
File "/usr/local/bin/ivre", line 78, in <module>
main()
File "/usr/local/bin/ivre", line 51, in main
tools.get_command(possible_commands[0])()
File "/usr/local/lib/python2.7/dist-packages/ivre/tools/runscansagentdb.py", line 231, in main
ivre.db.db.agent.feed_all(masterid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1351, in feed_all
self.feed(masterid, scanid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1354, in feed
scan = self.lock_scan(scanid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1486, in lock_scan
scan = self._lock_scan(scanid, None, lockid.bytes)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/mongo.py", line 3372, in _lock_scan
if "target_info" not in scan:
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def lock_scan(self, scanid):
    """Acquire lock for scanid. Returns the new scan object on success,
    and raises a LockError on failure.

    """
    lockid = uuid.uuid1()
    scan = self._lock_scan(scanid, None, lockid.bytes)
    if scan["lock"] is not None:
        # This might be a bug in uuid module, Python 2 only
        ##  File "/opt/python/2.6.9/lib/python2.6/uuid.py", line 145, in __init__
        ##    int = long(('%02x'*16) % tuple(map(ord, bytes)), 16)
        # scan['lock'] = uuid.UUID(bytes=scan['lock'])
        scan["lock"] = uuid.UUID(hex=utils.encode_hex(scan["lock"]).decode())
    if scan["lock"] == lockid:
        return scan
# Buggy code
def unlock_scan(self, scan):
    if scan.get("lock") is None:
        raise ValueError("Scan is not locked")
    scan = self._lock_scan(scan["_id"], scan["lock"].bytes, None)
    return scan["lock"] is None


# Traceback (TypeError)
root@ivreclient:~# ivre runscansagentdb --daemon
Traceback (most recent call last):
File "/usr/local/bin/ivre", line 78, in <module>
main()
File "/usr/local/bin/ivre", line 51, in main
tools.get_command(possible_commands[0])()
File "/usr/local/lib/python2.7/dist-packages/ivre/tools/runscansagentdb.py", line 231, in main
ivre.db.db.agent.feed_all(masterid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1351, in feed_all
self.feed(masterid, scanid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1354, in feed
scan = self.lock_scan(scanid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1486, in lock_scan
scan = self._lock_scan(scanid, None, lockid.bytes)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/mongo.py", line 3372, in _lock_scan
if "target_info" not in scan:
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def unlock_scan(self, scan):
    """Release lock for scanid. Returns True on success, and raises a
    LockError on failure.

    """
    if scan.get("lock") is None:
        raise LockError("Cannot release lock for %r: scan is not locked" % scan["_id"])
    scan = self._lock_scan(scan["_id"], scan["lock"].bytes, None)
    return scan["lock"] is None
# Buggy code
def display_scan(scan, verbose=True):
    scan["target"] = ivre.db.db.agent.get_scan_target(scan["_id"])
    print("scan:")
    if verbose:
        print("  - id: %s" % scan["_id"])
    print("  - categories:")
    for category in scan["target"].target.infos["categories"]:
        print("    - %s" % category)
    print("  - targets added: %d" % scan["target"].nextcount)
    print("  - results fetched: %d" % scan["results"])
    print("  - total targets to add: %d" % scan["target"].target.maxnbr)
    print("  - available targets: %d" % scan["target"].target.targetscount)
    if scan["target"].nextcount == scan["target"].target.maxnbr:
        print("    - all targets have been added")
    if scan["results"] == scan["target"].target.maxnbr:
        print("    - all results have been retrieved")
    if verbose:
        print("  - internal state: %r" % (scan["target"].getstate(),))
    print("  - agents:")
    for agent in scan["agents"]:
        print("    - %s" % agent)


# Traceback (TypeError)
root@ivreclient:~# ivre runscansagentdb --daemon
Traceback (most recent call last):
File "/usr/local/bin/ivre", line 78, in <module>
main()
File "/usr/local/bin/ivre", line 51, in main
tools.get_command(possible_commands[0])()
File "/usr/local/lib/python2.7/dist-packages/ivre/tools/runscansagentdb.py", line 231, in main
ivre.db.db.agent.feed_all(masterid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1351, in feed_all
self.feed(masterid, scanid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1354, in feed
scan = self.lock_scan(scanid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1486, in lock_scan
scan = self._lock_scan(scanid, None, lockid.bytes)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/mongo.py", line 3372, in _lock_scan
if "target_info" not in scan:
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def display_scan(scan, verbose=True):
    scan["target"] = ivre.db.db.agent.get_scan_target(scan["_id"])
    print("scan:")
    if verbose:
        print("  - id: %s" % scan["_id"])
    print("  - categories:")
    for category in scan["target"].target.infos["categories"]:
        print("    - %s" % category)
    print("  - targets added: %d" % scan["target"].nextcount)
    print("  - results fetched: %d" % scan["results"])
    print("  - total targets to add: %d" % scan["target"].target.maxnbr)
    print("  - available targets: %d" % scan["target"].target.targetscount)
    if scan["target"].nextcount == scan["target"].target.maxnbr:
        print("    - all targets have been added")
    if scan["results"] == scan["target"].target.maxnbr:
        print("    - all results have been retrieved")
    if verbose:
        print("  - internal state: %r" % (scan["target"].getstate(),))
    if scan.get("lock") is not None:
        print("  - locked", end="")
        if scan.get("pid") is not None:
            print(" (by %d)" % scan["pid"])
        else:
            print()
    print("  - agents:")
    for agent in scan["agents"]:
        print("    - %s" % agent)
# Buggy code
def terminate(signum, _):
    global WANT_DOWN
    print("SHUTDOWN: got signal %d, will halt after current task." % signum)
    WANT_DOWN = True


# Traceback (TypeError)
root@ivreclient:~# ivre runscansagentdb --daemon
Traceback (most recent call last):
File "/usr/local/bin/ivre", line 78, in <module>
main()
File "/usr/local/bin/ivre", line 51, in main
tools.get_command(possible_commands[0])()
File "/usr/local/lib/python2.7/dist-packages/ivre/tools/runscansagentdb.py", line 231, in main
ivre.db.db.agent.feed_all(masterid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1351, in feed_all
self.feed(masterid, scanid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1354, in feed
scan = self.lock_scan(scanid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1486, in lock_scan
scan = self._lock_scan(scanid, None, lockid.bytes)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/mongo.py", line 3372, in _lock_scan
if "target_info" not in scan:
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def terminate(signum, _):
    global WANT_DOWN
    ivre.utils.LOGGER.info(
        "shutdown: got signal %d, will halt after current task.",
        signum,
    )
    WANT_DOWN = True
# Buggy code
def terminate_now(signum, _):
    print("SHUTDOWN: got signal %d, halting now." % signum)
    exit()


# Traceback (TypeError)
root@ivreclient:~# ivre runscansagentdb --daemon
Traceback (most recent call last):
File "/usr/local/bin/ivre", line 78, in <module>
main()
File "/usr/local/bin/ivre", line 51, in main
tools.get_command(possible_commands[0])()
File "/usr/local/lib/python2.7/dist-packages/ivre/tools/runscansagentdb.py", line 231, in main
ivre.db.db.agent.feed_all(masterid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1351, in feed_all
self.feed(masterid, scanid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1354, in feed
scan = self.lock_scan(scanid)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/__init__.py", line 1486, in lock_scan
scan = self._lock_scan(scanid, None, lockid.bytes)
File "/usr/local/lib/python2.7/dist-packages/ivre/db/mongo.py", line 3372, in _lock_scan
if "target_info" not in scan:
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def terminate_now(signum, _):
    ivre.utils.LOGGER.info("shutdown: got signal %d, halting now.", signum)
    exit()
# Buggy code
def _eventlet_sendfile(fdout, fdin, offset, nbytes):
    while True:
        try:
            return os.sendfile(fdout, fdin, offset, nbytes)
        except OSError as e:
            if e.args[0] == errno.EAGAIN:
                trampoline(fdout, write=True)
            else:
                raise


# Traceback (RecursionError)
Traceback (most recent call last):
File "/usr/local/share/virtualenv/pywb/lib/python3.6/site-packages/gunicorn/workers/base_async.py", line 111, in handle_request
resp.write_file(respiter)
File "/usr/local/share/virtualenv/pywb/lib/python3.6/site-packages/gunicorn/http/wsgi.py", line 392, in write_file
if not self.sendfile(respiter):
File "/usr/local/share/virtualenv/pywb/lib/python3.6/site-packages/gunicorn/http/wsgi.py", line 382, in sendfile
sent += os.sendfile(sockno, fileno, offset + sent, count)
File "/usr/local/share/virtualenv/pywb/lib/python3.6/site-packages/gunicorn/workers/ggevent.py", line 37, in _gevent_sendfile
return os.sendfile(fdout, fdin, offset, nbytes)
File "/usr/local/share/virtualenv/pywb/lib/python3.6/site-packages/gunicorn/workers/ggevent.py", line 37, in _gevent_sendfile
return os.sendfile(fdout, fdin, offset, nbytes)
File "/usr/local/share/virtualenv/pywb/lib/python3.6/site-packages/gunicorn/workers/ggevent.py", line 37, in _gevent_sendfile
return os.sendfile(fdout, fdin, offset, nbytes)
[Previous line repeated 923 more times]
RecursionError: maximum recursion depth exceeded

# Fixed code
def _eventlet_sendfile(fdout, fdin, offset, nbytes, _os_sendfile=os.sendfile):
    while True:
        try:
            return _os_sendfile(fdout, fdin, offset, nbytes)
        except OSError as e:
            if e.args[0] == errno.EAGAIN:
                trampoline(fdout, write=True)
            else:
                raise
# Buggy code
def _gevent_sendfile(fdout, fdin, offset, nbytes):
    while True:
        try:
            return os.sendfile(fdout, fdin, offset, nbytes)
        except OSError as e:
            if e.args[0] == errno.EAGAIN:
                socket.wait_write(fdout)
            else:
                raise


# Traceback (RecursionError)
Traceback (most recent call last):
File "/usr/local/share/virtualenv/pywb/lib/python3.6/site-packages/gunicorn/workers/base_async.py", line 111, in handle_request
resp.write_file(respiter)
File "/usr/local/share/virtualenv/pywb/lib/python3.6/site-packages/gunicorn/http/wsgi.py", line 392, in write_file
if not self.sendfile(respiter):
File "/usr/local/share/virtualenv/pywb/lib/python3.6/site-packages/gunicorn/http/wsgi.py", line 382, in sendfile
sent += os.sendfile(sockno, fileno, offset + sent, count)
File "/usr/local/share/virtualenv/pywb/lib/python3.6/site-packages/gunicorn/workers/ggevent.py", line 37, in _gevent_sendfile
return os.sendfile(fdout, fdin, offset, nbytes)
File "/usr/local/share/virtualenv/pywb/lib/python3.6/site-packages/gunicorn/workers/ggevent.py", line 37, in _gevent_sendfile
return os.sendfile(fdout, fdin, offset, nbytes)
File "/usr/local/share/virtualenv/pywb/lib/python3.6/site-packages/gunicorn/workers/ggevent.py", line 37, in _gevent_sendfile
return os.sendfile(fdout, fdin, offset, nbytes)
[Previous line repeated 923 more times]
RecursionError: maximum recursion depth exceeded

# Fixed code
def _gevent_sendfile(fdout, fdin, offset, nbytes, _os_sendfile=os.sendfile):
    while True:
        try:
            return _os_sendfile(fdout, fdin, offset, nbytes)
        except OSError as e:
            if e.args[0] == errno.EAGAIN:
                socket.wait_write(fdout)
            else:
                raise
# Buggy code
def _get_user(self, environ):
    user = None
    http_auth = environ.get("HTTP_AUTHORIZATION")
    if http_auth and http_auth.startswith("Basic"):
        auth = http_auth.split(" ", 1)
        if len(auth) == 2:
            try:
                # b64decode doesn't accept unicode in Python < 3.3
                # so we need to convert it to a byte string
                auth = base64.b64decode(auth[1].strip().encode("utf-8"))
                if PY3:  # b64decode returns a byte string in Python 3
                    auth = auth.decode("utf-8")
                auth = auth.split(":", 1)
            except TypeError as exc:
                self.debug("Couldn't get username: %s", exc)
                return user
            except binascii.Error as exc:
                self.debug("Couldn't get username: %s", exc)
                return user
            if len(auth) == 2:
                user = auth[0]
    return user


# Traceback (UnicodeDecodeError)
[2018-01-15 18:23:06 +0000] [15] [ERROR] Error handling request
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/glogging.py", line 269, in
'u': self._get_user(environ) or '-',
File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/glogging.py", line 446, in
auth = auth.decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 0: invalid start byte

# Fixed code
def _get_user(self, environ):
    user = None
    http_auth = environ.get("HTTP_AUTHORIZATION")
    if http_auth and http_auth.startswith("Basic"):
        auth = http_auth.split(" ", 1)
        if len(auth) == 2:
            try:
                # b64decode doesn't accept unicode in Python < 3.3
                # so we need to convert it to a byte string
                auth = base64.b64decode(auth[1].strip().encode("utf-8"))
                if PY3:  # b64decode returns a byte string in Python 3
                    auth = auth.decode("utf-8")
                auth = auth.split(":", 1)
            except (TypeError, binascii.Error, UnicodeDecodeError) as exc:
                self.debug("Couldn't get username: %s", exc)
                return user
            if len(auth) == 2:
                user = auth[0]
    return user
# Buggy code
def validate(self):
    """Validate pidfile and make it stale if needed"""
    if not self.fname:
        return
    try:
        with open(self.fname, "r") as f:
            try:
                wpid = int(f.read())
            except ValueError:
                return

            try:
                os.kill(wpid, 0)
                return wpid
            except OSError as e:
                if e.args[0] == errno.ESRCH:
                    return
                raise
    except IOError as e:
        if e.args[0] == errno.ENOENT:
            return
        raise


# Traceback (OSError)
Traceback (most recent call last):
File "/opt/python2.7/bin/gunicorn", line 11, in <module>
sys.exit(run())
File "/opt/python2.7/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 74, in run
WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run()
File "/opt/python2.7/lib/python2.7/site-packages/gunicorn/app/base.py", line 189, in run
super(Application, self).run()
File "/opt/python2.7/lib/python2.7/site-packages/gunicorn/app/base.py", line 72, in run
Arbiter(self).run()
File "/opt/python2.7/lib/python2.7/site-packages/gunicorn/arbiter.py", line 171, in run
self.start()
File "/opt/python2.7/lib/python2.7/site-packages/gunicorn/arbiter.py", line 125, in start
self.pidfile.create(self.pid)
File "/opt/python2.7/lib/python2.7/site-packages/gunicorn/pidfile.py", line 23, in create
oldpid = self.validate()
File "/opt/python2.7/lib/python2.7/site-packages/gunicorn/pidfile.py", line 75, in validate
os.kill(wpid, 0)
OSError: [Errno 1] Operation not permitted

# Fixed code
def validate(self):
    """Validate pidfile and make it stale if needed"""
    if not self.fname:
        return
    try:
        with open(self.fname, "r") as f:
            try:
                wpid = int(f.read())
            except ValueError:
                return

            try:
                os.kill(wpid, 0)
                return wpid
            except OSError as e:
                if e.args[0] == errno.EPERM:
                    return wpid
                if e.args[0] == errno.ESRCH:
                    return
                raise
    except IOError as e:
        if e.args[0] == errno.ENOENT:
            return
        raise
# Buggy code
def accept(self, listener):
    try:
        client, addr = listener.accept()
        # initialize the connection object
        conn = TConn(self.cfg, listener, client, addr)
        self.nr_conns += 1
        # enqueue the job
        self.enqueue_req(conn)
    except socket.error as e:
        if e.args[0] not in (errno.EAGAIN, errno.ECONNABORTED, errno.EWOULDBLOCK):
            raise


# Traceback (BrokenPipeError)
[2014-11-17 04:18:49 -0500] [13520] [ERROR] Error handling request
Traceback (most recent call last):
File "/usr/local/lib/python3.4/site-packages/gunicorn/workers/async.py", line 108, in handle_request
resp.write(item)
File "/usr/local/lib/python3.4/site-packages/gunicorn/http/wsgi.py", line 344, in write
util.write(self.sock, arg, self.chunked)
File "/usr/local/lib/python3.4/site-packages/gunicorn/util.py", line 301, in write
sock.sendall(data)
File "/usr/local/lib/python3.4/site-packages/eventlet/greenio.py", line 375, in sendall
tail = self.send(data, flags)
File "/usr/local/lib/python3.4/site-packages/eventlet/greenio.py", line 358, in send
total_sent += fd.send(data[total_sent:], flags)
File "/usr/local/lib/python3.4/site-packages/eventlet/greenio.py", line 351, in send
return fd.send(data, flags)
BrokenPipeError: [Errno 32] Broken pipe

# Fixed code
def accept(self, listener):
    try:
        client, addr = listener.accept()
        # initialize the connection object
        conn = TConn(self.cfg, listener, client, addr)
        self.nr_conns += 1
        # enqueue the job
        self.enqueue_req(conn)
    except EnvironmentError as e:
        if e.errno not in (errno.EAGAIN, errno.ECONNABORTED, errno.EWOULDBLOCK):
            raise