summaryrefslogtreecommitdiff
path: root/examples/py-flow-undetected-to-pcap/flow-undetected-to-pcap.py
blob: 961adc3cf0084366a76260800c1240a9ca1d9867 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/env python3

import os
import sys

sys.path.append(os.path.dirname(sys.argv[0]) + '/../../dependencies')
import nDPIsrvd
from nDPIsrvd import TermColor, nDPIsrvdSocket, PcapPacket

def onJsonLineRecvd(json_dict, current_flow, global_user_data):
    if current_flow is None:

        if 'packet_event_name' in json_dict and json_dict['packet_event_name'] == 'packet':
            fake_flow = Flow()
            fake_flow.pkt = PcapPacket()
            PcapPacket.handleJSON(json_dict, fake_flow)
            fake_flow.pkt.doDump()
            fake_flow.pkt.setSuffix('packet_undetected')
            fake_flow.pkt.fin()

        return True

    PcapPacket.handleJSON(json_dict, current_flow)

    if 'flow_event_name' in json_dict and PcapPacket.isInitialized(current_flow) and \
        (json_dict['flow_event_name'] == 'guessed' or json_dict['flow_event_name'] == 'not-detected'):

        current_flow.pcap_packet.doDump()
        if json_dict['flow_event_name'] == 'guessed':
            current_flow.pcap_packet.setSuffix('guessed')

            try:
                if current_flow.pcap_packet.fin() is True:
                    print('Guessed flow with id {}, dumped'.format(current_flow.flow_id))
            except RuntimeError as err:
                print('Guessed flow with id {} excepted: {}'.format(current_flow.flow_id, str(err)))

        else:
            current_flow.pcap_packet.setSuffix('undetected')

            try:
                if current_flow.pcap_packet.fin() is True:
                    print('Not-detected flow with id {}, dumped'.format(current_flow.flow_id))
            except RuntimeError as err:
                print('Not-detected flow with id {} excepted: {}'.format(current_flow.flow_id, str(err)))

    return True

if __name__ == '__main__':
    argparser = nDPIsrvd.defaultArgumentParser()
    args = argparser.parse_args()
    address = nDPIsrvd.validateAddress(args)

    sys.stderr.write('Recv buffer size: {}\n'.format(nDPIsrvd.NETWORK_BUFFER_MAX_SIZE))
    sys.stderr.write('Connecting to {} ..\n'.format(address[0]+':'+str(address[1]) if type(address) is tuple else address))

    nsock = nDPIsrvdSocket()
    nsock.connect(address)
    nsock.loop(onJsonLineRecvd, None)