Ejemplo n.º 1
0
 def _send(self, value , tags = None, le_byte = None, log_packet = True, se=False ):
         se = True if (se and not (str(value[0])+ str(value[1])).upper() in self.ClearCommands) else False
         slog = getSyslog()
         slog.loginfo("-- SE --" + str(se))
         from testharness.exceptions import logicalException
         tlvp = TLVPrepare()
         tosend=None
         if len( value ) != 4:
                 logicalException(' Invalid header len must be equal 4')
         log_out_frame_buf = []
         tags_array = None
         le_array = bytearray()
         if le_byte != None:
             le_array = bytearray([ le_byte & 0xFF ])
         if tags == None:
                 c_pcb = 0
                 tosend=bytearray( value ) + le_array 
                 
                 if se:
                     self.__SEQ_NUM+=1
                     tosend+=self.__SEQ_NUM.to_bytes(4,'big')
                     tosend = self.tdes.encrypt( tosend )
                     c_pcb |= 2
                 w_len = len( tosend )
                 lrc = tutil.lrccalc( self.__nad, c_pcb, w_len, tosend )
                 log_out_frame_buf += self.send_raw( self.__nad, c_pcb, w_len, tosend ,lrc )
         else:
                 tags_array = tlvp.prepare_packet_from_tags(tags)
                 #Prepare length
                 tags_array[0] = 255 if (len(tags_array)-1) > 255 else len(tags_array)-1
                 tags_array = bytearray( value ) + tags_array
                 tags_array += le_array
                 if se:
                     self.__SEQ_NUM+=1
                     tags_array+=self.__SEQ_NUM.to_bytes(4,'big')
                     tags_array=self.tdes.encrypt( tags_array )
                 w_len = len( tags_array )
                 #Send long or short packets depends on the chained msgs enabled
                 if w_len > self.__MAX_PACKET_PROTO_LEN and not self.__chained_tx_messages:
                         raise logicalException('Packet too long > 254 and chained msgs not enabled')
                 if w_len <= self.__MAX_PACKET_PROTO_LEN:
                         c_pcb = 2 if se else 0
                         lrc = tutil.lrccalc( self.__nad, c_pcb, w_len, tags_array )
                         log_out_frame_buf += self.send_raw( self.__nad, c_pcb, w_len ,tags_array ,lrc )            
                 else:
                         total_len = w_len
                         for p in range(0,total_len, self.__MAX_PACKET_PROTO_LEN):
                                 raw_data = tags_array[p:(p+self.__MAX_PACKET_PROTO_LEN) ]
                                 c_pcb = 2 if se else 0
                                 c_pcb |= 1 if len(raw_data)==self.__MAX_PACKET_PROTO_LEN else 0
                                 raw_len = len(raw_data)
                                 lrc = tutil.lrccalc( self.__nad, c_pcb, raw_len, raw_data )
                                 log_out_frame_buf += self.send_raw( self.__nad, c_pcb, raw_len, raw_data ,lrc )
         if not se and log_packet:
             self.log_message('send', tags_array , log_out_frame_buf, tags, value)
         elif log_packet:
             if tags == None:
                 self.log_message('send', tags_array, [ self.tdes.decrypt( tosend) ], tags, value )
             else:
                 self.log_message('send', tags_array, [ self.tdes.decrypt( tags_array ) ], tags, value )
Ejemplo n.º 2
0
 def __prepare_from_template(self, template, tags):
     from testharness.exceptions import logicalException
     #if type(template) != int or template>255 or template<0:
     if type(template) != int:
         logicalException(' Template value from 0 to 255 required')
     t_array = bytearray()
     tag_buf = self.__prepare_from_tags(tags)
     t_array.append(template)
     t_array += self.__prepare_tlv_length(len(tag_buf))
     #print('template tlv len', len(tag_buf))
     t_array += tag_buf
     return t_array
Ejemplo n.º 3
0
def execute_script(filename):
    global __SCRIPT_ROOT
    __SCRIPT_ROOT = os.path.dirname(os.path.abspath(filename))
    th_ast_parser = __create_ast_th_language_syntax()
    ast = th_ast_parser.parseFile(filename, True)
    log = getSyslog()
    conn = connection.Connection()
    req_unsolicited = conn.connect()
    abort_sw1sw2 = True
    pool = tagStorage()
    localtempl = {}
    if req_unsolicited:
        #Receive unsolicited
        status, buf, uns = conn.receive()
        if status != 0x9000:
            raise exc.invResponseException('Unsolicited message fail', status)
        log.log('Unsolicited', TLVParser(buf))
    for toks in ast:
        if toks[0] == 'setnad':
            conn.setnad(toks[1])
            log.loginfo('Set NAD to', toks[1])
        elif toks[0] == '#':
            log.loginfo("Comment:", str(toks[1]).strip())
        elif toks[0] == 'setdevice':
            log.loginfo('Set device to', toks[1])
        elif toks[0] == 'flush':
            log.loginfo('Flush comms')
        elif toks[0] == 'clearlocalpool':
            pool.clear()
            localtempl.clear()
            log.loginfo('Clear local pool')
        elif toks[0] == 'pause':
            log.loginfo('Pause for', toks[1], 'sec')
            time.sleep(toks[1])
        elif toks[0] == 'send':
            __send_command(toks, conn, pool, localtempl, log)
        elif toks[0] == 'abortsw1sw2':
            abort_sw1sw2 = toks[1]
            log.loginfo('Abort SW1SW2 =', abort_sw1sw2)
        elif toks[0] == 'wait':
            __wait_command(toks, conn, log, abort_sw1sw2)
        elif toks[0] == 'prompt':
            log.loginfo('Prompt message:', str(" ").join(toks[1].asList()))
            __wait_command(toks, conn, log, abort_sw1sw2)
        elif toks[0] == 'storelocaltag':
            pool = __storetag_command(toks, pool)
        elif toks[0] == 'appendlocal':
            tpl, data = __appendlocal_command(toks, pool)
            localtempl[tpl] = data
        elif toks[0] == 'senddirect':
            __senddirect_command(toks, conn, log)
        elif toks[0] == 'putfile':
            __putfile_command(toks, conn, log)
        elif toks[0] == 'updatefile':
            __updatefile_command(toks, conn, log)
        elif toks[0] == 'getfile':
            __getfile_command(toks, conn, log)
        else:
            log.logerr('Unknown tokens', str(toks))
            raise exc.logicalException('Unknown tokens in script')
Ejemplo n.º 4
0
def __send_command(toks, conn, pool, localtempl, log):
    b4list = toks.asList()[1:5]
    print(toks)
    if len(toks) == 5:
        conn.send(b4list)
    elif len(toks) == 6 or len(toks) == 7:
        tag = toks.get("tag")
        data = toks.get("hex")
        lebyte = toks.get("le")
        if lebyte != None: lebyte = lebyte[0]
        if data != None and len(data[0]) > 0:
            print((data))
            data = bytearray(sum(data[0], []))
            conn.send(b4list, data, le_byte=lebyte)
        elif tag != None:
            tagdata = pool.getTagData(tag[0])
            if tag[0][0] in localtempl:
                conn.send(b4list, localtempl[tag[0][0]], le_byte=lebyte)
            elif tagdata != None:
                conn.send(b4list, [tag, data], le_byte=lebyte)
            else:
                log.logerr("Unable to find tag or template", tag)
                raise exc.logicalException('Unable to find tag or template')
        else:
            conn.send(b4list, le_byte=lebyte)
    else:
        raise exc.invtypeException("Unknown parameters send command")
Ejemplo n.º 5
0
def getfile(conn, log, remote_fn, local_fn=None, progress=None):
    from struct import pack
    conn.send([0x00, 0xA4, 0x04, 0x00], remote_fn.upper())
    status, buf, uns = conn.receive()
    if status != 0x9000:
        raise exc.invResponseException('Cannot select file ' + remote_fn,
                                       status)
    if progress != None:
        log.loginfo('INFO: Binary stream data not included in log')
        enable_logging = False
    else:
        enable_logging = True
    tlv = TLVParser(buf)
    fileSize = tlv.getTag(0x80, tlv.CONVERT_INT)[0]
    if fileSize == 0:
        raise exc.logicalException('File with name ' + remote_fn +
                                   " doesn't exists")
    now = strftime("%Y%m%d%H%M%S")
    if local_fn == None:
        local_fn = remote_fn + '_' + now
    packetLen = 248
    log.log('Downloading File', remote_fn, 'Length', fileSize, 'as localfile',
            local_fn)
    prevPercent = -1
    with open(local_fn, 'wb') as f:
        offset = 0
        while offset < fileSize:
            d1 = (offset & 0xFF)
            P2 = ((offset & 0xFF00) >> 8) & 0xFF
            P1 = ((offset & 0xFF0000) >> 16) & 0xFF
            P1 |= 0x80
            sendData = pack("B", d1)
            conn.send([0x00, 0xB0, P1, P2],
                      sendData,
                      log_packet=enable_logging)
            status, buf, uns = conn.receive_raw(log_packet=enable_logging)
            if status != 0x9000:
                raise exc.invResponseException('Error during get file', status)
            offset += len(buf)
            f.write(buf)
            if hasattr(progress, '__call__'):
                percent = round(offset / fileSize, 2)
                if percent != prevPercent: progress(percent)
                prevPercent = percent
    log.log('Download done')
    return local_fn
Ejemplo n.º 6
0
def updatefile(conn, log, fn, remote_fn=None, signature=False, progress=None):
    if not os.path.isfile(fn):
        raise exc.logicalException('File ' + fn + ' doesnt exist!')
    from struct import pack
    if remote_fn == None: remote_fn = os.path.basename(fn)
    log.log('Uploading file ', fn, ' as ', remote_fn)
    fileSize = os.path.getsize(fn)
    size = hex(fileSize)[2:]
    while len(size) < 8:
        size = '0' + size
    log.log('size ', size)

    c_tag = tagStorage()
    c_tag.store((0x84), remote_fn.lower())
    c_tag.store((0x80), bytearray.fromhex(size))
    conn.send([0x00, 0xA5, 0x05, 0x81], c_tag.getTemplate(0x6F))
    status, buf, uns = conn.receive()
    if status != 0x9000:
        raise exc.invResponseException('Cannot upload file ' + fn, status)
    dataCnt = 0
    prevPercent = -1
    with open(fn, 'rb') as f:
        while True:
            readData = f.read(1024)
            readSize = len(readData)
            if (readSize == 0): break
            dataCnt += readSize
            sendData = bytearray(readData)
            conn.send_raw(sendData)
            if hasattr(progress, '__call__'):
                percent = round(dataCnt / fileSize, 2)
                if percent != prevPercent: progress(percent)
                prevPercent = percent

    log.log('Done, waiting for confirmation')
    # We're done, wait for response
    status, buf, uns = conn.receive()
Ejemplo n.º 7
0
 def __receive( self, parse, timeout, log_packet, se=False ):
         if timeout == None:
             timeout = self.__timeout
             req_set = False
         else:
             req_set = True
         if timeout !=None and timeout > 0 and req_set == True:
             if self.__raw_socket != None:
                 self.__raw_socket.settimeout( timeout )
             else:
                 self.__connection.setTimeout( timeout )
         from testharness.exceptions import logicalException
         data_frame = bytearray()
         is_unsolicited = None
         log_out_frame_buf = []
         while True:
                 rxbuf = bytearray()
                 while True:
                         read_value = self.__connection.read( 3 )
                         if timeout!=None and timeout > 0 and len( read_value )==0:
                             raise timeoutException()
                         rxbuf += read_value
                         if len(rxbuf) < 3: continue
                         nad =  rxbuf[0]
                         pcb =  rxbuf[1]
                         blen = rxbuf[2]
                         if is_unsolicited==None: is_unsolicited = True if pcb&0x40 else False
                         break
                 rxbuf = bytearray()
                 while True:
                         read_value = self.__connection.read( blen )
                         if timeout!=None and timeout > 0 and len( read_value )==0:
                             raise timeoutException()
                         rxbuf += read_value
                         if len(rxbuf) >= blen: break
                 while True:
                         lrc = self.__connection.read( 1 )
                         if timeout!=None and timeout > 0 and len( lrc )==0:
                             raise timeoutException()
                         if len( lrc ) >= 1: break
                 calc_lrc = tutil.lrccalc( nad, pcb, blen, rxbuf, lrc )
                 if calc_lrc != 0 and nad == self.__nad:
                         raise logicalException('Invalid LRC')
                 if nad != self.__nad:
                         rxbuf = bytearray()
                         continue
                 data_frame += rxbuf
                 log_out_frame_buf += [ bytearray( [nad] ) +  bytearray( [pcb] ) +  bytearray( [blen] ) + data_frame + lrc ]
                 if pcb&1 == 0: break 
         from struct import unpack
         from binascii import hexlify
         tags=None
         slog = getSyslog()
         if se and ( pcb & 2):
             data_frame = bytearray(self.tdes.decrypt( data_frame ) )
             slog.log("Received seq num: ",str(hexlify(  data_frame[ len(data_frame) - 4: ] )))
             # if se take response except last 4 bytes
             data_frame = data_frame[:-4]
         slog.loginfo("IN: " + str(hexlify(data_frame)))
         if parse:
             tlvp = TLVPrepare()
             tags = tlvp.parse_received_data( data_frame )
         else:
             tags = data_frame[:-2]
         b_status = unpack("!H",data_frame[-2:])[0] 
         if log_packet:
             self.log_message('recv', data_frame[:-2] , log_out_frame_buf, tags, b_status)
         return b_status, tags , is_unsolicited