def handle_acks(self, packet_dict, pckt_id, response_packet, msg_type): if (response_packet != None and Checksum.validate_checksum(response_packet)): response = self.split_ack(response_packet) msg_type = response[0] ack_seqno = response[1] # checks to see if we have a corrupted message type if were are not in sack mode. if (msg_type != 'ack'): return # update the number of acks in the packet dictionary for each packet. if (ack_seqno in packet_dict.keys()): packet_dict[ack_seqno][2] += 1 # Handle duplicate acknowledgements. IF we have 3 acks for the same packet, # we should retransmit only that specific packet. if (ack_seqno in packet_dict.keys() and packet_dict[ack_seqno][2] >= 4): self.retransmitOnlyPacket(packet_dict, ack_seqno) # Handle correct ack by deleting the appropriate packets from the window. elif (((int(ack_seqno) - int(pckt_id[0])) >= 1) and msg_type != 'end'): diff = int(ack_seqno) - int(pckt_id[0]) # how many elements we should delete from dict/ lst. packet_dict, pckt_id = self.delete_elems(diff, pckt_id, packet_dict) # if ackqno == lowest packet number, then we have dropped that packet. elif (int(ack_seqno) - int(pckt_id[0]) == 0): self.retransmitPackets(packet_dict) # Handle packet loss and corruption. If the ack is never received, or # the checksum for the ack is invalid, we should retransmit the entire window. elif(response_packet == None or (not Checksum.validate_checksum(response_packet))): self.retransmitPackets(packet_dict)
def handle_sacks(self, packet_dict, pckt_id, response_pckt, msg_type, sack_lst): if (response_pckt != None and Checksum.validate_checksum(response_pckt)): response = self.split_sack(response_pckt) msg_type = response[0] # msg_type sack_seqno = response[1] # sack seqno sack_lst = self.update_sack_lst(response[2], sack_lst) # updates the sack list. if (msg_type != 'sack'): return if (sack_seqno in packet_dict.keys()): packet_dict[sack_seqno][2] += 1 if (sack_seqno in packet_dict.keys() and packet_dict[sack_seqno][2] >= 4): self.retransmitOnlyPacket(packet_dict, sack_seqno) # Handle correct ack by deleting the appropriate packets from the window. elif (((int(sack_seqno) - int(pckt_id[0])) >= 1) and msg_type != 'end'): diff = int(sack_seqno) - int(pckt_id[0]) # how many elements we should delete from dict/ lst. packet_dict, pckt_id = self.delete_elems(diff, pckt_id, packet_dict) elif (int(sack_seqno) - int(pckt_id[0]) == 0): self.retransmitSackPackets(packet_dict, response_pckt, sack_lst) elif(response_pckt == None or (not Checksum.validate_checksum(response_pckt))): self.retransmitPackets(packet_dict)
def handle_response(self,response): if (response==None): buffer=deque() while (len(self.queue)!=0): packet =self.queue.popleft() self.send(packet) buffer.append(packet) while (len(buffer) !=0): packet=buffer.popleft() self.queue.append(packet) response = self.receive(0.50) self.handle_response(response) elif Checksum.validate_checksum(response)==False: return elif Checksum.validate_checksum(response): type1, seq ,data,checksum =self.split_packet(response) if int(seq)-1 < self.unacknowledge: if int(seq) < self.unacknowledge: return packet=self.queue.popleft() self.send(packet) self.queue.appendleft(packet) response=self.receive(0.50) self.handle_response(response) else: self.difference = int(seq)- self.unacknowledge d=self.difference while (d >0): self.unacknowledge +=1 self.queue.popleft() d -=1
def paytm_request(request, token): teamcaptain = TeamCaptain.objects.get(payment_token=token) MERCHANT_KEY = settings.PAYTM_MERCHANT_KEY MERCHANT_ID = settings.PAYTM_MERCHANT_ID CALLBACK_URL = settings.HOST_URL + settings.PAYTM_CALLBACK_URL # Generating unique temporary ids order_id = Checksum.__id_generator__() teamcaptain.order_id = order_id teamcaptain.save() bill_amount = teamcaptain.event.price name = str(teamcaptain.name) + ' ' + str(teamcaptain.event.name) if bill_amount: data_dict = { 'MID': MERCHANT_ID, 'ORDER_ID': order_id, 'TXN_AMOUNT': bill_amount, 'CUST_ID': 'Cust002', 'INDUSTRY_TYPE_ID': 'Retail', 'WEBSITE': 'DIYtestingweb', #testing phase 'CHANNEL_ID': 'WEB', 'CALLBACK_URL': CALLBACK_URL, } param_dict = data_dict param_dict['CHECKSUMHASH'] = Checksum.generate_checksum( data_dict, MERCHANT_KEY) print param_dict return render(request, "registrations/payment.html", {'paytmdict': param_dict}) return HttpResponse("Bill Amount Error.")
def handle_response(self, response): if (response == None): buffer = deque() while (len(self.queue) != 0): packet = self.queue.popleft() self.send(packet) buffer.append(packet) while (len(buffer) != 0): packet = buffer.popleft() self.queue.append(packet) response = self.receive(0.50) self.handle_response(response) elif Checksum.validate_checksum(response) == False: return elif Checksum.validate_checksum(response): type1, seq, data, checksum = self.split_packet(response) if int(seq) - 1 < self.unacknowledge: if int(seq) < self.unacknowledge: return packet = self.queue.popleft() self.send(packet) self.queue.appendleft(packet) response = self.receive(0.50) self.handle_response(response) else: self.difference = int(seq) - self.unacknowledge d = self.difference while (d > 0): self.unacknowledge += 1 self.queue.popleft() d -= 1
def payment(request): MERCHANT_KEY = settings.PAYTM_MERCHANT_KEY MERCHANT_ID = settings.PAYTM_MERCHANT_ID get_lang = "/" + get_language() if get_language() else '' CALLBACK_URL = settings.HOST_URL + get_lang + settings.PAYTM_CALLBACK_URL # Generating unique temporary ids order_id = Checksum.__id_generator__() bill_amount = request.GET.get("bill_amount") if bill_amount: data_dict = { 'MID': MERCHANT_ID, 'ORDER_ID': order_id, 'TXN_AMOUNT': bill_amount, 'CUST_ID': '*****@*****.**', 'INDUSTRY_TYPE_ID': 'Retail', 'WEBSITE': 'WEB_STAGING', 'CHANNEL_ID': 'WEB', 'CALLBACK_URL': CALLBACK_URL, } param_dict = data_dict param_dict['CHECKSUMHASH'] = Checksum.generate_checksum( data_dict, MERCHANT_KEY) return render(request, "paytm/payment.html", {'paytmdict': param_dict}) return HttpResponse("Bill Amount Could not find. ?bill_amount=10")
def main(f1, f2): checksum1 = Checksum.hasfile(f1) checksum2 = Checksum.hasfile(f2) if checksum1 == checksum2: print("Success: Same contents") else: print("Failure: Do not have same contents..")
def create_rf_command_datagram(dest_callsign, dest_device_id, command, payload): """ This function creates a command packet datagram for commanding REMOTE (RF) Faraday devices. This datagram encapsulates the actual command packets to the passed to the remote device as a payload. The important difference between the RF and non RF command packet functions are remote callsign and ID arguments that tell Faraday what devices to target for commanding. .. note:: Remote commanding simply calls a specific local command that transmits a "local" command packet as a payload to the target Faraday device. Also, This command module has a predefined set of command number definitions for use/reference. :param dest_callsign: The callsign of the target Faraday unit :param dest_device_id: The device ID number of the target Faraday unit :param command: The command "number" that identifies the command packet to be parsed or direct action to be taken :param payload: The payload for the specified command packet type. This is usually just commands full "packet" structure :return: A complete command datagram packet as a string of raw bytes """ #Cheack if callsign is too long if len(dest_callsign) < DEST_CALLSIGN_MAX_LEN: #Define packet structures pkt_cmd_datagram_struct = struct.Struct( '2B25s' ) #Command packect to be run on remote unit as local command pkt_cmd_datagram_error_detection_struct = struct.Struct( '>1H' ) #Command packect to be run on remote unit as local command Error Detection pkt_rf_cmd_struct = struct.Struct( '9s2B29s' ) #RF Command packet that encapsulates local command to be run on remote unit pkt_rf_error_detection_struct = struct.Struct( '>1H') #16bit Error Detection (Checksum) #Create local command for remote unit pkt_cmd_datagram = pkt_cmd_datagram_struct.pack( command, len(payload), payload) pkt_cmd_datagram_error_detection = pkt_cmd_datagram_error_detection_struct.pack( checksum.compute_checksum_16(pkt_cmd_datagram, len(pkt_cmd_datagram))) pkt_cmd_datagram_final = pkt_cmd_datagram + pkt_cmd_datagram_error_detection print repr(pkt_cmd_datagram_final) #Create RF Command for local device without Error Detection appended. NOTE Callsign must be in uppercase! pkt_rf_cmd = pkt_rf_cmd_struct.pack( str(dest_callsign).upper(), len(dest_callsign), dest_device_id, pkt_cmd_datagram_final) #Create final local command packet with Error Detection appeneded pkt_rf_error_detection = pkt_rf_error_detection_struct.pack( checksum.compute_checksum_16(pkt_rf_cmd, len(pkt_rf_cmd))) packet = pkt_rf_cmd + pkt_rf_error_detection return packet else: print "Error: Callsign too long!"
def notCurrupted(rcvpkt): data = rcvpkt[1] #print(data) checksum = rcvpkt[2] rcvDataCheck = c.CHECK(data) result = c.binaryAddition(rcvDataCheck, checksum) length = len(result) for i in range(0, length): if (result[i] != "1"): return False break return True
def start(self): packets_data = self.split_file(self.infile.read()) #handshake #for jobia magram testebistvis while iyos :) while True: self.send(self.make_packet('syn', -1, '')) ack = self.receive(0.5) if ack is None: continue _, seqno, _, _ = self.split_packet(ack) break idx = 0 WINDOW = dict() while idx < len(packets_data): for i in range(idx, idx + 7): if i >= len(packets_data): break if WINDOW.get(i, False): continue self.send(self.make_packet('dat', i, packets_data[i])) Fast = dict() while True: ack_data = self.receive(0.5) if ack_data is None: break _, seqno, _, _ = self.split_packet(ack_data) if str(seqno).__contains__(';'): #SACK ls = seqno.split(';') WINDOW[int(ls[0]) - 1] = Checksum.validate_checksum(ack_data) if WINDOW[int(ls[0]) - 1]: idx = max(idx, int(ls[0])) if ls[0] in Fast: Fast[ls[0]] += 1 else: Fast[ls[0]] = 1 if Fast[ls[0]] > 3: idx = int(ls[0]) print('fast1') break if ls[1].__contains__(',') and WINDOW[int(ls[0]) - 1]: for num in ls[1].split(','): WINDOW[int(num)] = True elif len(ls[1]) == 1 and WINDOW[int(ls[0]) - 1]: WINDOW[int(ls[1])] = True else: #ACK if seqno in Fast: Fast[seqno] += 1 else: Fast[seqno] = 1 if Fast[seqno] > 3: idx = int(seqno) print('fast1') break WINDOW[int(seqno) - 1] = Checksum.validate_checksum(ack_data) if WINDOW[int(seqno) - 1]: idx = max(idx, int(seqno)) self.send(self.make_packet('fin', idx, ''))
def start(self): initialSeqNo = 0 print self.packets startData = self.infile.read(self.dataSize) firstPacket = self.make_packet("start", initialSeqNo, startData) self.packets[0] = firstPacket self.send(firstPacket) startTime = time.clock() while (True): response = self.receive(.5 - (time.clock()-startTime)) if response is None: self.send(firstPacket) startTime = time.clock() elif Checksum.validate_checksum(response): break self.base = 1 for i in range(1, self.N): data = self.infile.read(self.dataSize) if len(data) < self.dataSize: packet = self.make_packet("end", i, data) self.packets[i] = packet self.lastSeqNo = i self.send(packet) break else: packet = self.make_packet("data", i, data) self.packets[i] = packet self.send(packet) startTime = time.clock() while True: receivedPacket = self.receive(.5 - (time.clock() - startTime)) if receivedPacket is None: self.handle_timeout() elif not Checksum.validate_checksum(receivedPacket): pass else: msgType, seqNoStr, data, checkSum = self.split_packet(receivedPacket) seqNo = int(seqNoStr) if seqNo == self.lastSeqNo+1: break if not seqNo in self.acks: self.acks[seqNo] = 1 self.handle_new_ack(seqNo) else: self.acks[seqNo] += 1 self.handle_dup_ack(seqNo)
def notCurrupted(rcvpkt): data = rcvpkt[0] #print(data) checksum = rcvpkt[1] rcvDataCheck = c.CHECK(data) result = c.binaryAddition(rcvDataCheck, checksum) length = len(result) for i in range(0, length): if (result[i] != "1"): #print("Acknowledgement is not currupted") return False break #print("Acknowledgement is not currupted") return True
def start(self): while not self.should_stop_transmission: if not self.end_reached: self.send__fill_the_window(5 - len(self.sending_window), len(self.sending_window)) response = self.receive(0.5) if response and Checksum.validate_checksum(response): response_type, ack_num_str, data, checksum = self.split_packet( response) if response_type == "sack": #print "SACK got!" #print ack_num_str ack_num = int(ack_num_str.split(';')[0]) self.received = ack_num_str.split(';')[1].split(',') else: ack_num = int(ack_num_str) self.check_for_stop(ack_num) #checks for out of order acks #if ack_num is smaller than current window, then better ignore it, but we didn't if ack_num - self.window_start_number > 0: self.handle_new_ack(ack_num) else: self.handle_dup_ack(ack_num) else: self.handle_timeout(self.received) self.infile.close()
def _initialize_connection(self, retry_count): #print "WHY HELLO THERE" #Three Way Handshake if retry_count > 0: #Fields of the packet msg_type = 'start' msg = "" #Create and send the initlization packet start_packet = self.make_packet(msg_type, self.isn, msg) self.send(start_packet) #Wait 500ms to receive the packet response = self.receive(timeout=self.timeout) if response: if Checksum.validate_checksum(response): #Good Packet! msg_type, seqno, data, checksum = self.split_packet(response) ack = int(seqno) if msg_type == "ack" and ack == self.isn: self.send_base = self.isn + 1 return True else: return self._initialize_connection(retry_count - 1) else: #Not good packet! return self._initialize_connection(retry_count - 1) else: #Timeout return self._initialize_connection(retry_count - 1) else: #Could not connect return False
def _tear_down_connection(self, retry_count): #print "TEAR DOWN THIS WALL" if retry_count > 0: #Fields of the packet msg_type = 'end' msg = "" #Create and send the tear down packet tear_down_packet = self.make_packet(msg_type, self.send_base, msg) self.send(tear_down_packet) #Wait 500ms to receive the packet response = self.receive(timeout=self.timeout) if response: if Checksum.validate_checksum(response): #Good Packet! msg_type, seqno, data, checksum = self.split_packet(response) seqno = int(seqno) if seqno == self.send_base and msg_type == "ack": return True else: #Wrong SEQ NO EXPECTED return self._tear_down_connection(retry_count - 1) else: #Not good packet! return self._tear_down_connection(retry_count - 1) else: #Timeout return self._tear_down_connection(retry_count - 1) else: #Could not tear down packet. Should we just stop sending messages? return False
def handle_response(self, response_packet): if Checksum.validate_checksum(response_packet): print "recv: %s" % response_packet return True else: print "recv: %s <--- CHECKSUM FAILED" % response_packet return False
def handle_response(self, response): if response == None: self.handle_timeout() # elif Checksum.validate_checksum(response) == False: # # print "recv: %s <--- CHECKSUM FAILED" % response elif Checksum.validate_checksum(response): msgtype, ack_str, data, checksum = self.split_packet(response) if sackMode: split = ack_str.split(';') ack = int(split[0]) else: ack = int(ack_str) if ack < self.acktracker: # print ("rcv: buggy ack") response = self.receive(0.50) if self.printstatements: print response self.handle_response(response) elif ack == self.acktracker: self.handle_dup_ack(ack_str) elif ack > self.acktracker: self.handle_new_ack(ack_str)
def hand_shake(self): # Create a syn packet with the random initial sequence number syn_packet = self.make_packet(MSG_TYPE_SYN, self.sequence_number, PACKET_BODY_EMPTY) # Prepare to receive ack_packet = None ack_msg_type = None ack_sequence_number = None # We want to populate ack_packet, make sure the response message type is ack, # and check that the sequence number is the self.sequence_number + 1 while not ack_packet and ack_msg_type != MSG_TYPE_ACK and ack_sequence_number != self.sequence_number + 1: # Send the packet self.send(syn_packet) # After sending the synmessage, the sender waits for an ackpacket to finish a handshake ack_packet = self.receive(RETRANSMISSION_TIME) if ack_packet: # Split apart the packet components = self.packet_components(ack_packet) ack_msg_type = components[PACKET_COMPONENT_MSG_TYPE] ack_sequence_number = int(components[PACKET_COMPONENT_SEQUENCE_NUMBER]) # Validate the checksum valid_checksum = Checksum.validate_checksum(ack_packet) if not valid_checksum: ack_packet = None
def _listen_for_acks(self): self.time_til_timeout = self.timeout while True: #Always listen for acks start_time = datetime.now() response = self.receive(timeout=self.time_til_timeout) end_time = datetime.now() delta = end_time - start_time time_elapsed = delta.seconds + delta.microseconds/1E6 self.time_til_timeout = max(self.time_til_timeout - time_elapsed, 0) #print self.time_til_timeout if response: if Checksum.validate_checksum(response): #Good Packet! msg_type, seqno, data, checksum = self.split_packet(response) if msg_type != "ack": continue ack = int(seqno) if ack < self.send_base: continue if self.handle_new_ack(ack): return else: #Not good packet! Listen for acks again pass else: #TIMEOUT! self.handle_timeout()
def hand_shake(self): # Create a syn packet with the random initial sequence number syn_packet = self.make_packet(MSG_TYPE_SYN, self.sequence_number, PACKET_BODY_EMPTY) # Prepare to receive ack_packet = None ack_msg_type = None ack_sequence_number = None # We want to populate ack_packet, make sure the response message type is ack, # and check that the sequence number is the self.sequence_number + 1 while not ack_packet and ack_msg_type != MSG_TYPE_ACK and ack_sequence_number != self.sequence_number + 1: # Send the packet self.send(syn_packet) # After sending the synmessage, the sender waits for an ackpacket to finish a handshake ack_packet = self.receive(RETRANSMISSION_TIME) if ack_packet: # Split apart the packet components = self.packet_components(ack_packet) ack_msg_type = components[PACKET_COMPONENT_MSG_TYPE] ack_sequence_number = int( components[PACKET_COMPONENT_SEQUENCE_NUMBER]) # Validate the checksum valid_checksum = Checksum.validate_checksum(ack_packet) if not valid_checksum: ack_packet = None
def handle_dup_ack(self, ack): # invalid checksum if not Checksum.validate_checksum(ack): pass msg_type, seqno, data, checksum = self.split_packet(ack) if int(seqno) > self.window[0]: self.send(self.s_window[seqno])
def shop(): name = request.form['name'] email = request.form['email'] blog_id = request.form['blog_id'] amount = request.form['amount'] orderid = str(random.randint(1, 2000)) paymentemail[orderid] = email paymentblog[orderid] = blog_id # password1=request.form['password1'] # password2=request.form['password2'] # print(name,email,paytmno,amount) deepak_dict = { 'MID': MERCHANT_ID, 'ORDER_ID': orderid, 'TXN_AMOUNT': str(amount), 'CUST_ID': email, 'INDUSTRY_TYPE_ID': 'Retail', 'WEBSITE': 'WEBSTAGING', 'CHANNEL_ID': 'WEB', 'CALLBACK_URL': 'http://localhost:5000/shop/handlerequest/', } deepak_dict['CHECKSUMHASH'] = Checksum.generate_checksum( deepak_dict, MERCHANT_KEY) print(deepak_dict) return render_template('payment/paytm.html', deepak_dict=deepak_dict)
def slide_window(self, ack, received_packets): num_to_read = 0 if ack is None: num_to_send = self.window_size else: _, raw_seqno, _, _ = self.split_packet(ack) seqno = int(raw_seqno.split(';', 1)[0]) if seqno <= self.truly_received: num_to_send = 0 elif not Checksum.validate_checksum(ack): num_to_send = 1 #0 else: if self.sackMode: received_packets_indices = [ int(packet) for packet in raw_seqno.split(';', 1)[1].split(',') if packet ] for index in received_packets_indices: received_packets[index - 1] = True self.ack_counter[seqno] += 1 if self.ack_counter[seqno] == self.fast_retransmit_limit: num_to_send = 1 self.ack_counter[seqno] = 0 # num_to_send = self.window_size # for i in xrange(self.truly_received + 1, self.truly_received + self.window_size + 1): # self.ack_counter[i] = 0 else: num_to_read = seqno - 1 - self.truly_received num_to_send = num_to_read #self.window_size self.truly_received = seqno - 1 return num_to_read, num_to_send
def start(self): while True: try: # Receive the message and where it came from message, address = self.receive() # Split the message up into it's appropriate parts msg_type, seqno, data, checksum = self._split_message(message) if debug: print('Received message: {0} {1} {2} {3} {4}'.format( msg_type, seqno, data, sys.getsizeof(data), checksum)) if Checksum.validate_checksum(message): # If the checksum checks out, handle the message using one of the following methods defined by the # MESSAGE_HANDLER dictionary. self.MESSAGE_HANDLER.get(msg_type, self._handle_other)(seqno, data, address) elif self.debug: print("checksum failed: %s" % message) # If the timeout happens, do a cleanup. if time.time() - self.last_cleanup > self.timeout: self._cleanup() except socket.timeout: self._cleanup() except (KeyboardInterrupt, SystemExit): exit() except ValueError as e: if self.debug: print(e) pass # ignore
def handle_response(self,response_packet,sendNext): if Checksum.validate_checksum(response_packet): print "recv: %s" % response_packet else: print "recv: %s <--- CHECKSUM FAILED" % response_packet sendNext = False
def handle_corrupted_response(self, packet, response_packet): response = response_packet while Checksum.validate_checksum(response) == False: print "Resending packet..." self.send(packet) response = self.receive(2.0) self.handle_response(response)
def findDups(path): flag = os.path.isabs(path) if flag == False: path = os.path.abspath(path) exists = os.path.exists(path) if exists: dupsfilesDic = {} startTime = datetime.now().strftime('%Y-%m-%d_%H-%M-%S') totalFiles = 0 dupFiles = 0 for dirName, subDir, files in os.walk(path): for fname in files: totalFiles = len(files) fname = os.path.join(dirName, fname) file_hash = Checksum.hashfile(fname) if file_hash in dupsfilesDic: dupsfilesDic[file_hash].append(fname) dupFiles += 1 else: dupsfilesDic[file_hash] = [fname] return dupsfilesDic, startTime, totalFiles, dupFiles else: print("Invalid path")
def check_packet(self, r_pck): if self.sackMode: pieces = r_pck.split('|') seqnums = pieces[1] sackpieces = seqnums.split(';') seqno = int(sackpieces[0]) sack_str = sackpieces[1] sacks = [] if sack_str != '': sack_str = sackpieces[1].split(',') for i in sack_str: sacks.append(int(i)) return seqno, Checksum.validate_checksum(r_pck), sacks else: seqno = self.get_seq(r_pck) return seqno, Checksum.validate_checksum(r_pck), []
def validate(param_dict, merchant_key): if 'CHECKSUMHASH' not in param_dict: return False checksum = param_dict.pop('CHECKSUMHASH')[0] return Checksum.verify_checksum(param_dict=param_dict, merchant_key=merchant_key, checksum=checksum)
def start(self): msg_type=None while not len(self.window)==self.max_size: msg=self.infile.read(1372) if self.seq_no==0: msg_type='start' elif msg=="": msg_type='end' else: msg_type='data' packet=self.make_packet(msg_type,self.seq_no,msg) self.send(packet) self.window[self.seq_no]=packet self.seq_no+=1 while (not self.end) or (not len(self.window)==0): ack=self.receive(0.5) if ack==None: self.handle_timeout() elif Checksum.validate_checksum(ack): msg_type,seq_no,data,checksum=self.split_packet(ack) if self.last_ack_num==0: self.last_ack_num=int(seq_no) self.last_ack=ack self.handle_new_ack(ack,int(seq_no)) elif int(seq_no)==self.last_ack_num: self.handle_dup_ack(ack,int(seq_no)) else: self.handle_new_ack(ack,int(seq_no)) else: self.send(self.window[self.last_ack_num]) self.seq_no=0 self.last_ack_num=0 self.last_ack=None self.end=False
def checkresponse(self, resp, minack= 0, maxack= 1): """ Helper. Checks if the ack packet is not corrupted and that the seqno in the ack is the next seqno. Also checks if resp is null or Ack is non-int.""" # response is nil, not a valid response if not resp: return False # get the pieces of the response packet spacket = self.split_packet(resp) msg_type, ackno = spacket[0], spacket[1] # msgs from receiver should only be of type 'ack' if msg_type != 'ack': return False #if ackno is not an int, exit try: ackno = int(ackno) except ValueError: return False # keep track of dupacks to resend lost packet(s) if ackno == minack: self.dupacks += 1 else: self.dupacks = 0 # make sure checksum is valid, and the ackno is in the sequence of acknos we are expecting return Checksum.validate_checksum(resp) and ackno > minack and ackno <= maxack
def initiate_conversation(self): for i in range(1, self.windowSize + 1): msg = self.infile.read(500) self.buffer[i] = msg # End of file has been read. if msg == "": # Empty msg, need to send empty start and end packets. if i == 1: self.buffer[i + 1] = "" self.last_seqno = i + 1 else: self.last_seqno = i self.segmented_all_file = True self.infile.close() break # Will break out if we get a valid ack received_valid_ack = False while not received_valid_ack: # Will keep sending all the packets in the first window, except the end packet. for i in range(1, len(self.buffer.keys()) + 1): if i == 1: msg_type = "start" elif i == len(self.buffer.keys()): break else: msg_type = "data" packet = self.make_packet(msg_type, i, self.buffer[i]) self.send(packet) self.packets_in_transit += 1 response = self.receive(0.5) received_valid_ack = response != None and Checksum.validate_checksum(response) self.handle_response(response)
def update_packet(self, msg_type=None, seqno=None, data=None, full_packet=None, update_checksum=True): """ This function handles safely changing the contents of a packet. By default, we re-compute the checksum every time the packet is updated. However, you can disable this if you intend to create a corrupted packet. Note that the checksum is calculated over the NON-0-indexed sequence number. """ if not self.bogon: if msg_type == None: msg_type = self.msg_type if seqno == None: seqno = self.seqno if data == None: data = self.data if msg_type == "ack": # doesn't have a data field, so handle separately body = "%s|%d|" % (msg_type, seqno) checksum_body = "%s|%d|" % (msg_type, seqno + self.start_seqno_base) else: body = "%s|%d|%s|" % (msg_type, seqno, data) checksum_body = "%s|%d|%s|" % (msg_type, seqno + self.start_seqno_base, data) if update_checksum: checksum = Checksum.generate_checksum(checksum_body) else: checksum = self.checksum self.msg_type = msg_type self.seqno = seqno self.data = data self.checksum = checksum if full_packet: self.full_packet = full_packet else: self.full_packet = "%s%s" % (body, checksum)
def handle_response(self,response_packet): if Checksum.validate_checksum(response_packet): msg_type, seqno, data, checksum = self.split_packet(response_packet) print(type(seqno)) print "recv: %s" % response_packet else: print "recv: %s <--- CHECKSUM FAILED" % response_packet
def recvMyACKs(self): ACKlist = [] currentACK = self.receive(0.5) while currentACK != None: # If we get something, then check CHECKSUM temp = currentACK.split("|") if not (len(temp) == 3 and temp[1].isdigit() and temp[2].isdigit() and temp[0] == "ack"): # ignore if self.DEBUG: print "Disregarding corrupted packet: %s" % currentACK currentACK = self.receive(0.5) continue if Checksum.validate_checksum(currentACK): msg_type, seqno, checksum = currentACK.split('|') ACKlist.append(seqno) #put the next expected packet number in the list elif self.DEBUG: print "Received corrupted packet. Disregarding." #wait for next packet currentACK = self.receive(0.5) ACKlist = map(int, ACKlist) if self.DEBUG: print "Received %d ACK's: %s. Highest is %d: the receiver has everything to %d" % (len(ACKlist), ACKlist, max(ACKlist) if ACKlist else -1, max(ACKlist)-1 if ACKlist else -1) # No ACKs to be received. Act accordingly. if ACKlist: for key in self.packetList.keys(): # Cleaning up packets stored if key < max(ACKlist) and len(self.packetList) > 1: del self.packetList[key] return ACKlist
def handle_response(self,response): if response == None: self.handle_timeout() # elif Checksum.validate_checksum(response) == False: # # print "recv: %s <--- CHECKSUM FAILED" % response elif Checksum.validate_checksum(response): msgtype, ack_str, data, checksum = self.split_packet(response) if sackMode: split = ack_str.split(';') ack = int(split[0]) else: ack = int(ack_str) if ack < self.acktracker: # print ("rcv: buggy ack") response = self.receive(0.50) if self.printstatements: print response self.handle_response(response) elif ack == self.acktracker: self.handle_dup_ack(ack_str) elif ack > self.acktracker: self.handle_new_ack(ack_str)
def start(self): while not self.should_stop_transmission: if not self.end_reached: self.send__fill_the_window(5 - len(self.sending_window), len(self.sending_window)) response = self.receive(0.5) if response and Checksum.validate_checksum(response): response_type, ack_num_str, data, checksum = self.split_packet(response) if response_type == "sack": #print "SACK got!" #print ack_num_str ack_num = int(ack_num_str.split(';')[0]) self.received = ack_num_str.split(';')[1].split(',') else: ack_num = int(ack_num_str) self.check_for_stop(ack_num) #checks for out of order acks #if ack_num is smaller than current window, then better ignore it, but we didn't if ack_num - self.window_start_number > 0: self.handle_new_ack(ack_num) else: self.handle_dup_ack(ack_num) else: self.handle_timeout(self.received) self.infile.close()
def handlerequest(): # paytm will send you post request here form = request.form.to_dict() response_dict = {} for i in form.keys(): response_dict[i] = form[i] if i == 'CHECKSUMHASH': checksum = form[i] with open("invoice.json", "r") as read: myjsonread = json.load(read) mymain = myjsonread verify = Checksum.verify_checksum(response_dict, MERCHANT_KEY, checksum) if verify: if response_dict['RESPCODE'] == '01': # print('order successful') with open("invoice.json", "w") as write: myjsonread[str(form["ORDERID"])]["status"] = "Paid" myjsonread[str(form["ORDERID"])]["pmode"] = "Paytm" try: myjsonread[str(form["ORDERID"])]["transid"] = str( form["ORDERID"]) except: pass try: json.dump(myjsonread, write) except: json.dump(mymain, write) write.close() else: # print('order was not successful because' + response_dict['RESPMSG']) pass return render_template('paymentstatus.html', response=response_dict)
def checkresponse(self, resp, minack=0, maxack=1): """ Helper. Checks if the ack packet is not corrupted and that the seqno in the ack is the next seqno. Also checks if resp is null or Ack is non-int.""" # response is nil, not a valid response if not resp: return False # get the pieces of the response packet spacket = self.split_packet(resp) msg_type, ackno = spacket[0], spacket[1] # msgs from receiver should only be of type 'ack' if msg_type != 'ack': return False #if ackno is not an int, exit try: ackno = int(ackno) except ValueError: return False # keep track of dupacks to resend lost packet(s) if ackno == minack: self.dupacks += 1 else: self.dupacks = 0 # make sure checksum is valid, and the ackno is in the sequence of acknos we are expecting return Checksum.validate_checksum( resp) and ackno > minack and ackno <= maxack
def update_packet(self, msg_type=None, seqno=None, data=None, full_packet=None, update_checksum=True): """ This function handles safely changing the contents of a packet. By default, we re-compute the checksum every time the packet is updated. However, you can disable this if you intend to create a corrupted packet. Note that the checksum is calculated over the NON-0-indexed sequence number. """ if not self.bogon: if msg_type == None: msg_type = self.msg_type if seqno == None: seqno = self.seqno if data == None: data = self.data if msg_type == "ack": # doesn't have a data field, so handle separately body = "%s|%d|" % (msg_type, seqno) checksum_body = "%s|%d|" % (msg_type, seqno + self.start_seqno_base) else: body = "%s|%d|%s|" % (msg_type,seqno,data) checksum_body = "%s|%d|%s|" % (msg_type, seqno + self.start_seqno_base, data) if update_checksum: checksum = Checksum.generate_checksum(checksum_body) else: checksum = self.checksum self.msg_type = msg_type self.seqno = seqno self.data = data self.checksum = checksum if full_packet: self.full_packet = full_packet else: self.full_packet = "%s%s" % (body,checksum)
def start(self): # NOTE: Packet payload size should be larger than 1000 bytes (unless it is the last packet in the stream) # but less than 1472 bytes. msg_type = None while not self.done_sending: # Repeatedly send packets until our window is full or until our chunking is complete (i.e. msg_type == false) while not self.window.window_is_full() and self.is_chunking_done is False: # Send the next packet chunk and return a boolean that represents whether we are done chunking self.is_chunking_done = self.send_next_packet_chunk() if self.is_chunking_done: msg_type = 'end' # Receive an ACK from the Receiver packet_response = self.receive(0.5) # If we haven't received a response in 500ms, then handle timeout if (packet_response == None): self.handle_timeout() else: # Via the spec, we ignore all ACK packets with an invalid checksum if Checksum.validate_checksum(packet_response): msg_type, seqno, data, checksum = self.split_packet(packet_response) if self.sackMode: seqno = int(seqno.split(";")[0]) # For some reason, 'seqno' is returned as a string... so we parse it into an integer else: seqno = int(seqno) # Do ACKs have data? Probably not? if (self.debug): print("Received packet: %s | %d | %s | %s" % (msg_type, seqno, data, checksum)) # Put the current sequence number in our <sequence number -> ACKs> map, given some conditions # If we haven't seen the current ACK before if not self.window.is_seqno_contained_in_ack_map(seqno): self.handle_new_ack(seqno) # Current sequence number is NOT already contained within our map... else: # Increment the number of ACKs (for seqno) by 1 self.window.add_acks_count_to_map(seqno, self.window.get_ack_number_via_seqno(seqno) + 1) # Algorithm: If ACK count is 3, then we use fast retransmit and resend the seqno with count == 3 if (self.window.get_ack_number_via_seqno(seqno) == 3): self.handle_dup_ack(seqno) else: # Ignore ACKs with invalid checksum # Do we need to handle_timeout() if we receive an ACK with an invalid checksum? self.handle_timeout() pass # Declare that we are done sending if our window is empty AND we are done chunking if (self.window.get_number_of_packets_in_window() == 0 and self.is_chunking_done is True): self.done_sending = True
def start(self): print("===== Welcome to BEARDOWN-TP Receiver v2.0! =====") print("* Listening on port %d..." % self.port) while True: try: # message, address = self.receive() message_bytes, address = self.receive() message = message_bytes.decode() msg_type, seqno, data, checksum = self._split_message(message) try: seqno = int(seqno) except: raise ValueError if debug: print("%s %d %s %s" % (msg_type, seqno, data, checksum)) if Checksum.validate_checksum(message): # print("msg_type: %s" % msg_type) # print("data: %s" % data) self.MESSAGE_HANDLER.get(msg_type, self._handle_other)(seqno, data, address) elif self.debug: print("checksum failed: %s" % message) if time.time() - self.last_cleanup > self.timeout: self._cleanup() except socket.timeout: self._cleanup() except (KeyboardInterrupt, SystemExit): exit() except ValueError as e: if self.debug: print(e) pass # ignore
def make_packet(self, msg_type, seqno, msg): # msg_type can be either 'start', 'end', 'data', or 'ack' # seqno is simply the sequence number of the packet # msg is simply the packet's data body = "%s|%d|%s|" % (msg_type, seqno, msg) checksum = Checksum.generate_checksum(body) packet = "%s%s" % (body, checksum) return packet
def make_packet(self,msg_type,seqno,msg): # msg_type can be either 'start', 'end', 'data', or 'ack' # seqno is simply the sequence number of the packet # msg is simply the packet's data body = "%s|%d|%s|" % (msg_type,seqno,msg) checksum = Checksum.generate_checksum(body) packet = "%s%s" % (body,checksum) return packet
def handle_response(self, response_packet): if Checksum.validate_checksum(response_packet): # print "Checksum is valid: %s" % response_packet print "Checksum is valid!" else: # Checksum for response packet is not valid # Naively, we simply just resend the packet self.send(self.packet_to_send)
def make_packet(self, msg_type=None, seqno=None, msg=None, packet=None): if msg_type is not None: body = b"".join([ msg_type.encode(), b'|', bytes(str(seqno).encode()), b'|', msg, b'|' ]) checksum = Checksum.generate_checksum(body) return_packet = body + checksum return return_packet else: body = b"".join([ packet[0].encode(), b'|', bytes(str(packet[1]).encode()), b'|', packet[2], b'|' ]) checksum = Checksum.generate_checksum(body) return_packet = body + checksum return return_packet
def handle_response(self,response_packet): if Checksum.validate_checksum(response_packet): # print "Checksum is valid: %s" % response_packet print "Checksum is valid!" else: # Checksum for response packet is not valid # Naively, we simply just resend the packet self.send(self.packet_to_send)
def start(self): # print "AnDJ-Sender: dport = ", # print self.dport # send 5 packets and store these 5 packets to window. frequent = 0 while frequent != 5: msg = self.infile.read(4000) # print 'AnDJ-Sender: ----------read the file' msg_type = 'data' if msg == "": msg_type = 'end' packet = self.make_packet(msg_type, frequent, msg) self.window.append(packet) # print 'AnDJ-Sender: will send packet: %s|%d' % (msg_type, frequent) self.send(packet) self.isreadall = True break else: if frequent == 0: msg_type = 'start' packet = self.make_packet(msg_type, frequent, msg) self.window.append(packet) # print 'AnDJ-Sender: will send packet: %s|%d' % (msg_type, frequent) self.send(packet) frequent = frequent + 1 time.sleep(2) while len(self.window) != 0: try: response = self.receive(0.5) # print 'AnDJ-Sender: receive successful: message = ', # print response # self.handle_response(response) if not Checksum.validate_checksum(response): print "AnDJ-Sender: %s" % 'checksum error' continue expectno, checksum = self.split_ack_packet(response)[1:] if checksum: # print 'AnDJ-Sender: start to handle the ack. new_ack or dup_ack' msg_type, seqno, data, checksum = self.split_packet(self.window[0]) if int(expectno) - int(seqno) > 0: # print '1' self.skip_window(int(expectno) - int(seqno)) else: # print '2' self.handle_dup_ack(expectno) # print '--------------------------------------------------------' except socket.timeout: self.handle_timeout() self.infile.close()
def handle_response(self, response): if (response == None): buffer = deque() while (len(self.queue) != 0): packet = self.queue.popleft() self.send(packet) buffer.append(packet) while (len(buffer) != 0): packet = buffer.popleft() self.queue.append(packet) response = self.receive(0.50) self.handle_response(response) elif Checksum.validate_checksum(response) == False: return elif Checksum.validate_checksum(response): type1, seq, seqno_list, checksum = self.split_packet(response) packet = self.queue.pop() self.queue.append(packet) type2, seq2, data, checksum = self.split_packet(response) if int(seq) - 1 < self.unacknowledge: if int(seq) < self.unacknowledge: return l = seqno_list.split(' ') send_list = list() for x in range(self.unacknowledge, int(seq2) + 1): if x not in l: send_list.append(x - self.unacknowledge) buffer = deque() for i in range(int(seq2) + 1 - self.unacknowledge): packet = self.queue.popleft() if i in send_list: self.send(packet) buffer.append(packet) while (len(buffer) != 0): packet = buffer.pop() self.queue.appendleft(packet) response = self.receive(0.50) self.handle_response(response) else: self.difference = int(seq) - self.unacknowledge d = self.difference while (d > 0): self.unacknowledge += 1 self.queue.popleft() d -= 1
def handle_response(self,response): if (response==None): buffer=deque() while (len(self.queue)!=0): packet =self.queue.popleft() self.send(packet) buffer.append(packet) while (len(buffer) !=0): packet=buffer.popleft() self.queue.append(packet) response = self.receive(0.50) self.handle_response(response) elif Checksum.validate_checksum(response)==False: return elif Checksum.validate_checksum(response): type1, seq ,seqno_list,checksum =self.split_packet(response) packet=self.queue.pop() self.queue.append(packet) type2, seq2, data ,checksum=self.split_packet(response) if int(seq)-1 < self.unacknowledge: if int(seq) < self.unacknowledge: return l=seqno_list.split(' ') send_list=list() for x in range(self.unacknowledge,int(seq2)+1): if x not in l: send_list.append(x-self.unacknowledge) buffer=deque() for i in range(int(seq2)+1-self.unacknowledge): packet=self.queue.popleft() if i in send_list: self.send(packet) buffer.append(packet) while(len(buffer) != 0): packet=buffer.pop() self.queue.appendleft(packet) response=self.receive(0.50) self.handle_response(response) else: self.difference = int(seq)- self.unacknowledge d=self.difference while (d >0): self.unacknowledge +=1 self.queue.popleft() d -=1
def handle_response(self,response): #if None then its a timeout msgtype, ack, data, checksum = self.split_packet(response) if (response==None): self.handle_timeout() # make sure checksum works elif Checksum.validate_checksum(response)==False: print "recv: %s <--- CHECKSUM FAILED" % response # if checksum works elif Checksum.validate_checksum(response): #if acktracker equal to ack that means repeat ack if self.acktracker == ack: self.handle_dup_ack(ack) #if acktracker is less than ack that means new ack if self.acktracker < ack: print self.acktracker self.handle_new_ack(ack) print self.acktracker
def handle_response(self, response): #if None then its a timeout msgtype, ack, data, checksum = self.split_packet(response) if (response == None): self.handle_timeout() # make sure checksum works elif Checksum.validate_checksum(response) == False: print "recv: %s <--- CHECKSUM FAILED" % response # if checksum works elif Checksum.validate_checksum(response): #if acktracker equal to ack that means repeat ack if self.acktracker == ack: self.handle_dup_ack(ack) #if acktracker is less than ack that means new ack if self.acktracker < ack: print self.acktracker self.handle_new_ack(ack) print self.acktracker
def handle_response(self,response_packet): if Checksum.validate_checksum(response_packet): if DEBUG: print "recv: %s " % response_packet return 1 else: if DEBUG: print "recv: %s <--- CHECKSUM FAILED" % response_packet return False
def send_message(self, data, priority='11', count_incr=True): cksm = Checksum.calculate(data) message = priority + json.dumps(data) + cksm try: self.sock.sendto(message, (self.rxip, self.rxport)) #TODO implement catch, fail, etc except Exception: pass if count_incr: self.counter.increment()
def check_ack_packet(self, packet): msg_type, seqno, data, checksum = self.split_packet(packet) if(msg_type != 'ack' and not self.sackMode): return False elif(msg_type!='sack' and self.sackMode): return False elif(Checksum.validate_checksum(checksum)): return False else: return True
def handle_response(self, response_packet): if Checksum.validate_checksum(response_packet): internalACKPacket = self.internalACKPacketGenerator(response_packet) if internalACKPacket.getMsgtype() == ACK_TYPE and self.window.validateAckPacket(internalACKPacket): self.handle_cum_ack(internalACKPacket) elif internalACKPacket.getMsgtype() == SACK_TYPE and self.window.validateAckPacket(internalACKPacket): self.handle_sack_ack(internalACKPacket) else: # print('checksum drop or Window does not contain seqno') pass
def handle_packet(self): for p in self.forwarder.in_queue: p_type = p.msg_type p_no = p.seqno if random.choice([True, False]): p.update_packet(msg_type=p_type, seqno=-1, data='corrupt', full_packet=None, update_checksum=False) valid = Checksum.validate_checksum(p) self.forwarder.out_queue.append(p) else: self.forwarder.out_queue.append(p) #empty out in_queue self.forwarder.in_queue = []
def send_receive_loop(self): while True: self.send_five(self.ack_no) response = self.receive(.5) if response is not None and Checksum.validate_checksum(response): # ack_no is always the last received ack if self.ack_no <= self.ack_number(response): self.ack_no = self.ack_number(response) # if self.window == self.last_packet_no: if ack_no >= len(message): break
def handle_response(self,response): if (response==None): buffer=deque() i=len(self.queue)+self.detect_network() if (i<=0): i=1 j=min(len(self.queue), i) while (j > 0): packet =self.queue.popleft() self.send(packet) self.resend_packets+=1 self.total_packets+=1 buffer.append(packet) j-=1 while (len(buffer) !=0): packet=buffer.pop() self.queue.appendleft(packet) response = self.receive(0.50) self.handle_response(response) elif Checksum.validate_checksum(response)==False: return elif Checksum.validate_checksum(response): type1, seq ,data,checksum =self.split_packet(response) if int(seq)-1 < self.unacknowledge: if int(seq) < self.unacknowledge: return packet=self.queue.popleft() self.send(packet) self.resend_packets+=1 self.total_packets+=1 self.queue.appendleft(packet) response=self.receive(0.50) self.handle_response(response) else: self.difference = int(seq)- self.unacknowledge d=self.difference while (d >0): self.unacknowledge +=1 self.queue.popleft() d -=1