'Uses TShark to check for a handshake.
Returns "True" if handshake is found, false otherwise.'

def has_handshake_tshark(self, target, capfile):

    if program_exists('tshark'):
        cmd = ['tshark', '-r', capfile, '-R', 'eapol', '-2', '-n']
        proc = Popen(cmd, stdout=PIPE, stderr=DN)
        proc.wait()
        lines = proc.communicate()[0].split('\n')
        clients = []
        for line in lines:
            if ((line.find('appears    to    have    been    cut    short') != (-1)) or (line.find('Running    as    user    "root"') != (-1)) or (line.strip() == '')):
                continue
            while line.startswith('    '):
                line = line[1:]
            while (line.find('        ') != (-1)):
                line = line.replace('        ', '    ')
            fields = line.split('    ')
            if (len(fields) < 5):
                continue
            src = fields[2].lower()
            dst = fields[4].lower()
            if ((src == target.bssid.lower()) and (clients.count(dst) == 0)):
                clients.append(dst)
            elif ((dst == target.bssid.lower()) and (clients.count(src) == 0)):
                clients.append(src)
        for client in clients:
            msg_num = 1
            for line in lines:
                if (line.find('appears    to    have    been    cut    short') != (-1)):
                    continue
                if (line.find('Running    as    user    "root"') != (-1)):
                    continue
                if (line.strip() == ''):
                    continue
                while (line[0] == '    '):
                    line = line[1:]
                while (line.find('        ') != (-1)):
                    line = line.replace('        ', '    ')
                fields = line.split('    ')
                if (len(fields) < 8):
                    continue
                elif (len(fields) == 8):
                    fields.append('(msg')
                    fields.append('3/4)')
                src = fields[2].lower()
                dst = fields[4].lower()
                if (len(fields) == 12):
                    msg = fields[9][0]
                else:
                    msg = fields[(-1)][0]
                if (((msg_num % 2) == 1) and ((src != target.bssid.lower()) or (dst != client))):
                    continue
                elif (((msg_num % 2) == 0) and ((dst != target.bssid.lower()) or (src != client))):
                    continue
                try:
                    if (int(msg) != msg_num):
                        continue
                except ValueError:
                    continue
                msg_num += 1
                if (msg_num >= 4):
                    return True
    return False
