def handle(self): """Funcion handle.""" ip_client = str(self.client_address[0]) port_client = str(self.client_address[1]) 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') linea_recb = linea.replace("\r\n", " ") log( 'Received from ' + IP_PROXY + ':' + str(PORT_PROXY) + ': ' + linea_recb, LOG_PATH) print("El cliente nos manda ", linea) line = linea.split() if line[0] == 'INVITE': print(line) self.rtp.append(line[10]) self.rtp.append(line[13]) mensaje = ('SIP/2.0 100 Trying\r\n\r\n' + 'SIP/2.0 180 Ringing\r\n\r\n' + 'SIP/2.0 200 OK\r\n' + 'Content-Type: application/sdp\r\n\r\n' + 'v=0\r\n' + 'o=' + ADRESS + ' ' + IP + '\r\n' + 's=misesion\r\n' + 'm=audio ' + str(PORT_AUDIO) + ' RTP' + '\r\n\r\n') self.enviar_proxy(mensaje, ip_client, port_client) elif line[0] == 'ACK': mensaje = rtp(self.rtp[0], self.rtp[1], AUDIO_PATH) log( 'Sent to ' + self.rtp[0] + ':' + str(self.rtp[1]) + ': ' + mensaje, LOG_PATH) elif line[0] == 'BYE': mensaje = 'SIP/2.0 200 OK\r\n\r\n' self.enviar_proxy(mensaje, ip_client, port_client) elif metodo != ('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')
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 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 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()
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): """Handle.""" while 1: log("Starting...", LOGFILE) line = self.rfile.read() print("THE PROXY SEND: " + line.decode('utf-8')) lista = line.decode('utf-8') METHOD = lista.split(" ")[0] if METHOD == 'INVITE': self.wfile.write(b"SIP/2.0 100 Trying \r\n\r\n") self.wfile.write(b"SIP/2.0 180 Ringing\r\n\r\n") self.wfile.write(b"SIP/2.0 200 OK \r\n\r\n") break log('Sent to ' + SERVER + ':' + PORT + ': ' + ADDRESS, LOGFILE) log('Received from: ', LOGFILE) if METHOD == 'ACK': aEjecutar = './mp32rtp -i' + SERVER + '-p 23032 < ' aEjecutar = AUDIOFILE print("Vamos a ejecutar", aEjecutar) os.system(aEjecutar) print("Enviamos cancion") log('Sent to ' + SERVER + ':' + PORT + ': ' + ADDRESS + aEjecutar) break if METHOD == 'BYE': self.wfile.write(b"SIP/2.0 200 OK\r\n\r\n") log("Sent to " + SERVER + ": " + PORT + ":" + ADDRESS, LOGFILE) break if METHOD != ('INVITE' or 'ACK' or 'BYE'): self.wfile.write(b"SIP/2.0 405 Method Not Allowed\r\n\r\n") log('Error: Method Not Allowed', LOGFILE) break else: self.wfile.write(b"SIP/2.0 400 BAD REQUEST\r\n\r\n") Log('Error: Bad Request', LOGFILE) break if not line: break
break if __name__ == "__main__": try: CONFIG = sys.argv[1] except (IndexError, ValueError): sys.exit("Usage: python3 uaserver.py config") parser = make_parser() uHandler = Ua1Handler() parser.setContentHandler(uHandler) parser.parse(open(CONFIG)) dato = uHandler.get_tags() print(dato) ADDRESS = dato['account_username'] PORT = dato['uaserver_puerto'] LOGFILE = dato['log_path'] IPPROXY = dato['regproxy_ip'] PORTPROXY = int(dato['regproxy_puerto']) SERVER = dato['uaserver_ip'] AUDIOPORT = int(dato['rtpaudio_puerto']) AUDIOFILE = dato['audio_path'] serv = socketserver.UDPServer((SERVER, int(PORT)), EchoHandler) print('Listening...') log("Starting...", LOGFILE) try: serv.serve_forever() except KeyboardInterrupt: log("Finishing...", LOGFILE)
def handle(self): """Handler for SIP management. Functionality: Receive and manage REGISTER petitions Keeping client information Ban clients with overtimed expiration """ # Registro de clientes almacenados en el fichero .json self.json2registered() # Comprobación de la caducidad de los registros self.expiration() # Procesado de mensaje lines = self.rfile.read() slices = lines.decode('utf-8').split() method = slices[0] print('Received:') print(lines.decode('utf-8')) # Manejo de los distintos mensajes (REGISTER, INVITE, BYE, ACK) if method == 'REGISTER' and len(slices) >= 6: # Registro por segunda vez # Escribiendo en el log to_write = 'Received from ' + self.client_address[0] + ':' + \ slices[1][-4:] + ': ' + \ lines.decode('utf-8').replace('\r\n', ' ') log(config_data, to_write) authorization = slices[5] # Comprobar contraseña f = open(config_data['database']['passwdpath'], 'r') for line in f.readlines(): if slices[1][4:-5] == line.split()[0][:-5]: passwd = line.split()[0][-4:] # Obtener el hash authenticate = hashlib.sha1() authenticate.update(bytes(passwd, 'utf-8')) authenticate.update(bytes(self.nonce[0], 'utf-8')) authenticate = authenticate.hexdigest() if authenticate == slices[7][10:-1]: self.wfile.write(b"SIP/2.0 200 OK\r\n\r\n") # Escribiendo en el log to_write = 'Sent to ' + self.client_address[0] + \ ':' + slices[1][-4:] + ': ' + 'SIP/2.0 200 OK ' log(config_data, to_write) # Registro del cliente slices = lines.decode('utf-8').split() t = int(slices[4].split('/')[0]) date = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(time.time())) gm = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(time.time()+t)) client = [slices[1][4:-5], {"address": self.client_address[0], "port":slices[1][-4:], "expires": gm, "register_date": date}] # Si Expires=0, dar de baja al clliente if slices[0] == 'REGISTER': empty = True reg = True for usr in self.data_list: empty = False if usr[0] == client[0]: if slices[4].split('/')[0] == '0': exp = client[1]["expires"] date = client[1]["register_date"] usr[1]["expires"] = exp usr[1]["register_date"] = date self.data_list.remove(client) print('Time for client ' + client[0] + ' intentionally expired. ' + 'Removed.') reg = False else: print('Client ' + client[0] + ' already registered. Updated.') exp = client[1]["expires"] date = client[1]["register_date"] usr[1]["expires"] = exp usr[1]["register_date"] = date reg = False if empty or reg: if slices[4].split('/')[0] != '0': self.data_list.append(client) print('(^)Client successfully registered') self.register2json() else: # Respuesta para contraseña incorrecta print('Inorrect password for user: '******'Sent to ' + self.client_address[0] + \ ':' + slices[1][-4:] + ': ' + \ 'SIP/2.0 400 Bad Request ' log(config_data, to_write) self.nonce.clear() elif method == 'REGISTER' and len(slices) < 6: # Registro por primera vez. Se requiere autorización # Escribiendo en el log to_write = 'Received from ' + self.client_address[0] + ':' + \ slices[1][-4:] + ': ' + \ lines.decode('utf-8').replace('\r\n', ' ') log(config_data, to_write) self.nonce.append(str(random.randint(00000000000000000000, 99999999999999999999))) self.wfile.write(bytes(('SIP/2.0 401 Unauthorized\r\n' + 'WWW-Authenticate: Digest nonce="' + self.nonce[0] + '"\r\n\r\n'), 'utf-8')) # Escribiendo en el log to_write = 'Sent to ' + self.client_address[0] + ':' + \ slices[1][-4:] + ': ' + 'SIP/2.0 401 Unauthorized ' + \ 'WWW-Authenticate: Digest nonce="' + self.nonce[0] + '" ' log(config_data, to_write) print('(^)Not successfully registered, authentication required') print() elif method == 'INVITE': # Comprobar que el que hace la petición está registrado registered = False for client in self.data_list: if client[0] == slices[6][2:]: self.d[client[0]] = client[1]["address"] self.p[client[0]] = client[1]["port"] # Escribiendo en el log to_write = 'Received from ' + self.d[client[0]] + ':' + \ self.p[client[0]] + ': ' + \ lines.decode('utf-8').replace('\r\n', ' ') log(config_data, to_write) registered = True if not registered: # Escribiendo en el log to_write = 'Error: INVITE attempt from ' + \ self.client_address[0] + ':' + \ str(self.client_address[1]) + ' without previous REGISTER' log(config_data, to_write) print(to_write) self.wfile.write(b"SIP/2.0 400 Bad Request\r\n\r\n") # Escribiendo en el log to_write = 'Sent to ' + self.client_address[0] + ': ' + \ str(self.client_address[1]) + ': SIP/2.0 400 Bad Request ' log(config_data, to_write) self.d.clear() self.p.clear() else: # Comprobar que al que le hacen el invite esta registrado resend = False for client in self.data_list: if client[0] == slices[1][4:]: resend = True # Reenvío de INVITE, recepción y reenvío de respuesta with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as my_socket: add = client[1]["address"] my_socket.connect((add, int(client[1]["port"]))) self.resend_ad[client[0]] = add self.resend_port[client[0]] = client[1]["port"] my_socket.send(bytes(lines.decode('utf-8'), 'utf-8')) print() print("Resending: (" + client[1]["address"] + "," + client[1]["port"] + ")") print(lines.decode('utf-8')) # Escribiendo en el log to_write = 'Sent to ' + self.resend_ad[client[0]] to_write += ':' + self.resend_port[client[0]] + \ ': ' + \ lines.decode('utf-8').replace('\r\n', ' ') log(config_data, to_write) # Recibir el 200 OK con el sdp response = my_socket.recv(1024).decode('utf-8') print('Received --', response) # Escribiendo en el log to_write = 'Received from ' + \ self.resend_ad[client[0]] + ':' + \ self.resend_port[client[0]] + ': ' + \ response.replace('\r\n', ' ') log(config_data, to_write) # Reenviar al cliente self.wfile.write(bytes(response, 'utf-8')) # Escribiendo en el log to_write = 'Sent to ' + self.d[slices[6][2:]] + \ ':' + self.p[slices[6][2:]] + ': ' + \ response.replace('\r\n', ' ') log(config_data, to_write) if not resend: print('User ' + slices[1][4:] + ' Not Found. Resending (' + self.d[slices[6][2:]] + ':' + self.p[slices[6][2:]] + '): SIP/2.0 404 User Not Found\r\n\r\n') self.wfile.write(b"SIP/2.0 404 User Not Found\r\n\r\n") # Escribiendo en el log to_write = 'Error: INVITE attempt from ' + \ self.d[slices[6][2:]] + ':' + self.p[slices[6][2:]] + \ ': User Not Found' log(config_data, to_write) self.d.clear() self.p.clear() elif method == 'ACK': # Respuesta al INVITE ack_slices = lines.decode('utf-8').split() for client in self.data_list: if client[0] != slices[1][4:]: d = client[1]["address"] p = client[1]["port"] # Escribiendo en el log to_write = 'Received from ' + d + ':' + p + \ ': ' + lines.decode('utf-8').replace('\r\n', ' ') log(config_data, to_write) # Reenviando ACK print("Resending: (" + self.resend_ad[slices[1][4:]] + "," + self.resend_port[slices[1][4:]] + ")") print(lines.decode('utf-8')) with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as my_socket: add = self.resend_ad[slices[1][4:]] port = self.resend_port[slices[1][4:]] my_socket.connect((add, int(port))) my_socket.send(bytes(lines.decode('utf-8'), 'utf-8')) # Escribiendo en el log to_write = 'Sent to ' + add + ':' + port + \ ': ' + lines.decode('utf-8').replace('\r\n', ' ') log(config_data, to_write) self.resend_ad.clear() self.resend_port.clear() self.d.clear() self.p.clear() elif method == 'BYE': # Escribiendo en el log to_write = 'Received from ' + self.client_address[0] + ':' + \ str(self.client_address[1]) + ': ' + \ lines.decode('utf-8').replace('\r\n', ' ') log(config_data, to_write) dest = slices[1][4:] resend = False # Reenviando BYE for client in self.data_list: if client[0] == dest: resend = True with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as my_socket: add = client[1]["address"] port = client[1]["port"] my_socket.connect((add, int(port))) my_socket.send(bytes(lines.decode('utf-8'), 'utf-8')) print() print("Resending: (" + add + "," + port + ")") print(lines.decode('utf-8')) # Escribiendo en el log to_write = 'Sent to ' + add + ':' + port + \ ': ' + lines.decode('utf-8').replace('\r\n', ' ') log(config_data, to_write) # Recibir el 200 OK response = my_socket.recv(1024).decode('utf-8') print('Received --', response) # Escribiendo en el log to_write = 'Received from ' + add + ':' + port + \ ': ' + response.replace('\r\n', ' ') log(config_data, to_write) # Reenviar al cliente self.wfile.write(bytes(response, 'utf-8')) print("Resending (" + self.client_address[0] + "," + str(self.client_address[1]) + "): " + response) # Escribiendo en el log to_write = 'Sent to ' + self.client_address[0] + \ ':' + str(self.client_address[1]) + \ ': ' + response.replace('\r\n', ' ') log(config_data, to_write) if not resend: self.wfile.write(b"SIP/2.0 404 User Not Found\r\n\r\n") # Escribiendo en el log to_write = 'Error: BYE attempt from ' + \ self.client_address[0] + ':' + \ str(self.client_address[1]) + ': User Not Found' log(config_data, to_write) to_write = 'Sent to ' + self.client_address[0] + ':' + \ str(self.client_address[1]) + \ ': SIP/2.0 404 User Not Found ' log(config_data, to_write) elif method not in ['REGISTER', 'INVITE', 'ACK', 'BYE']: self.wfile.write(b"SIP/2.0 405 Method Not Allowed\r\n\r\n") print('Method ' + method + ' not allowed.') # Escribiendo en el log to_write = 'Error: Method ' + method + ' not allowed.' log(config_data, to_write) to_write = 'Sent: SIP/2.0 405 Method Not Allowed ' log(config_data, to_write)
def handle(self): solicitud = self.rfile.read().decode("utf-8") forma = ("Via: SIP/2.0/UDP " + IP + ":" + str(PUERTO_SERVER) + "\r\n") peticion = solicitud + forma print("El cliente manda:\r\n" + peticion) ipcliente = str(self.client_address[0]) puertocliente = str(self.client_address[1]) metodo = solicitud.split()[0] user = solicitud.split()[1].split(":")[1] solicitud_log = solicitud.replace("\r\n", " ") log( "Received from" + ipcliente + ":" + puertocliente + ": " + solicitud_log, LOG_PATH) metodo = solicitud.split()[0] self.jsonapasswd() self.jsonaregistrar() if metodo == "REGISTER": print(solicitud) user = solicitud.split()[1].split(":")[1] userport = solicitud.split()[1].split(":")[2] expires = solicitud.split()[4] puertocliente = str(self.client_address[1]) ipcliente = str(self.client_address[0]) expires_time = int(expires) + time.time() act_time = time.time() if metodo == "REGISTER" and len( solicitud.split()) == 5: # Si es 5 es el primer register. if user not in self.registrar: self.nonce[user] = str(random.randint(0, 99999999)) LINE = ("SIP/2.0 401 Unauthorized\r\n" + 'WWW Authenticate: Digest nonce="' + self.nonce[user] + '"\r\n\r\n') print("Enviando al cliente: \r\n" + LINE) else: LINE = ("SIP/2.0 200 OK" + "\r\n\r\n") if expires == "0": log( 'Send: ' + user + ':' + userport + ': SIP/2.0 200 OK. Deleting.\r\n', LOG_PATH) del self.registrar[user] #deja de estar registrado self.wfile.write(bytes(LINE, "utf-8")) log("Sent to" + ipcliente + ":" + puertocliente + ": " + LINE, LOG_PATH) elif metodo == "REGISTER" and len(solicitud.split()) != 5: contrasena = self.dicc_password[user]["passwd"] variable = hashlib.md5() variable.update(bytes(contrasena, 'utf-8')) variable.update(bytes(self.nonce[user], 'utf-8')) nonce_recv = solicitud.split()[8].split('"')[1] if variable.hexdigest() == nonce_recv: print("contraseña correcta") LINE = ("SIP/2.0 200 OK" + "\r\n\r\n") self.registro(user, userport, expires) else: LINE = ("ERROR: Clave no valida") else: LINE = ("SIP/2.0 404 User not found" + "\r\n\r\n") self.wfile.write(bytes(LINE, 'utf-8')) log("sent to" + ipcliente + puertocliente + LINE, LOG_PATH) self.registrarajson() elif metodo == "INVITE": with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as my_socket: user = solicitud.split()[1].split(":")[1] self.jsonaregistrar() if user in self.registrar: print(self.registrar[user]["puerto"]) print(self.registrar[user]["ip"]) try: ipuser = self.registrar[user]["ip"] puerto = self.registrar[user]["puerto"] my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) my_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) my_socket.connect((ipuser, int(puerto))) my_socket.send(bytes(solicitud, 'utf-8') + b'\r\n\r\n') data = my_socket.recv(1024).decode('utf-8') self.wfile.write(bytes(data, 'utf-8')) print("Recibo del servidor: " + data) except (ConnectionRefusedError, KeyError): recv = "" self.wfile.write( bytes("SIP/2.0 400 Bad Request\r\n\r\n", 'utf-8')) else: LINE = ("SIP/2.0 404 User not found" + "\r\n\r\n") self.wfile.write(bytes(LINE, 'utf-8')) log("Error: User not found", LOG_PATH) self.registrarajson() elif metodo == "BYE": with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as my_socket: print(solicitud) user = solicitud.split()[1].split(":")[1] ipuser = self.registrar[user]["ip"] puerto = self.registrar[user]["puerto"] line = solicitud.replace("\r\n", " ") log("Recieved from " + ipuser + ":" + puerto + ":" + line, LOG_PATH) if user in self.registrar: my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) my_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) my_socket.connect((ipuser, int(puerto))) my_socket.send(bytes(solicitud, 'utf-8') + b'\r\n\r\n') data = my_socket.recv(1024).decode('utf-8') self.wfile.write(bytes(data, 'utf-8')) print("Recibo del servidor: " + data) data = data.replace("\r\n", " ") log("Sent to" + ipuser + ":" + puerto + ": " + data, LOG_PATH) else: mensaje = ("SIP/2.0 404 User not found \r\n\r\n") self.wfile.write(bytes(mensaje, 'utf-8')) linea = ("Error: SIP/2.0 404 User not found:") log(linea, LOG_PATH) self.registrarajson() elif metodo == "ACK": with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as my_socket: print(solicitud) #recibe ACK sip:[email protected] SIP/2.0 user = solicitud.split()[1].split(":")[1] ipuser = self.registrar[user]["ip"] puerto = self.registrar[user]["puerto"] line = solicitud.replace("\r\n", " ") log("Recieved from " + ipuser + ":" + puerto + ":" + line, LOG_PATH) if user in self.registrar: my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) my_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) my_socket.connect((ipuser, int(puerto))) my_socket.send(bytes(solicitud, 'utf-8') + b'\r\n\r\n') data = my_socket.recv(1024).decode('utf-8') self.wfile.write(bytes(data, 'utf-8')) print("Recibo del servidor: " + data) else: mensaje = ("SIP/2.0 404 User not found \r\n\r\n") self.wfile.write(bytes(mensaje, 'utf-8')) linea = ("Error: SIP/2.0 404 User not found:") log(linea, LOG_PATH) self.registrarajson() elif metodo != ("REGISTER", "INVITE", "ACK", "BYE"): self.wfile.write(b"SIP/2.0 405 Method Not Allowed\r\n\r\n") mensajelog = ("Error: SIP/2.0 405 Method Not Allowed") log(mensajelog, LOG_PATH) print("Error por metodo") else: self.wfile.write(b"SIP/2.0 400 Bad Request\r\n\r\n") mensajelog = ("Error: SIP/2.0 400 Bad Request") log(mensajelog, LOG_PATH) self.registrarajson() mensajefinlog = ("Finish") log(mensajefinlog, LOG_PATH)
def handle(self): """Escribe dirección y puerto del cliente (de tupla client_address)""" self.client_address """ Comprueba si se ha caducado la sesion de algun usuario """ for x in Usuarios.keys(): tiempo_actual = time.time() if Usuarios[x][2] + float(Usuarios[x][3]) < tiempo_actual: del Usuarios[x] while 1: # Leyendo línea a línea lo que nos envía el proxy/User Agent Recibido = self.rfile.read() # Si no hay más líneas salimos del bucle infinito if not Recibido: break IP_Recib = self.client_address[0] Puerto_Recib = self.client_address[1] Lista_Metodos = ["Register", "Invite", "Bye", "Ack"] print 'Recibimos...\r\n' + Recibido Linea0 = Recibido.split('\r\n') Linea = Linea0[0].split(' ') Metodo = Linea[0] uaclient.log(Lista[2]['path'], 'Recibir', IP_Recib, Puerto_Recib, Linea0[0] + '\r\n') if len(Linea) != 3 or Linea[2] != 'SIP/2.0': Envio = 'SIP/2.0 400 Bad Request\r\n\r\n' self.wfile.write(Envio) print 'Enviamos...\r\n' + Envio Log = 'SIP/2.0 400 Bad Request\r\n' uaclient.log(Lista[2]['path'], 'Enviar', IP_Recib, Puerto_Recib, Log) else: if not Metodo in Lista_Metodos: if line != '': Envio = 'SIP/2.0 405 Method Not Allowed\r\n\r\n' self.wfile.write(Envio) print 'Enviamos...\r\n' + Envio Log = 'SIP/2.0 405 Method Not Allowed\r\n' uaclient.log(Lista[2]['path'], 'Enviar', IP_Recib, Puerto_Recib, Log) else: if Metodo == 'Register': Info = Linea[1].split(':') Direc = Info[1] IP = self.client_address[0] Puerto = Info[2] Expir = Recibido.split('\r\n') Expir = Expir[1].split(' ') Expir = Expir[1] if Expir == '0': if Direc in Usuarios: del Usuarios[Direc] elif not Direc in Usuarios: Line = 'SIP/2.0 404 User Not Found\r\n\r\n' self.wfile.write(Line) print 'Enviamos...\r\n' + Line Log = 'SIP/2.0 404 User Not Found\r\n' uaclient.log(Lista[2]['path'], 'Enviar', IP_Recib, Puerto_Recib, Log) elif Expir > '0': if not Direc in Usuarios: Hora = time.time() Usuarios[Direc] = (self.client_address[0], Puerto, time.time(), Expir) Line = 'SIP/2.0 200 OK\r\n\r\n' self.wfile.write(Line) print 'Enviamos...\r\n' + Line Log = 'SIP/2.0 200 OK\r\n' uaclient.log(Lista[2]['path'], 'Enviar', IP_Recib, Puerto_Recib, Log) self.register2file() if Metodo == 'Invite' or Metodo == 'Bye' or \ Metodo == 'Ack': Direc = Recibido.split(' ') Direc = Direc[1].split(':') Direc = Direc[1] if Direc in Usuarios: try: #SACARLO DEL BUFFER Y ENVIAR AL OTRO UA UA = Usuarios[Direc][0] PORT_UA = int(Usuarios[Direc][1]) # Creamos el socket del Proxy my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) my_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) my_socket.connect((UA, PORT_UA)) my_socket.send(Recibido) print 'Reenvio...\r\n' uaclient.log(Lista[2]['path'], 'Enviar', UA, PORT_UA, Linea0[0] + '\r\n') if Metodo == 'Invite' or Metodo == 'Bye': Recibido = my_socket.recv(1024) print 'Recibimos...\r\n' + Recibido Log = Recibido.split('\r\n') uaclient.log(Lista[2]['path'], 'Recibir', UA, PORT_UA, Log[0] + '\r\n') if len(Log) == 14: uaclient.log(Lista[2]['path'], 'Recibir', UA, PORT_UA, Log[2] + '\r\n') uaclient.log(Lista[2]['path'], 'Recibir', UA, PORT_UA, Log[4] + '\r\n') self.wfile.write(Recibido) print 'Reenvio...\r\n' Log = Recibido.split('\r\n') uaclient.log(Lista[2]['path'], 'Enviar', UA, PORT_UA, Log[0] + '\r\n') if len(Log) == 14: uaclient.log(Lista[2]['path'], 'Enviar', UA, PORT_UA, Log[2] + '\r\n') uaclient.log(Lista[2]['path'], 'Enviar', UA, PORT_UA, Log[4] + '\r\n') my_socket.close() except socket.error: Texto = 'Error: No server listening at ' Texto += IP_Recib + ' port ' Texto += str(Puerto_Recib) + '\r\n' print Texto uaclient.log(Lista[2]['path'], 'Error', '', '', Texto) raise SystemExit elif not Direc in Usuarios: Line = 'SIP/2.0 404 User Not Found\r\n\r\n' self.wfile.write(Line) print 'Enviamos...\r\n' + Line Log = 'SIP/2.0 404 User Not Found\r\n' uaclient.log(Lista[2]['path'], 'Enviar', IP_Recib, Puerto_Recib, Log)
def enviar_proxy(self, linea, ip, port): """Envia mensajes al proxy.""" self.wfile.write(bytes(linea, 'utf-8')) print('Enviamos al Proxy:\r\n', linea) linea = linea.replace("\r\n", " ") log('Sent to ' + ip + ':' + port + ': ' + linea, LOG_PATH)
def handle(self): """handle method of the server class.""" # Escribe dirección y puerto del cliente (de tupla client_address) line = self.rfile.read() print('Recibido -- ', line.decode('utf-8')) evento = "Received from " mensaje = line.decode('utf-8').replace("\r\n", " ") log(rutalog, evento, proxy_ip, proxy_port, mensaje) message = line.decode('utf-8').split() metodo = message[0] ip_client = self.client_address[0] if metodo == "INVITE" and not SIPHandlerServer.escucha: line2 = "Content-Type: application/sdp\r\n\r\nv=0\r\no=" + usuario line2 += " " + ip_serv + "\r\ns=lasesion\r\nt=0\r\nm=audio " line2 += puerto_rtp + " RTP\r\n" line = "SIP/2.0 100 Trying\r\n\r\n" + "SIP/2.0 180 Ringing\r\n\r\n" line += "SIP/2.0 200 OK\r\n" + line2 self.wfile.write(bytes(line, 'utf-8')) print("Enviando -- ", line) mensaje = line.replace("\r\n", " ") ip_rtp = message[7] port_rtp = message[11] self.ip_rtp_dest.append(ip_rtp) self.puerto_rtp_dest.append(port_rtp) SIPHandlerServer.escucha = True elif metodo == "INVITE" and SIPHandlerServer.escucha: line = "SIP/2.0 480 Temporarily Unavailable\r\n\r\n" self.wfile.write(bytes(line, 'utf-8')) print("Enviando -- ", line) mensaje = line.replace("\r\n", " ") elif metodo == "ACK": hilo1 = threading.Thread(target=viartp, args=( self.ip_rtp_dest[0], self.puerto_rtp_dest[0], fichero_audio, )) hilo2 = threading.Thread(target=vlc, args=( ip_serv, puerto_rtp, )) hilo2.start() hilo1.start() evento = "Sent to " mensaje = "RTP" elif metodo == "BYE": system("killall vlc 2> /dev/null") system("killall mp32rtp 2> /dev/null") line = "SIP/2.0 200 OK\r\n\r\n" self.wfile.write(bytes(line, 'utf-8')) print("Enviando -- ", line) mensaje = line.replace("\r\n", " ") SIPHandlerServer.escucha = False elif metodo not in ["INVITE", "ACK", "BYE"]: line = "SIP/2.0 405 Method Not Allowed\r\n\r\n" self.wfile.write(bytes(line, 'utf-8')) print("Enviando -- ", line) mensaje = line.replace("\r\n", " ") else: line = "SIP/2.0 400 Bad Request\r\n\r\n" self.wfile.write(bytes(line, 'utf-8')) print("Enviando -- ", line) mensaje = line.replace("\r\n", " ") evento = "Sent to " log(rutalog, evento, proxy_ip, proxy_port, mensaje)
def handle(self): while 1: # Leyendo línea a línea lo que nos envía el proxy/User Agent line = self.rfile.read() # Si no hay más líneas salimos del bucle infinito if not line: break print 'Recibimos...\r\n' + line IP_Recib = self.client_address[0] Puerto_Recib = self.client_address[1] Linea0 = line.split('\r\n') Linea = Linea0[0].split(' ') Metodo = Linea[0] Lista_Metodos = ["Invite", "Bye", "Ack"] UserName = Lista[0]['username'] uaclient.log(Lista[4]['path'], 'Recibir', IP_Recib, Puerto_Recib, Linea0[0] + '\r\n') try: if len(Linea) != 3 or Linea[2] != 'SIP/2.0': Envio = 'SIP/2.0 400 Bad Request\r\n\r\n' self.wfile.write(Envio) print 'Enviamos...\r\n' + Envio Log = 'SIP/2.0 400 Bad Request\r\n' uaclient.log(Lista[4]['path'], 'Enviar', IP_Recib, Puerto_Recib, Log) else: if not Metodo in Lista_Metodos: if line != '': Envio = 'SIP/2.0 405 Method Not Allowed\r\n\r\n' self.wfile.write(Envio) print 'Enviamos...\r\n' + Envio Log = 'SIP/2.0 405 Method Not Allowed\r\n' uaclient.log(Lista[4]['path'], 'Envio', IP_Recib, Puerto_Recib, Log) else: if Metodo == 'Invite': Info = line.split('\r\n\r\n') SDP = Info[1].split('\r\n') IP = SDP[1].split(' ') self.RTP[0] = IP[3] Puerto = SDP[4].split(' ') self.RTP[1] = Puerto[3] Envio = 'SIP/2.0 100 Trying\r\n\r\n' Envio += 'SIP/2.0 180 Ringing\r\n\r\n' Envio += 'SIP/2.0 200 OK\r\n' Envio += 'Content-Type: application/sdp\r\n\r\n' Envio += 'v = 0\r\no = ' + UserName + ' ' Envio += Lista[1]['ip'] + '\r\ns = misesion\r\n' Envio += 't = 0\r\n' + 'm = audio ' Envio += Lista[2]['puerto'] + ' RTP\r\n\r\n' print 'Enviamos...\r\n' + Envio self.wfile.write(Envio) uaclient.log(Lista[4]['path'], 'Enviar', IP_Recib, Puerto_Recib, 'SIP/2.0 100 Trying\r\n') uaclient.log(Lista[4]['path'], 'Enviar', IP_Recib, Puerto_Recib, 'SIP/2.0 180 Ringing\r\n') uaclient.log(Lista[4]['path'], 'Enviar', IP_Recib, Puerto_Recib, 'SIP/2.0 200 OK\r\n') elif Metodo == 'Ack': print 'Envio RTP.....' #aEjecutar es un string con lo que se ejecuta #en la shell aEjecutar = './mp32rtp -i ' + self.RTP[0] + ' -p ' aEjecutar += str(self.RTP[1]) + '< ' aEjecutar += Lista[5]['path'] print "Vamos a ejecutar", aEjecutar os.system('chmod 755 mp32rtp') os.system(aEjecutar) uaclient.log(Lista[4]['path'], 'Enviar', self.RTP[0], self.RTP[1], 'Envio RTP\r\n') print 'Terminado RTP' elif Metodo == 'Bye': Envio = 'SIP/2.0 200 OK\r\n\r\n' print 'Enviamos...\r\n' + Envio self.wfile.write(Envio) Log = 'SIP/2.0 200 OK\r\n' uaclient.log(Lista[4]['path'], 'Enviar', IP_Recib, Puerto_Recib, Log) uaclient.log(Lista[4]['path'], 'Finish', '', '', '') except socket.error: Texto = 'Error: No server listening at ' Texto += IP_Recib + ' port ' + str(Puerto_Recib) + '\r\n' uaclient.log(Lista[4]['path'], 'Error', '', '', Texto) print Texto raise SystemExit
def handle(self): solicitud = self.rfile.read().decode("utf-8") metodo = solicitud.split()[0] start = ("Start server") log(start, LOG_PATH) solicitud_log = solicitud.replace("\r\n", " ") log("Received from: " + PROXY_IP + ":" + PROXY_PUERTO + ": " + solicitud_log, LOG_PATH) if metodo == "INVITE": line = ("SIP/2.0 100 Trying\r\n\r\n" + "SIP/2.0 180 Ringing\r\n\r\n" + "SIP/2.0 200 OK\r\n" + "Content-Type: application/sdp\r\n\r\n" + "v=0\r\n" + "o=" + USERNAME + " " + IP_UASERVER + "\r\n " + "s=misesion\r\n" + "m=audio " + str(RTPAUDIO) + " RTP \r\n\r\n") self.wfile.write(bytes(line, 'utf-8')+ b'\r\n') log("Sent to" + PROXY_IP + ":" + PROXY_PUERTO + ": " + line, LOG_PATH) elif metodo == "ACK": aEjecutar = "./mp32rtp -i " + IP_UASERVER + " -p " + str(RTPAUDIO) aEjecutar += " < " + AUDIO_PATH print("Vamos a ejecutar", aEjecutar ) os.system(aEjecutar) log("Sent to" + PROXY_IP + ":" + PROXY_PUERTO + ": " + aEjecutar , LOG_PATH) elif metodo == "BYE": self.wfile.write(b"SIP/2.0 200 OK:\r\n\r\n") line = ("SIP/2.0 200 OK:") log("Sent to" + PROXY_IP + ":" + PROXY_PUERTO + ": " + line, LOG_PATH) elif metodo != ("INVITE", "ACK", "BYE"): self.wfile.write(b"SIP/2.0 405 Method Not Allowed:\r\n\r\n") line = "SIP/2.0 405 Method Not Allowed:\r\n\r\n" log(line, LOG_PATH) print("Metodo erroneo ):") print(solicitud) else: self.wfile.write(b"SIP/2.0 400 Bad Request...\r\n\r\n") line = ("Error: SIP/2.0 400 Bad Request...") log(line, LOG_PATH)
if __name__ == "__main__": parser = make_parser() myHandler = XmlHandler() parser.setContentHandler(myHandler) try: parser.parse(open(CONFIG)) except FileNotFoundError: sys.exit("Usage: python uaserver.py config") CONFIGXML = myHandler.get_tags() # Pasamos los datos leidos xml a constantes USERNAME = CONFIGXML["account_username"] PASSWORD = CONFIGXML["account_passwd"] IP_UASERVER = CONFIGXML["uaserver_ip"] PUERTO_UASERVER = int(CONFIGXML["uaserver_puerto"]) RTPAUDIO = int(CONFIGXML["rtpaudio_puerto"]) PROXY_IP = CONFIGXML["regproxy_ip"] PROXY_PUERTO = CONFIGXML["regproxy_puerto"] LOG_PATH = CONFIGXML["log_path"] AUDIO_PATH = CONFIGXML["audio_path"] serv = socketserver.UDPServer((IP_UASERVER, PUERTO_UASERVER), HandlerEchoServer) print("Listening:\r\n") log("start:", LOG_PATH) try: serv.serve_forever() except KeyboardInterrupt: print("Server interrumpido") log("Finish", LOG_PATH)
except: password = "******" return password if __name__ == "__main__": try: CONFIG = sys.argv[1] except: sys.exit("Usage: python3 proxy_registrar.py config") parser = make_parser() cHandler = XMLProxyHandler() parser.setContentHandler(cHandler) parser.parse(open(CONFIG)) datos = cHandler.get_tags() database = datos['database']['path'] rutalog = datos['log']['path'] ip_serv = datos['server']['ip'] puerto_serv = datos['server']['puerto'] evento = "" serv = socketserver.UDPServer((ip_serv, int(puerto_serv)), SIPHandler) log(rutalog, evento, ip_serv, puerto_serv, "Starting...") print("Lanzando servidor UDP de eco...") try: serv.serve_forever() # espera en un bucle except KeyboardInterrupt: # ^C log(rutalog, evento, ip_serv, puerto_serv, "Finishing.") print("Finalizado servidor")
mensajefinlog = ("Finish") log(mensajefinlog, LOG_PATH) if __name__ == "__main__": parser = make_parser() prHandler = proxyRHandler() parser.setContentHandler(prHandler) try: parser.parse(open(CONFIG)) except FileNotFoundError: sys.exit("Usage: python proxy_registrar.py config") CONFIGXML = prHandler.get_tags() IP = CONFIGXML["server_ip"] PUERTO_SERVER = int(CONFIGXML["server_puerto"]) USERNAME = CONFIGXML["server_name"] LOG_PATH = CONFIGXML["log_path"] DATABASE_PATH = CONFIGXML["database_path"] DATABASE_PASSWD = CONFIGXML["database_passwdpath"] serv = socketserver.UDPServer((IP, PUERTO_SERVER), SIPRegisterHandler) print("Server " + USERNAME + " listening at port " + str(PUERTO_SERVER)) log("Starting...", LOG_PATH) try: serv.serve_forever() except KeyboardInterrupt: sys.exit("\r\n Proxy finalizado") log("Finishing.", LOG_PATH)
def handle(self): """handle method of the proxy class.""" line = self.rfile.read() print('Recibido -- ', line.decode('utf-8')) message = line.decode('utf-8').split() metodo = message[0] self.json2registered() ip_client = str(self.client_address[0]) puerto_client = str(self.client_address[1]) t = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(time.time() + 3600)) self.eliminar_usuario(t) if metodo == "REGISTER": sip_address = message[1][4:] usuario = sip_address.split(":")[0] puerto_serv = sip_address.split(":")[1] evento = "Received from " mensaje = line.decode('utf-8').replace("\r\n", " ") log(rutalog, evento, ip_client, puerto_client, mensaje) if int(message[4].split('/')[0]) >= 0: time_exp = int(message[4].split('/')[0]) else: time_exp = 0 t_tot = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime( time.time() + 3600 + time_exp)) if usuario not in self.dicc_users: nonce = str(random.randint(00000000000000000000, 99999999999999999999)) self.dicc_users[usuario] = {'autorizado': False, 'address': ip_client, 'expires': t_tot, 'port': puerto_serv, 'nonce': nonce} line = 'SIP/2.0 401 Unauthorized\r\nWWW-Authenticate: Digest' line += ' nonce="' + nonce + '"\r\n\r\n' print("Enviando -- ", line) self.wfile.write(bytes(line, 'utf-8')) elif not self.dicc_users[usuario]['autorizado']: contra = obtener_contra(usuario) nonce = self.dicc_users[usuario]['nonce'] h = hashlib.md5() h.update(bytes(contra, 'utf-8') + bytes(nonce, 'utf-8')) response = h.hexdigest() try: authenticate_recib = message[7].split('"')[1] except: authenticate_recib = "" line = "Failed to get the password" print(line) evento = "Error" log(rutalog, evento, proxy_ip, proxy_port, line) if authenticate_recib == response: line = "SIP/2.0 200 OK\r\n\r\n" print("Enviando -- ", line) self.wfile.write(bytes(line, 'utf-8')) self.dicc_users[usuario]['autorizado'] = True self.dicc_users[usuario]['expires'] = t_tot else: line = 'SIP/2.0 401 Unauthorized\r\nWWW-Authenticate:' line += ' Digest nonce="' + nonce + '"\r\n\r\n' print("Enviando -- ", line) self.wfile.write(bytes(line, 'utf-8')) else: expires_anterior = self.dicc_users[usuario]['expires'] if t_tot >= expires_anterior or time_exp == 0: self.dicc_users[usuario]['expires'] = t_tot line = "SIP/2.0 200 OK\r\n\r\n" print("Enviando -- ", line) self.wfile.write(bytes(line, 'utf-8')) evento = "Sent to " mensaje = line.replace("\r\n", " ") log(rutalog, evento, ip_client, puerto_client, mensaje) self.register2json() elif metodo == "INVITE": evento = "Received from " mensaje = line.decode('utf-8').replace("\r\n", " ") log(rutalog, evento, ip_client, puerto_client, mensaje) with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as my_socket: try: address_destino = message[1][4:] ip_destino = self.dicc_users[address_destino]['address'] puerto_destino = self.dicc_users[address_destino]['port'] my_socket.connect((ip_destino, int(puerto_destino))) my_socket.send(bytes(line.decode('utf-8'), 'utf-8')) print("Enviando -- ", line.decode('utf-8')) evento = "Sent to " mensaje = line.decode('utf-8').replace("\r\n", " ") log(rutalog, evento, ip_destino, puerto_destino, mensaje) data = my_socket.recv(1024) data = data.decode('utf-8') print("Recibido -- ", data) evento = "Received from " mensaje = data.replace("\r\n", " ") log(rutalog, evento, ip_destino, puerto_destino, mensaje) self.wfile.write(bytes(data, 'utf-8')) except: print("User " + address_destino + " Not Found") data = "SIP/2.0 404 User Not Found\r\n\r\n" self.wfile.write(bytes(data, 'utf-8')) evento = "Sent to " mensaje = data.replace("\r\n", " ") log(rutalog, evento, ip_client, puerto_client, mensaje) elif metodo == "ACK": evento = "Received from " mensaje = line.decode('utf-8').replace("\r\n", " ") log(rutalog, evento, ip_client, puerto_client, mensaje) with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as my_socket: address_destino = message[1][4:] ip_destino = self.dicc_users[address_destino]['address'] puerto_destino = self.dicc_users[address_destino]['port'] my_socket.connect((ip_destino, int(puerto_destino))) my_socket.send(bytes(line.decode('utf-8'), 'utf-8')) print("Enviando -- ", line.decode('utf-8')) evento = "Sent to " mensaje = line.decode('utf-8').replace("\r\n", " ") log(rutalog, evento, ip_destino, puerto_destino, mensaje) elif metodo == "BYE": evento = "Received from " mensaje = line.decode('utf-8').replace("\r\n", " ") log(rutalog, evento, ip_client, puerto_client, mensaje) with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as my_socket: try: address_destino = message[1][4:] ip_destino = self.dicc_users[address_destino]['address'] puerto_destino = self.dicc_users[address_destino]['port'] my_socket.connect((ip_destino, int(puerto_destino))) my_socket.send(bytes(line.decode('utf-8'), 'utf-8')) print("Enviando -- ", line.decode('utf-8')) evento = "Sent to " mensaje = line.decode('utf-8').replace("\r\n", " ") log(rutalog, evento, ip_destino, puerto_destino, mensaje) data = my_socket.recv(1024) data = data.decode('utf-8') print("Recibido -- ", data) evento = "Received from " mensaje = data.replace("\r\n", " ") log(rutalog, evento, ip_destino, puerto_destino, mensaje) line = data self.wfile.write(bytes(line, 'utf-8')) except: data = "" print("User " + address_destino + " Not Found") line = "SIP/2.0 404 User Not Found\r\n\r\n" self.wfile.write(bytes(line, 'utf-8')) print("Enviando -- ", line) evento = "Sent to " mensaje = line.replace("\r\n", " ") log(rutalog, evento, ip_client, puerto_client, mensaje) elif metodo not in ["REGISTER", "INVITE", "ACK", "BYE"]: line = "SIP/2.0 405 Method Not Allowed\r\n\r\n" print("Enviando -- ", line) self.wfile.write(bytes(line, 'utf-8')) evento = "Sent to " mensaje = line.replace("\r\n", " ") log(rutalog, evento, ip_client, puerto_client, mensaje) else: line = "SIP/2.0 400 Bad Request\r\n\r\n" print("Enviando -- ", line) self.wfile.write(bytes(line, 'utf-8')) evento = "Sent to " mensaje = line.replace("\r\n", " ") log(rutalog, evento, ip_client, puerto_client, mensaje)
log.logsent(IP, PORT, message, fichero) else: IP = self.client_address[0] PORT = self.client_address[1] message = 'SIP/2.0 405 Method Not Allowed \r\n\r\n' self.wfile.write(bytes(message, 'utf-8')) log.logrecive(IP, PORT, RECIVE, fichero) log.logsent(IP, PORT, message, fichero) print(line.decode('utf-8'), end='') print(self.dic) if __name__ == "__main__": if len(sys.argv) != 2: sys.exit(' Usage: python proxy_registrar.py config') CONFIG = sys.argv[1] XML.parse() IP = XML.dic['server_ip'] PORT = int(XML.dic['server_port']) base = XML.dic['database_path'] psw_file = XML.dic['database_passwdpath'] fichero = XML.dic['log_path'] abro = open(base, 'w') abro.close() log = log(fichero) SERV = socketserver.UDPServer((IP, PORT), USERS) print('Server V listening at port ' + str(PORT) + '...') SERV.serve_forever()
json.dump(self.data_list, open('registered.json', 'w'), indent='\t') if __name__ == "__main__": try: CONFIG = sys.argv[1] except (IndexError, ValueError): sys.exit("Usage:\n python3 proxy_registrar.py config") parser = make_parser() cHandler = Proxy_XmlHandler() parser.setContentHandler(cHandler) parser.parse(open(CONFIG)) config_data = cHandler.get_tags() # Escribiendo en el log log(config_data, 'Starting...') serv = socketserver.UDPServer(('', int(config_data['server']['puerto'])), SIPRegisterHandler) print("Server Sheldon_Proxy listening at port " + config_data['server']['puerto'] + " ...") print() try: serv.serve_forever() except KeyboardInterrupt: # Escribiendo en el log log(config_data, 'Finishing.') print("Ending proxy.")