forked from gregoriorobles/ptavi-pfinal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy_registrar.py
272 lines (246 loc) · 11.1 KB
/
proxy_registrar.py
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""Programa para un servidor proxy/registrar."""
import sys
from xml.sax import make_parser
from xml.sax.handler import ContentHandler
import socketserver
import time
import json
from uaclient import log, password
import random
import socket
class PrHandler(ContentHandler):
"""Class Handler."""
def __init__(self):
"""Inicializa los diccionarios."""
self.diccionario = {}
self.dicc_ua1xml = {'server': ['name', 'ip', 'puerto'],
'database': ['path', 'passwdpath'],
'log': ['path']}
def startElement(self, name, attrs):
"""Crea el diccionario con los valores del fichero xml."""
diccionario = {}
if name in self.dicc_ua1xml:
for atributo in self.dicc_ua1xml[name]:
self.diccionario[name+'_'+atributo] = attrs.get(atributo, '')
def get_tags(self):
"""Devuelve el diccionario creado."""
return self.diccionario
class SIPRegisterHandler(socketserver.DatagramRequestHandler):
"""Inicializo los diccionarios de usuarios, registrados y nonce."""
dicc_reg = {}
dicc_passw = {}
nonce = {}
def json2password(self):
"""Descargo fichero json en el diccionario."""
try:
with open(CONTRASEÑA, 'r') as jsonfile:
self.dicc_passw = json.load(jsonfile)
except FileNotFoundError:
pass
def json2register(self):
"""Descargo fichero json en el diccionario."""
try:
with open(REGISTRO, 'r') as jsonfile:
self.dicc_reg = json.load(jsonfile)
except FileNotFoundError:
pass
def register2json(self):
"""
Escribir diccionario.
En formato json en elfichero registered.json.
"""
with open(REGISTRO, 'w') as jsonfile:
json.dump(self.dicc_reg, jsonfile, indent=4)
def envio_client(self, ip, port, linea):
"""Envio mensajes al uaclient."""
self.wfile.write(bytes(linea, 'utf-8'))
print('mandamos al cliente: ', linea)
log_send = linea.replace("\r\n", " ")
log('Sent to ' + ip + ':' + str(port) + ': ' + log_send, LOG_PATH)
def envio_destino(self, ip, port, mensaje):
"""Envio los mensajes al uaserver."""
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as my_socket:
my_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
my_socket.connect((ip, port))
mens = mensaje.split('\r\n\r\n')
mens_proxy = (mens[0] + '\r\nVia: SIP/2.0/UDP ' + IP + ':' +
str(PORT_SERVER) + '\r\n\r\n' + mens[1])
print('mandamos al servidor: ', mens_proxy)
my_socket.send(bytes(mens_proxy, 'utf-8'))
mens_proxy = mens_proxy.replace("\r\n", " ")
log('Sent to ' + ip + ':' + str(port) + ': ' +
mens_proxy, LOG_PATH)
try:
data = my_socket.recv(1024).decode('utf-8')
print('recibimos del servidor: ', data)
except ConnectionRefusedError:
log("Error: No server listening at " + ip +
" port " + str(port), LOG_PATH)
recb = data.split()
env_proxy = ''
try:
if recb[7] == '200':
recb_proxy = data.split('\r\n\r\n')
env_proxy = (recb_proxy[0] + '\r\n\r\n' + recb_proxy[1] +
'\r\n\r\n' + recb_proxy[2] +
'\r\nVia: SIP/2.0/UDP ' + IP + ':' +
str(PORT_SERVER) + '\r\n\r\n' + recb_proxy[3])
except IndexError:
env_proxy = data
if env_proxy != '':
log_send = env_proxy.replace("\r\n", " ")
log('Received from ' + ip + ':' +
str(port) + ': ' + log_send, LOG_PATH)
self.envio_client(ip, port, env_proxy)
def user_not_found(self):
"""Mensaje de usuario no encontrado."""
linea_send = 'SIP/2.0 404 User Not Found\r\n\r\n'
log_send = linea_send.replace("\r\n", " ")
log('Error: ' + log_send, LOG_PATH)
self.wfile.write(bytes(linea_send, 'utf-8'))
def handle(self):
"""Escribe dirección y puerto del cliente."""
ip_client = str(self.client_address[0])
port_client = str(self.client_address[1])
self.json2register()
self.json2password()
while 1:
# Leyendo línea a línea lo que nos envía el cliente
line = self.rfile.read()
# Si no hay más líneas salimos del bucle infinito
if not line:
break
linea = line.decode('utf-8')
print("El cliente nos manda\r\n", linea)
line = linea.split()
if line[0] == 'REGISTER' and len(line) == 5:
TimeExp = time.time() + int(line[4])
now = time.time()
user = line[1].split(':')[1]
linea_recb = linea.replace("\r\n", " ")
log('Received from ' + ip_client + ':' +
port_client + ': ' + linea_recb, LOG_PATH)
if user in self.dicc_passw.keys():
if user in self.dicc_reg.keys():
port = line[1].split(':')[2]
if line[4] == '0':
del self.dicc_reg[user]
linea_send = "SIP/2.0 200 OK\r\n\r\n"
else:
self.dicc_reg[user] = {'ip': ip_client,
'expires': TimeExp,
'puerto': port,
'registro': now}
linea_send = "SIP/2.0 200 OK\r\n\r\n"
else:
self.nonce[user] = str(random.randint(0, 100000000))
linea_send = ('SIP/2.0 401 Unauthorized\r\n' +
'WWW Authenticate: Digest ' +
'nonce="' + self.nonce[user] +
'"\r\n\r\n')
self.envio_client(ip_client, port_client, linea_send)
else:
self.user_not_found()
elif line[0] == 'REGISTER' and len(line) == 8:
TimeExp = time.time() + int(line[4])
now = time.time()
user = line[1].split(':')[1]
port = line[1].split(':')[2]
linea_recb = linea.replace("\r\n", " ")
log('Received from ' + ip_client + ':' +
port_client + ': ' + linea_recb, LOG_PATH)
pw = self.dicc_passw[user]['passwd']
nonce = password(pw, self.nonce[user])
nonce_recv = line[7].split('"')[1]
if nonce == nonce_recv:
if line[4] == '0':
linea_send = "SIP/2.0 200 OK\r\n\r\n"
else:
self.dicc_reg[user] = {'ip': ip_client,
'expires': TimeExp,
'puerto': port, 'registro': now}
linea_send = "SIP/2.0 200 OK\r\n\r\n"
else:
self.nonce[user] = str(random.randint(0, 100000000))
linea_send = ('SIP/2.0 401 Unauthorized\r\n' +
'WWW Authenticate: Digest ' +
'nonce="' + self.nonce[user] +
'"\r\n\r\n')
self.envio_client(ip_client, port_client, linea_send)
elif line[0] == 'INVITE':
linea_recb = linea.replace("\r\n", " ")
log('Received from ' + ip_client + ':' +
port_client + ': ' + linea_recb, LOG_PATH)
user = line[6].split('=')[1]
if user in self.dicc_reg.keys():
server = line[1].split(':')[1]
if server in self.dicc_reg.keys():
ip_destino = self.dicc_reg[server]['ip']
port_destino = int(self.dicc_reg[server]['puerto'])
self.envio_destino(ip_destino, port_destino, linea)
else:
self.user_not_found()
else:
self.user_not_found()
elif line[0] == 'ACK':
linea_recb = linea.replace("\r\n", " ")
log('Received from ' + ip_client + ':' +
port_client + ': ' + linea_recb, LOG_PATH)
server = line[1].split(':')[1]
if server in self.dicc_reg.keys():
ip_destino = self.dicc_reg[server]['ip']
port_destino = int(self.dicc_reg[server]['puerto'])
self.envio_destino(ip_destino, port_destino, linea)
else:
self.user_not_found()
elif line[0] == 'BYE':
linea_recb = linea.replace("\r\n", " ")
log('Received from ' + ip_client + ':' +
port_client + ': ' + linea_recb, LOG_PATH)
server = line[1].split(':')[1]
if server in self.dicc_reg.keys():
ip_destino = self.dicc_reg[server]['ip']
port_destino = int(self.dicc_reg[server]['puerto'])
self.envio_destino(ip_destino, port_destino, linea)
else:
self.user_not_found()
elif line[0] != ('REGISTER', 'INVITE', 'ACK', 'BYE'):
self.wfile.write(b"SIP/2.0 405 Method Not Allowed\r\n\r\n")
log("Error: SIP/2.0 405 Method Not Allowed", LOG_PATH)
print('metodo erroneo')
else:
self.wfile.write(b"SIP/2.0 400 Bad Request\r\n\r\n")
log("Error: SIP/2.0 400 Bad Request", LOG_PATH)
print('pregunta mal formulada')
self.register2json()
if __name__ == "__main__":
try:
CONFIG = sys.argv[1]
except (IndexError, ValueError):
sys.exit("Usage: python proxy_registrar.py config")
parser = make_parser()
pHandler = PrHandler()
parser.setContentHandler(pHandler)
try:
parser.parse(open(CONFIG))
except FileNotFoundError:
sys.exit("Usage: python proxy_registrar.py config")
CONFIGURACION = pHandler.get_tags()
if CONFIGURACION['server_ip'] == '':
IP = '127.0.0.1'
else:
IP = CONFIGURACION['server_ip']
PORT_SERVER = int(CONFIGURACION['server_puerto'])
PROXY = CONFIGURACION['server_name']
LOG_PATH = CONFIGURACION['log_path']
REGISTRO = CONFIGURACION['database_path']
CONTRASEÑA = CONFIGURACION['database_passwdpath']
serv = socketserver.UDPServer((IP, PORT_SERVER), SIPRegisterHandler)
print("Server " + PROXY + " listening at port " + str(PORT_SERVER))
log("Starting...", LOG_PATH)
try:
serv.serve_forever()
except KeyboardInterrupt:
log("Finishing.", LOG_PATH)