def handleClient(name, clientsocket, table, msgqueue, answers): msg = '-' connected = True while connected: try: msg = receiveString(clientsocket) cmd = msg.split(' ') method = cmd[0].upper() except: method = '' if len(method) != 0: if method == 'PTR': req_msg = table.getStr() sendString(clientsocket, table.getStr()) elif not table.exists(cmd[-1]): newpdu = PDU(name, 'ROUTE_REQUEST', 5, None, cmd[-1], '', [name]) msgqueue.put(newpdu) if answers.get() == 'not found': sendString(clientsocket, 'Server unavailable.') elif method == 'GET' or method == 'LST' or method == 'DEL' or method == 'PUT': fields = method.upper() i = 1 while i < len(cmd) - 1: fields += ' ' + cmd[i] i += 1 newpdu = PDU(name, 'METHOD_REQUEST', 5, None, cmd[-1], fields, [name]) msgqueue.put(newpdu) pdu = answers.get() req_msg = pdu.getMsg() sendString(clientsocket, req_msg) table.remove(cmd[-1]) else: sendString(clientsocket, '[METHOD not found]') print('[METHOD not found]') elif method == 'GET' or method == 'LST' or method == 'DEL' or method == 'PUT': newpdu = PDU(name, 'METHOD_REQUEST', 5, None, ' '.join(cmd.pop()), tmsg, [name]) msgqueue.put(newpdu) pdu = answers.get() req_msg = pdu.getMsg() sendString(clientsocket, req_msg) else: print('[METHOD not found]') else: connected = False print("[CONNECTION closed] disconnected.")
def menus(source, msgqueue, answers, cs, pit): print('Nodo: ' + source) print('---------Pedidos-----------') print('Publicar: pub data_name data_value') print('Subscrever: sub data_name') print('---------------------------') while True: opt = input() directive = opt.split(' ') # Publicar informação if directive[0].upper() == 'PUB': cs.addContent(directive[1], directive[2]) print(opt) # Subscrever informação elif directive[0].upper() == 'SUB': content = directive[1] if cs.checkContent(content): print('Conteudo: ', cs.getContent(content)) elif not pit.checkInterest(content): pit.addInterest(content, source) newpdu = PDU(source, 'SUB_REQUEST', 10, None, None, content) msgqueue.put(newpdu) else: print('Conteudo já procurado') ans = answers.get() print(ans) # Operação padrão else: print('Opção inválida.')
def sender(socket, name, port, groupipv6, routing_table, interval, msgqueue, rplyawait, answersr, answersm): sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 0) # (ROUTE_REPLY|ROUTE_REQUEST) Enviar pdus em fila de espera rr = threading.Thread(target=dispatch, args=(sock, msgqueue, groupipv6, port, rplyawait, interval, name, answersr, answersm)) rr.start() # (Protocolo HELLO) Atualizar tabelas de roteamento while True: pdu = PDU(name, 'HELLO', 1, routing_table) sock.sendto(pickle.dumps(pdu), (groupipv6, port)) time.sleep(interval)
def menus(name, router, radius, timeout, dispatch_queue): print('---------Opções:-----------') print('Encontrar nodo: find') print('Imprimir tabela: print') print('---------------------------') while True: opt = input() cmd = opt.split(' ') # Imprimir tabela if cmd[0] == 'print': router.routingTable.printTable() # Encontrar novo nodo elif cmd[0] == 'find': # Verificar se existe, ou não, um pdu para enviar. if not router.routingTable.exists(cmd[1]): if router.pendingTable.check((cmd[1], 'ROUTE_REPLY')): router.pendingTable.add((cmd[1], 'ROUTE_REPLY'), name) print('[ROUTE_REQUEST] already requested') else: router.pendingTable.add((cmd[1], 'ROUTE_REPLY'), name) pdu = PDU('ROUTE_REQUEST', name, None, radius, None, cmd[1], [name]) dispatch_queue.put(pdu) # Criar thread para remover elemento da pendingTable depois do passar o tempo de timeout threading.Thread(target=pendingTimeout, args=( timeout, router.pendingTable, (cmd[1], 'ROUTE_REPLY'), )).start() else: print('----------------------------') print('Face | Neighbour | Content ') row = router.routingTable.exists(cmd[1]) print(row[0], ' ', row[1], ' ', row[2]) print('----------------------------') # Operação padrão else: print('Opção inválida.')
def menus(source, msgqueue, table): while True: print('Nodo: ' + source) # print('---------Opções:-----------') # print('Encontrar nodo: f') # print('Imprimir tabela: p') # print('---------------------------') opt = input() # Imprimir tabela if opt == 'p': table.printTable() # Encontrar novo nodo elif opt == 'f': print('Nome do nodo:') nodo = input() newpdu = PDU(source, 'ROUTE_REQUEST', 5, None, nodo, '', [source]) msgqueue.put(newpdu) # Operação padrão else: print('Opção inválida.')
def hello(sock, groupipv6, port, zone, name, routing_table, hello_interval): while True: pdu = PDU('HELLO', name, None, 1, routing_table, zone, [name]) sock.sendto(pickle.dumps(pdu), (groupipv6, port)) time.sleep(hello_interval)
def route(self, pdu): newpdu = None # Obter tipo do pdu, ttl e target pdu_type = pdu.getType() ttl = pdu.getTTL() source = pdu.getSource() directive = pdu.getDirective() target = pdu.getTarget() # Verificar tempo de vida do pdu caso seja positivo verifica o tipo de pdu. if ttl <= 0: print('[TTL expired]', pdu_type) elif source == self.name: newpdu = None elif pdu_type == 'HELLO': hello(self.zone, self.name, pdu, self.routingTable) elif pdu_type == 'ROUTE_REQUEST': found = self.routingTable.exists(directive) if found: strrow = str(found[0]) + ' ' + str(found[2]) newpdu = PDU('ROUTE_REPLY', self.name, source, self.radius, None, strrow, [self.name]) print('[ROUTE_REQUEST] found') elif self.pendingTable.check((directive, 'ROUTE_REPLY')): self.pendingTable.add((directive, 'ROUTE_REPLY'), source) print('[ROUTE_REQUEST] already requested') else: self.pendingTable.add((directive, 'ROUTE_REPLY'), source) newpdu = PDU('ROUTE_REQUEST', source, None, ttl - 1, None, directive, [self.name]) # Criar thread para remover elemento da pendingTable depois do passar o tempo de timeout threading.Thread(target=pendingTimeout, args=( self.timeout, self.pendingTable, (directive, 'ROUTE_REPLY'), )).start() print('[ROUTE_REQUEST] forward') elif pdu_type == 'ROUTE_REPLY': row = directive.split(' ') if self.pendingTable.check((row[0], 'ROUTE_REPLY')): faces = self.pendingTable.get((row[0], 'ROUTE_REPLY')) self.pendingTable.rm((row[0], 'ROUTE_REPLY')) if self.name in faces: self.routingTable.addNode(row[0], source, row[1], time.time()) faces.remove(self.name) print('[ROUTE_REPLY] tabela de routing atualizada') if faces != []: newpdu = PDU('ROUTE_REPLY', self.name, faces[0], self.radius, None, directive, [self.name]) print('[ROUTE_REPLY] forward') else: print('[PDU TYPE unknown]', pdu_type) return newpdu
def receiver(socket, name, port, groupipv6, routing_table, interval, msgqueue, rplyawait, answers, cs, pit, fib): # Look up multicast group address in name server and find out IP version addrinfo = socket.getaddrinfo(groupipv6, None)[0] # Create a socket s = socket.socket(addrinfo[0], socket.SOCK_DGRAM) # Bind it to the port s.bind(('', port)) group_bin = socket.inet_pton(addrinfo[0], addrinfo[4][0]) # Join group mreq = group_bin + struct.pack('@I', 0) s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq) # Loop, printing any data we receive while True: # Obter o pdu recebido data, sender = s.recvfrom(4096) pdu = pickle.loads(data) # Remover nodos, da rede, da tabla pelo tempo de expiração. routing_table.verifyTimes(interval) # Obter informações do pdu pdutype = pdu.getType() path = pdu.getPath() source = pdu.getSource() ttl = pdu.getTTL() if ttl >= 0: if pdutype == 'SUB_REQUEST': content = pdu.getMsg() if cs.checkContent(content): value = cs.getContent(content) newpdu = PDU(name, 'SUB_DATA', 100, None, source, content + ' ' + value) msgqueue.put(newpdu) print('[SUB_REQUEST] Informação encontrada:', content) elif pit.checkInterest(content): pit.addInterest(content, source) elif fib.checkInterface(content): pit.addInterest(content, source) interface = fib.getInterface(content)[0] newpdu = PDU(name, 'SUB_REQUEST', ttl - 1, None, source, content) msgqueue.put(newpdu) print('[SUB_REQUEST] Informação reencaminhada:', content) else: print('[SUB_REQUEST] Informação inexistente:', content) if pdutype == 'SUB_DATA': data = pdu.getMsg().split(' ') content = data[0] value = data[1] if pit.checkInterest(content): interested = pit.getInterested(content) pit.rmInterest(content) cs.addContent(content, value) for i in interested: if i == name: answers.put(content + ' ' + value) else: newpdu = PDU(name, 'SUB_DATA', 100, None, i, content + ' ' + value) msgqueue.put(newpdu) print('[SUB_REQUEST] Informação encontrada:', content) else: print('[SUB_DATA] Descartado', content) # Verificar o tipo de pdu # Processar pedido HELLO recebido. if pdutype == 'HELLO': # Adicionar o nodo nas tabelas (geral e vizinhos diretos). # Juntar a tabela dos vizinhos do emissor do pdu recebido # com a tabela geral. nodetime = time.time() routing_table.addNode(source, source, str(sender[0]).split('%')[0], nodetime) routing_table.addNeighbour(source, source, str(sender[0]).split('%')[0], nodetime) routing_table.mergeTable(pdu.getTable(), source, nodetime, name) # Processar pedido Method_REQUEST recebido. elif pdutype == 'METHOD_REQUEST': target = pdu.getTarget() if not routing_table.exists(target): if target == name: opt = pdu.getMsg() print('receiver ' + pdu.getMsg()) rec_msg = get(opt, port) # METHOD_REPLY caso o nodo procurado exista na tabela pdutable = Table() pdu.replyPDU(name, source, pdutable, 'METHOD_REPLY', rec_msg) msgqueue.put(pdu) print('[METHOD_REQUEST Encontrado] ', source, ' -> ', target[0]) elif name not in path: print('receiver ' + pdu.getMsg()) # METHOD_REQUEST caso o nodo procurado não exista na tabela pdu.forwardingPDU(name) msgqueue.put(pdu) print('[METHOD_REQUEST Reencaminhar] ', source, ' -> *') # Processar pedido METHOD_REPLY recebido. elif pdutype == 'METHOD_REPLY': poped = path[-1:] # Verificar se é o próximo elemento do caminho e se estava a espera de resposta if len(poped) == 1: if poped[0] == name: # Verificar se este é o destino da informação if pdu.getTarget() == name: answers.put(pdu) print('[METHOD_REPLY Atualizar Tabela] ', source, ' -> ', name) else: pdu.forwardingPDU(name) msgqueue.put(pdu) print('[METHOD_REPLY Reencaminhar] ', source, ' -> *') # Processar pedido ROUTE_REQUEST recebido. elif pdutype == 'ROUTE_REQUEST': # Verificar se a origem do datagrama não é este nodo; # Verificar se o pdu ainda não tinha passado por este nodo. if source != name and (name not in path): # Verificar a tabela tem a informação do nodo procurado. target = routing_table.exists(pdu.getTarget()) if target: # ROUTE_REPLY caso o nodo procurado exista na tabela pdutable = Table() pdutable.addNeighbour(target[0], None, target[2], -1) pdu.replyPDU(name, source, pdutable, 'ROUTE_REPLY') msgqueue.put(pdu) print('[ROUTE_REQUEST Encontrado] ', source, ' -> ', target[0]) else: # ROUTE_REQUEST caso o nodo procurado não exista na tabela pdu.forwardingPDU(name) msgqueue.put(pdu) print('[ROUTE_REQUEST Não Encontrado] ', source, ' -> *') else: print('[ROUTE_REQUEST Replicado] ', source, ' -> ', name) # Processar pedido ROUTE_REPLY recebido. elif pdutype == 'ROUTE_REPLY': nodetime = time.time() waited = list(pdu.getTable().getNeighbours())[0] poped = path[-1:] # Verificar se é o próximo elemento do caminho e se estava a espera de resposta if len(poped) == 1 and waited: if poped[0] == name and rplyawait.checkElem(waited[0]): rplyawait.rmElem(waited[0]) routing_table.addNode(waited[0], source, waited[2], nodetime) # Verificar se este é o destino da informação if pdu.getTarget() == name: ## tabela atualizada answers.put('table updated') print('[ROUTE_REPLY Atualizar Tabela] ', source, ' -> ', name) else: pdu.forwardingPDU(name) msgqueue.put(pdu) print('[ROUTE_REPLY Reencaminhar] ', source, ' -> *')