summaryrefslogtreecommitdiff
blob: 4e4e54385c6561d1a6ed3153f186ac58e7a466df (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#!/bin/env python3
import argparse
import re

import socket
import _thread

class ClientState:
    CLIENT_IS_SENDING_DOWNSTREAM = 1
    CLIENT_IS_SENDING_UPSTREAM = 2
    CLIENT_IS_CONNECTING = 3
    CLIENT_IS_TERMINATING = 4

def client_main (source, params):
    pattern = re.compile(params.regex)
    state = ClientState.CLIENT_IS_CONNECTING
    t_connect = None
    f_connect = None
    current_target = None

    try:
        while True:
            if (state == ClientState.CLIENT_IS_SENDING_DOWNSTREAM):
                try:
                    in_data = b""

                    while True:
                        in_char = source.recv(1)
                        in_data = (in_data + in_char)

                        if (in_char == b"\n"):
                            break
                        elif (in_char == b''):
                            raise Exception("Disconnected client")

                    up_data = in_data.decode("UTF-8")
                    valid = 1
                except UnicodeDecodeError:
                    valid = 0

                if ((valid == 1) and pattern.match(up_data)):
                    if (t_connect != None):
                        if (params.replacement != None):
                            print("Transformed \"" + up_data + "\"")
                            up_data = re.sub(
                                pattern,
                                params.replacement,
                                up_data
                            )
                            print("into \"" + up_data + "\"")
                            t_connect.sendall(up_data.encode("UTF-8"))
                        else:
                            t_connect.sendall(in_data)
                        current_target = 't'
                        state = ClientState.CLIENT_IS_SENDING_UPSTREAM
                        print("[Matched] Sending upstream...")
                    else:
                        source.send(b"!P \n")
                        print("Matched")
                else:
                    if (f_connect != None):
                        f_connect.sendall(in_data)
                        current_target = 'f'
                        state = ClientState.CLIENT_IS_SENDING_UPSTREAM
                        print("[No match] Sending upstream...")
                    else:
                        source.sendall(b"!P \n")
                        print("Did not match")
            elif (state == ClientState.CLIENT_IS_SENDING_UPSTREAM):
                matched = 0
                c = b"\0"

                while (c != b"\n"):
                    if (current_target == 't'):
                        c = t_connect.recv(1)
                    else:
                        c = f_connect.recv(1)

                    source.send(c)

                    if ((matched == 0) and (c == b"!")):
                        matched = 1
                    elif ((matched == 1) and ((c == b"P") or (c == b"N"))):
                        matched = 2
                    elif ((matched == 2) and (c == b" ")):
                        print("Sending downstream...")
                        state = ClientState.CLIENT_IS_SENDING_DOWNSTREAM
                    else:
                        matched = -1

            elif (state == ClientState.CLIENT_IS_CONNECTING):
                print("Connecting to downstream...")
                if (params.destination_true != None):
                    t_connect = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
                    t_connect.connect(params.destination_true)

                if (params.destination_false != None):
                    f_connect = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
                    f_connect.connect(params.destination_false)

                print("Sending downstream...")
                state = ClientState.CLIENT_IS_SENDING_DOWNSTREAM
            else:
                break
    except:
        print("Closing")
        source.close()

        if (t_connect != None):
            t_connect.close()

        if (f_connect != None):
            f_connect.close()

################################################################################
## ARGUMENTS HANDLING ##########################################################
################################################################################

parser = argparse.ArgumentParser(
    description = (
        "Generates a list of instructions to construct the Structural Level."
    )
)

parser.add_argument(
    '-s',
    '--socket-name',
    type = str,
    required = True,
    help = 'Name of the UNIX socket for this filter.'
)

parser.add_argument(
    '-t',
    '--destination-true',
    type = str,
    help = 'UNIX socket this filter sends to when a match is found.',
)

parser.add_argument(
    '-f',
    '--destination-false',
    type = str,
    help = 'UNIX socket this filter sends to when a match is found.',
)

parser.add_argument(
    '-r',
    '--regex',
    type = str,
    required = True,
    help = 'The regex to test the message against.',
)

parser.add_argument(
    '-x',
    '--replacement',
    type = str,
    required = False,
    help = 'The transformation regex to be applied',
)

args = parser.parse_args()

################################################################################
## MAIN ########################################################################
################################################################################
server_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

server_socket.bind(args.socket_name)
server_socket.listen(5)

while True:
    (client, client_address) = server_socket.accept()
    _thread.start_new_thread(client_main, (client, args))