//=================================================================================================
axCharA axDataBufferReader::ReadCharA()
{
	axCharA cResultA;
	ReadBytes((axBytes)&cResultA, axSizeOf(axCharA));
	return cResultA;
}
Esempio n. 2
0
/* if we can't determine it, we will return true */
static int
is_gui_app (char *exe)
{
  HANDLE hImage;

  DWORD  bytes;
  DWORD  iSection;
  DWORD  SectionOffset;
  DWORD  CoffHeaderOffset;
  DWORD  MoreDosHeader[16];
  CHAR   *file;
  size_t nlen;

  ULONG  ntSignature;

  IMAGE_DOS_HEADER      image_dos_header;
  IMAGE_FILE_HEADER     image_file_header;
  IMAGE_OPTIONAL_HEADER image_optional_header;
  IMAGE_SECTION_HEADER  image_section_header;

  /*
   *  Open the reference file.
  */
  nlen = strlen (exe);
  file = exe;
  if (nlen > 2) {
    if (exe[0] == '"') {
      /* remove quotes */
      nlen -= 2;
      file = malloc ((nlen + 1) * sizeof (char));
      memcpy (file, &exe[1], nlen);
      file [nlen] = '\0';
    }
  }
  hImage = CreateFile(file,
                      GENERIC_READ,
                      FILE_SHARE_READ,
                      NULL,
                      OPEN_EXISTING,
                      FILE_ATTRIBUTE_NORMAL,
                      NULL);

  if (file != exe) {
    free (file);
  }

  if (INVALID_HANDLE_VALUE == hImage)
    {
      report_file_error ("Could not open exe: ", Qnil);
      report_file_error (exe, Qnil);
      report_file_error ("\n", Qnil);
      CloseHandle (hImage);
      return -1;
    }

  /*
   *  Read the MS-DOS image header.
   */
  ReadBytes(hImage, &image_dos_header, sizeof(IMAGE_DOS_HEADER));

  if (IMAGE_DOS_SIGNATURE != image_dos_header.e_magic)
    {
      report_file_error("Sorry, I do not understand this file.\n", Qnil);
      CloseHandle (hImage);
      return -1;
    }

  /*
   *  Read more MS-DOS header.       */
  ReadBytes(hImage, MoreDosHeader, sizeof(MoreDosHeader));
   /*
   *  Get actual COFF header.
   */
  CoffHeaderOffset = AbsoluteSeek(hImage, image_dos_header.e_lfanew) +
                     sizeof(ULONG);
  if (CoffHeaderOffset < 0) {
    CloseHandle (hImage);
    return -1;
  }

  ReadBytes (hImage, &ntSignature, sizeof(ULONG));

  if (IMAGE_NT_SIGNATURE != ntSignature)
    {
      report_file_error ("Missing NT signature. Unknown file type.\n", Qnil);
      CloseHandle (hImage);
      return -1;
    }

  SectionOffset = CoffHeaderOffset + IMAGE_SIZEOF_FILE_HEADER +
    IMAGE_SIZEOF_NT_OPTIONAL_HEADER;

  ReadBytes(hImage, &image_file_header, IMAGE_SIZEOF_FILE_HEADER);

  /*
   *  Read optional header.
   */
  ReadBytes(hImage,
            &image_optional_header,
            IMAGE_SIZEOF_NT_OPTIONAL_HEADER);

  CloseHandle (hImage);

  switch (image_optional_header.Subsystem)
    {
    case IMAGE_SUBSYSTEM_UNKNOWN:
        return 1;
        break;

    case IMAGE_SUBSYSTEM_NATIVE:
        return 1;
        break;

    case IMAGE_SUBSYSTEM_WINDOWS_GUI:
        return 1;
        break;

    case IMAGE_SUBSYSTEM_WINDOWS_CUI:
        return 0;
        break;

    case IMAGE_SUBSYSTEM_OS2_CUI:
        return 0;
        break;

    case IMAGE_SUBSYSTEM_POSIX_CUI:
        return 0;
        break;

    default:
        /* Unknown, return GUI app to be preservative: if yes, it will be
           correctly launched, if no, it will be launched, and a console will
           be also displayed, which is not a big deal */
        return 1;
        break;
    }

}
Esempio n. 3
0
int16 ModVDMX(CONST_TTFACC_FILEBUFFERINFO * pInputBufferInfo, 
              TTFACC_FILEBUFFERINFO * pOutputBufferInfo,
              CONST uint16 usFormat,
              uint32 *pulNewOutOffset)
{
VDMX Vdmx;
uint32 ulSrcOffset; /* offset to Src VDMX table */
uint32 ulSrcLength; /* length of Src VDMX table */
uint32 ulDestOffset; /* offset to Dest VDMX table */
uint32 ulDestLength; /* length of Dest VDMX table */
uint32 ulSrcOffsetRatios;   /* absolute offset to Ratios in Src file */
uint32 ulSrcOffsetOffsets;  /* absolute offset to Offsets in Src file */
uint32 ulSrcOffsetGroups;   /* absolute offset to Groups in Src file */
uint32 ulDestOffsetRatios;  /* absolute offset to Ratios in Dest file */
uint32 ulDestOffsetOffsets; /* absolute offset to Offsets in Dest file */
uint32 ulDestOffsetGroups;  /* absolute offset to Groups in Dest file */
uint16 usCurrGroupSrcOffset; /* relative offset from beginning of VDMX table */
uint16 usCurrGroupDestOffset; /* relative offset from beginning of VDMX table */
uint32 ulCurrGroupDestOffset=0; /* relative offset from beginning of VDMX table - long value */
uint16 usGroupDestOffset; /* relative offset from beginning of VDMX table, local copy for writing */
uint16 ----cRatioIndex,usDestRatioIndex;
uint16 i;
uint16 usBytesRead;
uint16 usBytesWritten;
uint32 ulBytesRead;
int16 errCode=NO_ERROR;
VDMXRatio *SrcRatioArray=NULL;
int8 *KeepSrcRatioArray = NULL;   /* parallel array to SrcRatioArray */
VDMXGroup GroupHeader;
uint8 * pGroupBuffer=NULL;
uint32 ulGroupBufferLength; /* total length of the Group Buffer (from source file) */
uint32 ulGroupLength; /* length of individual group to be read */
uint16 usGroupCount = 0; 
uint16 usKeepRatioCount = 0;
uint16 usRatioSize;
uint16 xRatio, yRatio; /* for reducing the ratios */
int16 Found1to1; 
GROUPOFFSETRECORDKEEPER keeper; 
TTFACC_FILEBUFFERINFO * pUnCONSTInputBufferInfo;

    if (usFormat == TTFDELTA_DELTA)  /* only formats for which this is not valid */
    {
        MarkTableForDeletion(pOutputBufferInfo, VDMX_TAG);
        return errCode;
    }

    pUnCONSTInputBufferInfo = (TTFACC_FILEBUFFERINFO *) pInputBufferInfo; /* used for Read functions ONLY. Not for Write */
/* get input buffer information */
    ulSrcOffset = TTTableOffset( pUnCONSTInputBufferInfo, VDMX_TAG );
    if ( ulSrcOffset == 0L )
        return NO_ERROR;
    ulSrcLength = TTTableLength( pUnCONSTInputBufferInfo, VDMX_TAG );
    if ( ulSrcLength == 0L )
    {
        MarkTableForDeletion(pOutputBufferInfo, VDMX_TAG);
        return NO_ERROR;
    }
    /* get output buffer information */
    if ((errCode = ZeroLongWordAlign(pOutputBufferInfo, *pulNewOutOffset, &ulDestOffset)) != NO_ERROR)
        return errCode;

    if ((errCode = ReadGeneric( pUnCONSTInputBufferInfo, (uint8 *) &Vdmx, SIZEOF_VDMX, VDMX_CONTROL, ulSrcOffset, &usBytesRead )) != NO_ERROR)
        return errCode;
    if (Vdmx.numRatios == 0)
    {
        MarkTableForDeletion(pOutputBufferInfo, VDMX_TAG);
        return NO_ERROR;
    }


    ulSrcOffsetRatios = ulSrcOffset + usBytesRead;
    ulSrcOffsetOffsets = ulSrcOffsetRatios + GetGenericSize(VDMXRATIO_CONTROL) * Vdmx.numRatios;
    ulSrcOffsetGroups = ulSrcOffsetOffsets + sizeof(uint16) * Vdmx.numRatios;
    memset(&keeper, 0, sizeof(keeper));

    SrcRatioArray = (VDMXRatio *)Mem_Alloc(Vdmx.numRatios * sizeof(VDMXRatio));
    if (SrcRatioArray == NULL)
        errCode = ERR_MEM;
    else
    {
        KeepSrcRatioArray = (int8 *)Mem_Alloc(Vdmx.numRatios * sizeof(int8));
        if (KeepSrcRatioArray == NULL)
            errCode = ERR_MEM;
        else
            errCode = ReadGenericRepeat(pUnCONSTInputBufferInfo, (uint8 *) SrcRatioArray, VDMXRATIO_CONTROL, ulSrcOffsetRatios, &ulBytesRead, Vdmx.numRatios, SIZEOF_VDMXRATIO );
    }

    while (errCode == NO_ERROR)     /* while is so we can break out. Only go once through */
    {
        Found1to1 = FALSE;
        for (i = 0; i < Vdmx.numRatios ; ++i)    /* keep all 1:1 aspect ratios */
        {
            KeepSrcRatioArray[i] = 1; /* assume we'll keep it */
            xRatio = SrcRatioArray[i].xRatio;
            yRatio = SrcRatioArray[i].yStartRatio;
            ReduceRatio(&xRatio,&yRatio);
            if (xRatio == yRatio)
            {
                if (SrcRatioArray[i].xRatio == 0)   /* anything after 0:0 is ignored */
                {
                    if (!Found1to1) /* need to keep this one */
                        ++usKeepRatioCount;
                    break;
                }
                if (Found1to1)  /* already have one */
                    KeepSrcRatioArray[i] = 0;  /* don't keep this one */
                else
                {
                    Found1to1 = TRUE;
                    ++usKeepRatioCount;
                }
            }
            else if (xRatio == EGA_X_RATIO && yRatio == EGA_Y_RATIO)
                KeepSrcRatioArray[i] = 0;  /* don't keep this one */
            else
                ++usKeepRatioCount;
        }

        if ((usKeepRatioCount == 0) || (usKeepRatioCount == Vdmx.numRatios))
        {                       /* don't change a thing */
            Mem_Free(SrcRatioArray);
            Mem_Free(KeepSrcRatioArray);
            return CopyTableOver(pOutputBufferInfo, pInputBufferInfo, VDMX_TAG, pulNewOutOffset);
        }
        ulDestOffsetRatios = ulDestOffset + usBytesRead;
        /* figure out offset for the Offset array */
        ulDestOffsetOffsets = ulDestOffsetRatios + GetGenericSize(VDMXRATIO_CONTROL) * usKeepRatioCount;
        ulDestOffsetGroups = ulDestOffsetOffsets + sizeof(uint16) * usKeepRatioCount;
        usRatioSize = GetGenericSize(VDMXRATIO_CONTROL);
        ulCurrGroupDestOffset = ulDestOffsetGroups - ulDestOffset; /* calculate offset from start of VDMX table */
        if ((errCode = InitGroupOffsetArray(&keeper,usKeepRatioCount)) != NO_ERROR)  /* initialize structure to track offset re-use */ 
            break;
        ulGroupBufferLength = ulSrcLength - (ulSrcOffsetGroups - ulSrcOffset);  /* calculate the length of the group section */
        pGroupBuffer = (uint8 *)Mem_Alloc(ulGroupBufferLength); /* allocate buffer the size of the group buffer */
        if (pGroupBuffer == NULL)
        {
            errCode = ERR_MEM;
            break;
        }
        
        for (----cRatioIndex = usDestRatioIndex = 0; ----cRatioIndex < Vdmx.numRatios && usDestRatioIndex < usKeepRatioCount; ++----cRatioIndex)     /* keep all 1:1 aspect ratios */
        {
            if (KeepSrcRatioArray[----cRatioIndex] == 1)
            {
                /* write out the Ratio to the proper location */
                if ((errCode = WriteGeneric(pOutputBufferInfo, (uint8 *) &(SrcRatioArray[----cRatioIndex]), SIZEOF_VDMXRATIO, VDMXRATIO_CONTROL, ulDestOffsetRatios + (usDestRatioIndex * usRatioSize), &usBytesWritten)) != NO_ERROR)
                    break;
                /* now read the offset to the group */
                if ((errCode = ReadWord(pUnCONSTInputBufferInfo, &usCurrGroupSrcOffset, ulSrcOffsetOffsets + (----cRatioIndex * sizeof(uint16)) )) != NO_ERROR)
                    break;
                /* check if offset already used */
                if ((usGroupDestOffset = LookupGroupOffset(&keeper, usCurrGroupSrcOffset)) == 0)  /* not there already */
                {
                    if (ulCurrGroupDestOffset > USHRT_MAX)  /* check if will fit in unsigned short */
                    {
                        errCode = ERR_INVALID_VDMX;
                        break;
                    }
                    usCurrGroupDestOffset = (uint16) ulCurrGroupDestOffset;  /* already checked if in range */
                    /* need to register the old and new group offsets */
                    if ((errCode = RecordGroupOffset(&keeper, usCurrGroupSrcOffset, usCurrGroupDestOffset)) != NO_ERROR)
                        break;

                    usGroupDestOffset = usCurrGroupDestOffset;
                    /* need to copy the group data over */
                    if ((errCode = ReadGeneric(pUnCONSTInputBufferInfo, (uint8 *) &GroupHeader, SIZEOF_VDMXGROUP, VDMXGROUP_CONTROL, ulSrcOffset + usCurrGroupSrcOffset, &usBytesRead)) != NO_ERROR)
                        break;
 
                    ulGroupLength =  usBytesRead + (GroupHeader.recs * GetGenericSize(VDMXVTABLE_CONTROL));
                    /* read the group data into a buffer */
                    if (ulGroupLength > ulGroupBufferLength)
                    {
                        errCode = ERR_INVALID_VDMX; /* error in data! */
                        break;
                    }
                    if ((errCode = ReadBytes(pUnCONSTInputBufferInfo, (uint8 *) pGroupBuffer, ulSrcOffset + usCurrGroupSrcOffset, ulGroupLength)) != NO_ERROR)
                        break;
                    /* and write them to the output buffer */
                    if ((errCode = WriteBytes(pOutputBufferInfo, (uint8 *) pGroupBuffer, ulDestOffset + usCurrGroupDestOffset, ulGroupLength)) != NO_ERROR)
                        break;
                    ++usGroupCount;
                    /* increment our CurrGroupDestOffset value for next time around */
                    ulCurrGroupDestOffset = usCurrGroupDestOffset + ulGroupLength;
                }
                /* now write out that relative offset value */
                if ((errCode = WriteWord(pOutputBufferInfo, usGroupDestOffset, ulDestOffsetOffsets + (usDestRatioIndex * sizeof(uint16)))) != NO_ERROR)
                    break;

                ++usDestRatioIndex; /* increment in dest array */
            }
        }
        break; /* out of while */
    }
    if (errCode == NO_ERROR)
    {
        Vdmx.numRatios = usKeepRatioCount;
        Vdmx.numRecs = usGroupCount;
        errCode = WriteGeneric( pOutputBufferInfo, (uint8 *) &Vdmx, SIZEOF_VDMX, VDMX_CONTROL, ulDestOffset, &usBytesWritten );
    }
    
    if (errCode == NO_ERROR)
    {
        ulDestLength = ulCurrGroupDestOffset; /* this is the size of the table */
        errCode = UpdateDirEntryAll( pOutputBufferInfo, VDMX_TAG, ulDestLength, ulDestOffset );
        *pulNewOutOffset = ulDestOffset + ulDestLength;
    }
 
    FreeGroupOffsetArray(&keeper);  /* free up structure to track offset re-use */ 

    Mem_Free(pGroupBuffer);

    Mem_Free(KeepSrcRatioArray);
    Mem_Free(SrcRatioArray);
    return errCode;
}
Esempio n. 4
0
void AuthSocket::HandleProof()
{
    if(!m_account || !HasBytes(sizeof(sAuthLogonProof_C)))
        return ;

    sLog.outDebug("[AuthLogonProof] Interleaving and checking proof...");

    sAuthLogonProof_C lp;
    ReadBytes((u8*)&lp, sizeof(sAuthLogonProof_C));

    BigNumber A;
    A.SetBinary(lp.A, 32);

    Sha1Hash sha;
    sha.UpdateBigNumbers(&A, &B, 0);
    sha.Finalize();

    BigNumber u;
    u.SetBinary(sha.GetDigest(), 20);
    
    BigNumber S = (A * (v.ModExp(u, N))).ModExp(b, N);
    uint8 t[32];
    uint8 t1[16];
    uint8 vK[40];
    memcpy(t, S.AsByteArray(), 32);
    for (int i = 0; i < 16; i++)
    {
        t1[i] = t[i*2];
    }
    sha.Initialize();
    sha.UpdateData(t1, 16);
    sha.Finalize();
    for (int i = 0; i < 20; i++)
    {
        vK[i*2] = sha.GetDigest()[i];
    }
    for (int i = 0; i < 16; i++)
    {
        t1[i] = t[i*2+1];
    }
    sha.Initialize();
    sha.UpdateData(t1, 16);
    sha.Finalize();
    for (int i = 0; i < 20; i++)
    {
        vK[i*2+1] = sha.GetDigest()[i];
    }
    m_sessionkey.SetBinary(vK, 40);

    uint8 hash[20];

    sha.Initialize();
    sha.UpdateBigNumbers(&N, NULL);
    sha.Finalize();
    memcpy(hash, sha.GetDigest(), 20);
    sha.Initialize();
    sha.UpdateBigNumbers(&g, NULL);
    sha.Finalize();
    for (int i = 0; i < 20; i++)
    {
        hash[i] ^= sha.GetDigest()[i];
    }
    BigNumber t3;
    t3.SetBinary(hash, 20);

    sha.Initialize();
    sha.UpdateData(m_account->Username);
    sha.Finalize();

    BigNumber t4;
    t4.SetBinary(sha.GetDigest(), 20);

    sha.Initialize();
    sha.UpdateBigNumbers(&t3, &t4, &s, &A, &B, &m_sessionkey, NULL);
    sha.Finalize();

    BigNumber M;
    M.SetBinary(sha.GetDigest(), 20);

    // Compare M1 values.
    if(memcmp(lp.M1, M.AsByteArray(), 20) != 0)
    {
        // Authentication failed.
        //SendProofError(4, 0);
	SendChallengeError(CE_NO_ACCOUNT);
        sLog.outDebug("[AuthLogonProof] M1 values don't match.");
        return;
    }

    // Store sessionkey
    BigNumber * bs = new BigNumber(m_sessionkey);
    sInfoCore.SetSessionKey(m_account->AccountId, bs);

    // let the client know
    sha.Initialize();
    sha.UpdateBigNumbers(&A, &M, &m_sessionkey, 0);
    sha.Finalize();

    SendProofError(0, sha.GetDigest());
    sLog.outDebug("[AuthLogonProof] Authentication Success.");

    // we're authenticated now :)
    m_authenticated = true;



}
Esempio n. 5
0
HRESULT DataTargetReader::Read32(ULONG32* pUlong32Value)
{
    Align(4);
    return ReadBytes((BYTE*)pUlong32Value, sizeof(ULONG32));
}
Esempio n. 6
0
UT_uint16 IE_ImpGraphic_BMP::Read2Bytes(UT_ByteBuf* pBB, 
									    UT_uint32 offset)
{
	return ( static_cast<const UT_uint16>(ReadBytes(pBB,offset,2) ));
}
Esempio n. 7
0
bool LoadWavFromFileInMemory(const u8 *fileData, size_t numBytes, std::vector<u8> &dst, bool *isStereo, bool *is16Bit, int *frequency)
{
    if (!fileData || numBytes == 0)
    {
        LogError("Null input data passed in");
        return false;
    }

    if (!isStereo || !is16Bit || !frequency)
    {
        LogError("Outputs not set");
        return false;
    }

    unsigned int index = 0;
    
    u8 riff_text[4];
    ReadBytes(riff_text, fileData, index, 4);
    if (!!memcmp(riff_text, "RIFF", 4))
    {
        LogError("No RIFF chunk in WAV data");
        return false;
    }
    if (index >= numBytes) 
        return false;

    ReadU32(fileData, index);
    u8 wave_text[4];
    ReadBytes(wave_text, fileData, index, 4);
    if (!!memcmp(wave_text, "WAVE", 4))
    {
        LogError("No WAVE chunk in WAV data");
        return false;
    }
    
    // Search for the fmt chunk
    for(;;)
    {
        if (index >= numBytes)
        {
            LogError("No fmt chunk in WAV data");
            return false;
        }
        u8 chunk_text[4]; 
        ReadBytes(chunk_text, fileData, index, 4);
        unsigned int chunk_size = ReadU32(fileData, index);
        if (!memcmp(chunk_text, "fmt ", 4))
            break;
        if (!chunk_size)
            return false;
        index += chunk_size;
    }
    
    if (index >= numBytes) 
        return false;

    u16 format = ReadU16(fileData, index);
    u16 channels = ReadU16(fileData, index);
    unsigned int sampleFrequency = ReadU32(fileData, index);
    /*unsigned int avgbytes =*/ ReadU32(fileData, index);
    /*unsigned int blockalign =*/ ReadU16(fileData, index);
    u16 bits = ReadU16(fileData, index);

    if (format != 1)
    {
        LogError("Sound is not PCM data");
        return false;
    }
    if (channels != 1 && channels != 2)
    {
        LogError("Sound is not either mono or stereo");
        return false;
    }
    if (bits != 8 && bits != 16)
    {
        LogError("Sound is not either 8bit or 16bit");
        return false;
    }
                            
    // Search for the data chunk
    unsigned int data_length = 0;
    for(;;)
    {
        if (index >= numBytes)
        {
            LogError("No data chunk in WAV data");
            return false;
        }
        u8 chunk_text[4]; 
        ReadBytes(chunk_text, fileData, index, 4);
        data_length = ReadU32(fileData, index);
        if (!memcmp(chunk_text, "data", 4))
            break;
        if (!data_length) return false;
        index += data_length;
    }        
    
    if (!data_length)
    {
        LogError("Zero numBytes data chunk in WAV data");
        return false;
    }
    
    std::ostringstream msg;
    msg << "Loaded WAV sound with " << channels << " channels " << bits << " bits, frequency " << sampleFrequency << " datasize " << data_length; 
    LogDebug(msg.str());
 
    dst.clear();
    dst.insert(dst.end(), &fileData[index], &fileData[index + data_length]);
    *isStereo = (channels == 2);
    *is16Bit = (bits == 16);
    *frequency = sampleFrequency;

    return true;
}
//=================================================================================================
axInt16 axDataBufferReader::ReadInt16()
{
	axInt16 i16Result;
	ReadBytes((axBytes)&i16Result, axSizeOf(axInt16));
	return i16Result;
}
Esempio n. 9
0
uint8_t RecvCommand() {
	uint8_t Cmd;
	char Username[32];
	uint8_t TargetUser = MAX_USERS+1;
	uint8_t DeviceType;
	uint16_t DeviceId;
	uint16_t AlarmId;
	uint8_t NewDevice;
	uint8_t UserId;

	// Read in the one-byte command
	if (!ReadBytes((unsigned char *)&Cmd, 1)) {
		return(0);
	}

	switch (Cmd) {
		case CMD_POWER_OFF:
			SendResp(RESP_SUCCESS, NULL);
			return(0);
			break;

		case CMD_ADD_USER:
			if (!AddUser()) {
				SendResp(RESP_ADD_USER_FAILED, NULL);
				return(1);
			}
			SendResp(RESP_SUCCESS, NULL);
			break;

		case CMD_DEL_USER:
			if (!DelUser()) {
				SendResp(RESP_DEL_USER_FAILED, NULL);
				return(1);
			}
			SendResp(RESP_SUCCESS, NULL);
			break;

		case CMD_ADD_DEVICE:
			// Read in the device type
			if (!ReadBytes((unsigned char *)&DeviceType, 1)) {
				return(0);
			}
			
		        // Find the next available device slot
			if ((NewDevice = FindAvailableDevice()) >= MAX_DEVICES) {
				SendResp(RESP_INVALID_CMD, NULL);
				return(0);
			}
			
			switch (DeviceType) {
				case DEVICE_KEYPAD:
					if (!(DeviceId = NewGenericDevice(DeviceType, NewDevice))) {
						SendResp(RESP_ADD_DEVICE_FAILED, NULL);
						return(0);
					}
					break;
				case DEVICE_SWIPE:
					if (!(DeviceId = NewGenericDevice(DeviceType, NewDevice))) {
						SendResp(RESP_ADD_DEVICE_FAILED, NULL);
						return(0);
					}
					break;
				case DEVICE_CONTACT:
					if (!(DeviceId = NewContact(NewDevice))) {
						SendResp(RESP_ADD_DEVICE_FAILED, NULL);
						return(0);
					}
					break;
				case DEVICE_MOTION:
					if (!(DeviceId = NewMotion(NewDevice))) {
						SendResp(RESP_ADD_DEVICE_FAILED, NULL);
						return(0);
					}
					break;
				case DEVICE_HEAT:
					if (!(DeviceId = NewHeat(NewDevice))) {
						SendResp(RESP_ADD_DEVICE_FAILED, NULL);
						return(0);
					}
					break;
				case DEVICE_SMOKE:
					if (!(DeviceId = NewSmoke(NewDevice))) {
						SendResp(RESP_ADD_DEVICE_FAILED, NULL);
						return(0);
					}
					break;
				case DEVICE_ALARM:
					if (!(DeviceId = NewGenericDevice(DeviceType, NewDevice))) {
						SendResp(RESP_ADD_DEVICE_FAILED, NULL);
						return(1);
					}
					break;
				default:
					SendResp(RESP_ADD_DEVICE_FAILED, NULL);
					break;
			}
			// Send success along with the generated DeviceId
			SendResp(RESP_SUCCESS, (unsigned char *)&DeviceId);
			break;	

		case CMD_DEL_DEVICE:
			// Read in the device id
			if (!ReadBytes((unsigned char *)&DeviceId, 2)) {
				return(0);
			}
			
			if (!DeleteDevice(DeviceId)) {
				SendResp(RESP_DEL_DEVICE_FAILED, NULL);
				return(1);
			}
			SendResp(RESP_SUCCESS, NULL);
			break;

		case CMD_GRANT_ACCESS:
			// Read in the device id
			if (!ReadBytes((unsigned char *)&DeviceId, 2)) {
				return(0);
			}
			
			// Read in the user id
			if (!ReadBytes((unsigned char *)&UserId, 1)) {
				return(0);
			}
			
			if (!GrantAccess(DeviceId, UserId)) {
				SendResp(RESP_GRANT_FAILED, NULL);
				return(1);
			}
			SendResp(RESP_SUCCESS, NULL);
			break;

		case CMD_UPDATE_DEVICE:
			// Read in the device id
			if (!ReadBytes((unsigned char *)&DeviceId, 2)) {
				return(0);
			}

			if (!UpdateDevice(DeviceId)) {
				SendResp(RESP_UPDATE_DEVICE_FAILED, NULL);
				return(1);
			}
			SendResp(RESP_SUCCESS, NULL);
			break;

		case CMD_ADD_DEVICE_TO_ALARM:
			// Read in the device id
			if (!ReadBytes((unsigned char *)&DeviceId, 2)) {
				return(0);
			}
			
			// Read in the alarm id
			if (!ReadBytes((unsigned char *)&AlarmId, 2)) {
				return(0);
			}

			if (!AddDeviceToAlarm(DeviceId, AlarmId)) {
				SendResp(RESP_ADD_DEVICE_TO_ALARM_FAILED, NULL);
				return(0);
			}

			SendResp(RESP_SUCCESS, NULL);
			break;

		case CMD_LIST_ALARM_CODES:
			// Read in the device id
			if (!ReadBytes((unsigned char *)&DeviceId, 2)) {
				return(0);
			}
			
			if (!ListValidAlarmCodes(DeviceId)) {
				SendResp(RESP_INVALID_CMD, NULL);
				return(0);
			}

			break;

		default:
			SendResp(RESP_INVALID_CMD, NULL);
			return(1);
			break;
	}

	return(1);
}
//=================================================================================================
axInt8 axDataBufferReader::ReadInt8()
{
	axInt8 i8Result;
	ReadBytes((axBytes)&i8Result, axSizeOf(axInt8));
	return i8Result;
}
//=================================================================================================
axUInt8 axDataBufferReader::ReadUInt8()
{
	axUInt8 u8Result;
	ReadBytes((axBytes)&u8Result, axSizeOf(axUInt8));
	return u8Result;
}
//=================================================================================================
axUInt axDataBufferReader::ReadUInt()
{
	axUInt uResult;
	ReadBytes((axBytes)&uResult, axSizeOf(axUInt));
	return uResult;
}
//=================================================================================================
axInt axDataBufferReader::ReadInt()
{
	axInt iResult;
	ReadBytes((axBytes)&iResult, axSizeOf(axInt));
	return iResult;
}
//=================================================================================================
axCharW axDataBufferReader::ReadCharW()
{
	axCharW cResultW;
	ReadBytes((axBytes)&cResultW, axSizeOf(axCharW));
	return cResultW;
}
Esempio n. 15
0
int main(void) {
	unsigned int type2_addr;
	unsigned int type2_size;
	unsigned int type2_length;
	unsigned char Frame[MAX_FRAME_SIZE];
	uint8_t Len;
	uint8_t EchoLen;
	pL2Hdr pL2 = (pL2Hdr)Frame;
	uint8_t i;
	fd_set readfds;
	int readyfds;
	struct timeval timeout;
	unsigned char *magic_bytes;

	// negotiate a Type2 POV with the Competition Framework
	NegotiateType2Pov(&type2_addr, &type2_size, &type2_length);

	// force the pov to sleep letting the router and cb_3 processes
	// exchange their echo packets so that SendQueue[0] has the desired
	// Frame data
	FD_ZERO(&readfds);
	FD_SET(STDIN, &readfds);
	timeout.tv_sec = 2;
	timeout.tv_usec = 0;
	fdwait(STDIN+1, &readfds, NULL, &timeout, NULL);

	// send 13 gratuitous ADP packets for different L3Addr's
	uint32_t L3Addr = 0x0a010110;
	for (i = 0; i < 13; i++, L3Addr++) {
		bzero(Frame, MAX_FRAME_SIZE);
		Len = BuildAdpResponse(L3Addr, 0x1001, 0x0001, 0x1000, 0, Frame);
		SendBytes(STDOUT, Frame, Len);
	}

	// send one more ADP which will overwrite SendQueue[0]
	//
	// the L3addr of the ADP header should point to a L3Addr that
	// has been previously populated in the router's ADP cache
	//
	// the L2Addr of the ADP header should overwrite the 1-byte Valid
	// with a non-zero value and the 1-byte Age field with 0xfe.
	bzero(Frame, MAX_FRAME_SIZE);
	Len = BuildAdpResponse(0x0a010102, 0x0001, 0x0001, 0x1000, 0, Frame);
	//                                   ^ ^
	//                                Age| |Valid
	SendBytes(STDOUT, Frame, Len);

	// Send enough packets to the original L3Addr we populated in the router's
	// ADP to cause it to age out.
	// The router will forward it back to VLAN 1, but to an unknown unicast L2Addr
	// so the switch will drop it
	for (i = 0; i < 8; i++) {
		bzero(Frame, MAX_FRAME_SIZE);
	        BuildL4Segment(ECHO_L4ADDR, 0x41, (unsigned char *)"AA", 2, Frame);
	        BuildL3Packet(L3Addr-1, 0x0a010102, Frame);
	        EchoLen = BuildL2Frame(0x0001, 0x1000, 0, Frame);
	        SendBytes(STDOUT, Frame, EchoLen);
	}

	// Finally, create ADP entry for the addr we over-wrote
	// allowing the queued packet to be sent
	bzero(Frame, MAX_FRAME_SIZE);
	Len = BuildAdpResponse(0x0a010102, 0x1000, 0x0001, 0x1000, 0, Frame);
	SendBytes(STDOUT, Frame, Len);

	// cgc_read in the ADP frame that'll be sent before the target frame
	bzero(Frame, MAX_FRAME_SIZE);
	ReadBytes(STDIN, Frame, sizeof(L2Hdr)+sizeof(L2Adjacency)+4);
	
	// see if we have a packet to cgc_read 
	FD_ZERO(&readfds);
	FD_SET(STDIN, &readfds);
	timeout.tv_sec = 2;
	timeout.tv_usec = 0;
	if (fdwait(STDIN+1, &readfds, NULL, &timeout, &readyfds) != 0) {
		SendBytes(STDOUT, (unsigned char *)"diedie!", 7);
		bzero(Frame, MAX_FRAME_SIZE);
		SendBytes(FRAMEWORK, Frame, 4);
		_terminate(0);	
	}
	if (readyfds == 0) {
		SendBytes(STDOUT, (unsigned char *)"diedie!", 7);
		bzero(Frame, MAX_FRAME_SIZE);
		SendBytes(FRAMEWORK, Frame, 4);
		_terminate(0);	
	}

	// cgc_read the forwarded frame
	bzero(Frame, MAX_FRAME_SIZE);
	ReadBytes(STDIN, Frame, sizeof(L2Hdr)+sizeof(L3Hdr)+sizeof(L4Hdr)+4+4);
	
	// send the recovered page bytes to the competition framework
	magic_bytes = Frame+sizeof(L2Hdr)+sizeof(L3Hdr)+sizeof(L4Hdr);
	SendBytes(FRAMEWORK, magic_bytes, 4);

}
Esempio n. 16
0
Bool16 QTAtom::ReadInt8(UInt64 Offset, UInt8 * Datum)
{
    //
    // Read and return.
    return ReadBytes(Offset, (char *)Datum, 1);
}
Esempio n. 17
0
// public string ReadString() [instance] :351
uString* BinaryReader::ReadString()
{
    return ::g::Uno::Runtime::Implementation::TextEncodingImpl::DecodeUtf8(ReadBytes(Read7BitEncodedInt()));
}
Esempio n. 18
0
NTSTATUS
SerenumDetectPnpDevice(
	IN PDEVICE_OBJECT DeviceObject,
	IN PDEVICE_OBJECT LowerDevice)
{
	HANDLE Handle = NULL;
	UCHAR Buffer[256];
	ULONG BaudRate;
	ULONG_PTR TotalBytesReceived = 0;
	ULONG_PTR Size;
	ULONG Msr, Purge;
	ULONG i;
	BOOLEAN BufferContainsBeginId = FALSE;
	BOOLEAN BufferContainsEndId = FALSE;
	SERIAL_LINE_CONTROL Lcr;
	SERIAL_TIMEOUTS Timeouts;
	SERIALPERF_STATS PerfStats;
	NTSTATUS Status;

	/* Open port */
	Status = ObOpenObjectByPointer(
		LowerDevice,
		OBJ_KERNEL_HANDLE,
		NULL,
		0,
		NULL,
		KernelMode,
		&Handle);
	if (!NT_SUCCESS(Status)) goto ByeBye;

	/* 1. COM port initialization, check for device enumerate */
	TRACE_(SERENUM, "COM port initialization, check for device enumerate\n");
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_CLR_DTR,
		NULL, 0, NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_CLR_RTS,
		NULL, 0, NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Wait(200);
	Size = sizeof(Msr);
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_GET_MODEMSTATUS,
		NULL, 0, &Msr, &Size);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	if ((Msr & SERIAL_DSR_STATE) == 0) goto DisconnectIdle;

	/* 2. COM port setup, 1st phase */
	TRACE_(SERENUM, "COM port setup, 1st phase\n");
	BaudRate = 1200;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_BAUD_RATE,
		&BaudRate, sizeof(BaudRate), NULL, 0);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Lcr.WordLength = 7;
	Lcr.Parity = NO_PARITY;
	Lcr.StopBits = STOP_BIT_1;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_LINE_CONTROL,
		&Lcr, sizeof(Lcr), NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_CLR_DTR,
		NULL, 0, NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_CLR_RTS,
		NULL, 0, NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Wait(200);
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_DTR,
		NULL, 0, NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Wait(200);

	/* 3. Wait for response, 1st phase */
	TRACE_(SERENUM, "Wait for response, 1st phase\n");
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_RTS,
		NULL, 0, NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Timeouts.ReadIntervalTimeout = 0;
	Timeouts.ReadTotalTimeoutMultiplier = 0;
	Timeouts.ReadTotalTimeoutConstant = 200;
	Timeouts.WriteTotalTimeoutMultiplier = Timeouts.WriteTotalTimeoutConstant = 0;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_TIMEOUTS,
		&Timeouts, sizeof(Timeouts), NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Status = ReadBytes(LowerDevice, Buffer, sizeof(Buffer), &Size);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	if (Size != 0) goto CollectPnpComDeviceId;

	/* 4. COM port setup, 2nd phase */
	TRACE_(SERENUM, "COM port setup, 2nd phase\n");
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_CLR_DTR,
		NULL, 0, NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_CLR_RTS,
		NULL, 0, NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Purge = SERIAL_PURGE_RXABORT | SERIAL_PURGE_RXCLEAR;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_PURGE,
		&Purge, sizeof(ULONG), NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Wait(200);

	/* 5. Wait for response, 2nd phase */
	TRACE_(SERENUM, "Wait for response, 2nd phase\n");
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_DTR,
		NULL, 0, NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_RTS,
		NULL, 0, NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Status = ReadBytes(LowerDevice, Buffer, 1, &TotalBytesReceived);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	if (TotalBytesReceived != 0) goto CollectPnpComDeviceId;
	Size = sizeof(Msr);
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_GET_MODEMSTATUS,
		NULL, 0, &Msr, &Size);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	if ((Msr & SERIAL_DSR_STATE) == 0) goto VerifyDisconnect; else goto ConnectIdle;

	/* 6. Collect PnP COM device ID */
CollectPnpComDeviceId:
	TRACE_(SERENUM, "Collect PnP COM device ID\n");
	Timeouts.ReadIntervalTimeout = 200;
	Timeouts.ReadTotalTimeoutMultiplier = 0;
	Timeouts.ReadTotalTimeoutConstant = 2200;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_TIMEOUTS,
		&Timeouts, sizeof(Timeouts), NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Status = ReadBytes(LowerDevice, &Buffer[TotalBytesReceived], sizeof(Buffer) - TotalBytesReceived, &Size);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	TotalBytesReceived += Size;
	Size = sizeof(PerfStats);
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_GET_STATS,
		NULL, 0, &PerfStats, &Size);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	if (PerfStats.FrameErrorCount + PerfStats.ParityErrorCount != 0) goto ConnectIdle;
	for (i = 0; i < TotalBytesReceived; i++)
	{
		if (Buffer[i] == BEGIN_ID) BufferContainsBeginId = TRUE;
		if (Buffer[i] == END_ID) BufferContainsEndId = TRUE;
	}
	if (TotalBytesReceived == 1 || BufferContainsEndId)
	{
		if (IsValidPnpIdString(Buffer, TotalBytesReceived))
		{
			Status = ReportDetectedPnpDevice(Buffer, TotalBytesReceived);
			goto ByeBye;
		}
		goto ConnectIdle;
	}
	if (!BufferContainsBeginId) goto ConnectIdle;
	if (!BufferContainsEndId) goto ConnectIdle;
	Size = sizeof(Msr);
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_GET_MODEMSTATUS,
		NULL, 0, &Msr, &Size);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	if ((Msr & SERIAL_DSR_STATE) == 0) goto VerifyDisconnect;

	/* 7. Verify disconnect */
VerifyDisconnect:
	TRACE_(SERENUM, "Verify disconnect\n");
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_DTR,
		NULL, 0, NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_CLR_RTS,
		NULL, 0, NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Wait(5000);
	goto DisconnectIdle;

	/* 8. Connect idle */
ConnectIdle:
	TRACE_(SERENUM, "Connect idle\n");
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_DTR,
		NULL, 0, NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_CLR_RTS,
		NULL, 0, NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	BaudRate = 300;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_BAUD_RATE,
		&BaudRate, sizeof(BaudRate), NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Lcr.WordLength = 7;
	Lcr.Parity = NO_PARITY;
	Lcr.StopBits = STOP_BIT_1;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_LINE_CONTROL,
		&Lcr, sizeof(Lcr), NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	if (TotalBytesReceived == 0)
		Status = STATUS_DEVICE_NOT_CONNECTED;
	else
		Status = STATUS_SUCCESS;
	goto ByeBye;

	/* 9. Disconnect idle */
DisconnectIdle:
	TRACE_(SERENUM, "Disconnect idle\n");
	/* FIXME: report to OS device removal, if it was present */
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_DTR,
		NULL, 0, NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_CLR_RTS,
		NULL, 0, NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	BaudRate = 300;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_BAUD_RATE,
		&BaudRate, sizeof(BaudRate), NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Lcr.WordLength = 7;
	Lcr.Parity = NO_PARITY;
	Lcr.StopBits = STOP_BIT_1;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_LINE_CONTROL,
		&Lcr, sizeof(Lcr), NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Status = STATUS_DEVICE_NOT_CONNECTED;

ByeBye:
	/* Close port */
	if (Handle)
		ZwClose(Handle);
	return Status;
}
Esempio n. 19
0
UT_uint32 IE_ImpGraphic_BMP::Read4Bytes(UT_ByteBuf* pBB, 
									    UT_uint32 offset)
{
	return ( ReadBytes(pBB,offset,4) );
}
Esempio n. 20
0
NTSTATUS
SerenumDetectLegacyDevice(
	IN PDEVICE_OBJECT DeviceObject,
	IN PDEVICE_OBJECT LowerDevice)
{
	HANDLE Handle = NULL;
	ULONG Fcr, Mcr;
	ULONG BaudRate;
	ULONG Command;
	SERIAL_TIMEOUTS Timeouts;
	SERIAL_LINE_CONTROL LCR;
	ULONG i, Count = 0;
	UCHAR Buffer[16];
	UNICODE_STRING DeviceDescription;
	UNICODE_STRING DeviceId;
	UNICODE_STRING InstanceId;
	UNICODE_STRING HardwareIds;
	UNICODE_STRING CompatibleIds;
	NTSTATUS Status;

	TRACE_(SERENUM, "SerenumDetectLegacyDevice(DeviceObject %p, LowerDevice %p)\n",
		DeviceObject,
		LowerDevice);

	RtlZeroMemory(Buffer, sizeof(Buffer));

	/* Open port */
	Status = ObOpenObjectByPointer(
		LowerDevice,
		OBJ_KERNEL_HANDLE,
		NULL,
		0,
		NULL,
		KernelMode,
		&Handle);
	if (!NT_SUCCESS(Status)) return Status;

	/* Reset UART */
	TRACE_(SERENUM, "Reset UART\n");
	Mcr = 0; /* MCR: DTR/RTS/OUT2 off */
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_MODEM_CONTROL,
		&Mcr, sizeof(Mcr), NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;

	/* Set communications parameters */
	TRACE_(SERENUM, "Set communications parameters\n");
	/* DLAB off */
	Fcr = 0;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_FIFO_CONTROL,
		&Fcr, sizeof(Fcr), NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	/* Set serial port speed */
	BaudRate = 1200;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_BAUD_RATE,
		&BaudRate, sizeof(BaudRate), NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	/* Set LCR */
	LCR.WordLength = 7;
	LCR.Parity = NO_PARITY;
	LCR.StopBits = STOP_BITS_2;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_LINE_CONTROL,
		&LCR, sizeof(LCR), NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;

	/* Flush receive buffer */
	TRACE_(SERENUM, "Flush receive buffer\n");
	Command = SERIAL_PURGE_RXCLEAR;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_MODEM_CONTROL,
		&Command, sizeof(Command), NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	/* Wait 100 ms */
	Wait(100);

	/* Enable DTR/RTS */
	TRACE_(SERENUM, "Enable DTR/RTS\n");
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_DTR,
		NULL, 0, NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_RTS,
		NULL, 0, NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;

	/* Set timeout to 500 microseconds */
	TRACE_(SERENUM, "Set timeout to 500 microseconds\n");
	Timeouts.ReadIntervalTimeout = 100;
	Timeouts.ReadTotalTimeoutMultiplier = 0;
	Timeouts.ReadTotalTimeoutConstant = 500;
	Timeouts.WriteTotalTimeoutMultiplier = Timeouts.WriteTotalTimeoutConstant = 0;
	Status = DeviceIoControl(LowerDevice, IOCTL_SERIAL_SET_TIMEOUTS,
		&Timeouts, sizeof(Timeouts), NULL, NULL);
	if (!NT_SUCCESS(Status)) goto ByeBye;

	/* Fill the read buffer */
	TRACE_(SERENUM, "Fill the read buffer\n");
	Status = ReadBytes(LowerDevice, Buffer, sizeof(Buffer)/sizeof(Buffer[0]), (PVOID)&Count);
	if (!NT_SUCCESS(Status)) goto ByeBye;

	RtlInitUnicodeString(&DeviceId, L"Serenum\\Mouse");
	RtlInitUnicodeString(&InstanceId, L"0000"); /* FIXME */
	for (i = 0; i < Count; i++)
	{
		if (Buffer[i] == 'B')
		{
			/* Sign for Microsoft Ballpoint */
			/* Hardware id: *PNP0F09
			 * Compatible id: *PNP0F0F, SERIAL_MOUSE
			 */
			RtlInitUnicodeString(&DeviceDescription, L"Microsoft Ballpoint device");
			SerenumInitMultiSzString(&HardwareIds, "*PNP0F09", NULL);
			SerenumInitMultiSzString(&CompatibleIds, "*PNP0F0F", "SERIAL_MOUSE", NULL);
			Status = ReportDetectedDevice(DeviceObject,
				&DeviceDescription, &DeviceId, &InstanceId, &HardwareIds, &CompatibleIds);
			RtlFreeUnicodeString(&HardwareIds);
			RtlFreeUnicodeString(&CompatibleIds);
			goto ByeBye;
		}
		else if (Buffer[i] == 'M')
		{
			/* Sign for Microsoft Mouse protocol followed by button specifier */
			if (i == sizeof(Buffer) - 1)
			{
				/* Overflow Error */
				Status = STATUS_DEVICE_NOT_CONNECTED;
				goto ByeBye;
			}
			switch (Buffer[i + 1])
			{
				case '3':
					/* Hardware id: *PNP0F08
					 * Compatible id: SERIAL_MOUSE
					 */
					RtlInitUnicodeString(&DeviceDescription, L"Microsoft Mouse with 3-buttons");
					SerenumInitMultiSzString(&HardwareIds, "*PNP0F08", NULL);
					SerenumInitMultiSzString(&CompatibleIds, "SERIAL_MOUSE", NULL);
					break;
				default:
					/* Hardware id: *PNP0F01
					 * Compatible id: SERIAL_MOUSE
					 */
					RtlInitUnicodeString(&DeviceDescription, L"Microsoft Mouse with 2-buttons or Microsoft Wheel Mouse");
					SerenumInitMultiSzString(&HardwareIds, "*PNP0F01", NULL);
					SerenumInitMultiSzString(&CompatibleIds, "SERIAL_MOUSE", NULL);
					break;
			}
			Status = ReportDetectedDevice(DeviceObject,
				&DeviceDescription, &DeviceId, &InstanceId, &HardwareIds, &CompatibleIds);
			RtlFreeUnicodeString(&HardwareIds);
			RtlFreeUnicodeString(&CompatibleIds);
			goto ByeBye;
		}
	}

	Status = STATUS_DEVICE_NOT_CONNECTED;

ByeBye:
	/* Close port */
	if (Handle)
		ZwClose(Handle);
	return Status;
}
Esempio n. 21
0
// Read a command from the CRS
uint8_t ReadCmd(void) {
	Command Cmd;
	uint32_t *NewNodeNames;
	pEdgeArray NewEdges;
	uint32_t i;
	pNode NewNode;
	pEdge NewEdge;
	pEdge ExistingEdge;
	uint8_t NodeCount;
	uint32_t *SPT;

	// read in the basic command header
	if (ReadBytes((unsigned char *)&Cmd, sizeof(Command)) != sizeof(Command)) {
		return(0);
	}

	if (Cmd.Action == CMD_SEND_NODES) {
		// read in the indicated number of Nodes
#ifdef PATCHED_1
		if ((Cmd.NumElements + NumNodes) > MAX_NODES) {
#else
		if (Cmd.NumElements > MAX_NODES) {
#endif
			ReadNull(sizeof(uint32_t)*Cmd.NumElements);
			SendErrorResponse(RESP_ERROR_TOO_MANY_NODES);
			return(0);
		}
		if ((NewNodeNames = (uint32_t *)calloc(sizeof(uint32_t)*Cmd.NumElements)) == NULL) {
			DestroyNodes();
			DestroyEdges();
			_terminate(1);
		}
		if (ReadBytes((unsigned char *)NewNodeNames, sizeof(uint32_t)*Cmd.NumElements) != sizeof(uint32_t)*Cmd.NumElements) {
			free(NewNodeNames);
			return(0);
		}

		// make sure none of the new node names exist already
		for (i = 0; i < Cmd.NumElements; i++) {
			if (FindNode(NewNodeNames[i]) != NULL) {
				free(NewNodeNames);
				SendErrorResponse(RESP_ERROR_DUPLICATE_NODE);
				return(0);
			}
		}

		// Create the new nodes 
		for (i = 0; i < Cmd.NumElements; i++) {
			// create a new node
			if ((NewNode = (pNode)calloc(sizeof(Node))) == NULL) {
				free(NewNodeNames);
				DestroyNodes();
				DestroyEdges();
				_terminate(1);
			}
			NewNode->Name = NewNodeNames[i];
			NewNode->Distance = SIZE_MAX;
			// Add it to the graph
			if (!AddNode(NewNode)) {
				free(NewNodeNames);
				DestroyNodes();
				DestroyEdges();
				_terminate(1);
			}
		}

		// done creating new nodes
		free(NewNodeNames);

	} else if (Cmd.Action == CMD_SEND_EDGES) {
		// read in the indicated number of Edges
		if ((Cmd.NumElements + NumEdges) > MAX_EDGES) {
			ReadNull(sizeof(EdgeArray)*Cmd.NumElements);
			SendErrorResponse(RESP_ERROR_TOO_MANY_EDGES);
			return(0);
		}
		if ((NewEdges = (pEdgeArray)calloc(sizeof(EdgeArray)*Cmd.NumElements)) == NULL) {
			DestroyNodes();
			DestroyEdges();
			_terminate(1);
		}
		if (ReadBytes((unsigned char *)NewEdges, sizeof(EdgeArray)*Cmd.NumElements) != sizeof(EdgeArray)*Cmd.NumElements) {
			free(NewEdges);
			return(0);
		}
		
		// Create the new edges 
		for (i = 0; i < Cmd.NumElements; i++) {
			// create a new Edge
			if ((NewEdge = (pEdge)calloc(sizeof(Edge))) == NULL) {
				free(NewEdges);
				DestroyNodes();
				DestroyEdges();
				_terminate(1);
			}
			// make sure the starting and ending nodes exist
			if ((NewEdge->NodeA = FindNode(NewEdges[i].NodeA)) == NULL) {
				SendErrorResponse(RESP_ERROR_INVALID_NODE);
				free(NewEdge);
				free(NewEdges);
				DestroyNodes();
				DestroyEdges();
				_terminate(1);
			}
			if ((NewEdge->NodeZ = FindNode(NewEdges[i].NodeZ)) == NULL) {
				SendErrorResponse(RESP_ERROR_INVALID_NODE);
				free(NewEdge);
				free(NewEdges);
				DestroyNodes();
				DestroyEdges();
				_terminate(1);
			}
			// offset the weight by a fixed magic_page-based value
			NewEdge->Weight = NewEdges[i].Weight + rand_page[NumNodes];

			// see if one already exists
			if ((ExistingEdge = FindEdge(NewEdge->NodeA, NewEdge->NodeZ)) != NULL) {
				if (ExistingEdge->Weight > NewEdge->Weight) {
					ExistingEdge->Weight = NewEdge->Weight;
				}

				// keep the existing edge
				free(NewEdge);
				continue;
			}

			// Add it to the graph
			if (!AddEdge(NewEdge)) {
				free(NewEdge);
				free(NewEdges);
				DestroyNodes();
				DestroyEdges();
				_terminate(1);
			}
		}

	} else if (Cmd.Action == CMD_RUN_SPT) {
		if ((SPT = FindSpt(Cmd.StartingNode, Cmd.EndingNode, &NodeCount)) == NULL) {
			// unable to find SPT
			SendErrorResponse(RESP_ERROR_SPT_FAIL);
			return(0);
		}
		SendResponse(RESP_NODE_SET, NodeCount, SPT);
		free(SPT);

	} else {
		SendErrorResponse(RESP_ERROR_INVALID_CMD);
		return(0);
	}

	return(1);
}
Esempio n. 22
0
void CInArchive::GetNextFolderItem(CFolder &folder)
{
  CNum numCoders = ReadNum();

  folder.Coders.Clear();
  folder.Coders.Reserve((int)numCoders);
  CNum numInStreams = 0;
  CNum numOutStreams = 0;
  CNum i;
  for (i = 0; i < numCoders; i++)
  {
    folder.Coders.Add(CCoderInfo());
    CCoderInfo &coder = folder.Coders.Back();

    {
      Byte mainByte = ReadByte();
      int idSize = (mainByte & 0xF);
      Byte longID[15];
      ReadBytes(longID, idSize);
      if (idSize > 8)
        ThrowUnsupported();
      UInt64 id = 0;
      for (int j = 0; j < idSize; j++)
        id |= (UInt64)longID[idSize - 1 - j] << (8 * j);
      coder.MethodID = id;

      if ((mainByte & 0x10) != 0)
      {
        coder.NumInStreams = ReadNum();
        coder.NumOutStreams = ReadNum();
      }
      else
      {
        coder.NumInStreams = 1;
        coder.NumOutStreams = 1;
      }
      if ((mainByte & 0x20) != 0)
      {
        CNum propsSize = ReadNum();
        coder.Props.SetCapacity((size_t)propsSize);
        ReadBytes((Byte *)coder.Props, (size_t)propsSize);
      }
      if ((mainByte & 0x80) != 0)
        ThrowUnsupported();
    }
    numInStreams += coder.NumInStreams;
    numOutStreams += coder.NumOutStreams;
  }

  CNum numBindPairs = numOutStreams - 1;
  folder.BindPairs.Clear();
  folder.BindPairs.Reserve(numBindPairs);
  for (i = 0; i < numBindPairs; i++)
  {
    CBindPair bp;
    bp.InIndex = ReadNum();
    bp.OutIndex = ReadNum();
    folder.BindPairs.Add(bp);
  }

  if (numInStreams < numBindPairs)
    ThrowUnsupported();
  CNum numPackStreams = numInStreams - numBindPairs;
  folder.PackStreams.Reserve(numPackStreams);
  if (numPackStreams == 1)
  {
    for (i = 0; i < numInStreams; i++)
      if (folder.FindBindPairForInStream(i) < 0)
      {
        folder.PackStreams.Add(i);
        break;
      }
    if (folder.PackStreams.Size() != 1)
      ThrowUnsupported();
  }
  else
    for (i = 0; i < numPackStreams; i++)
      folder.PackStreams.Add(ReadNum());
}
Esempio n. 23
0
HRESULT DataTargetReader::Read8(BYTE* pByteValue)
{
    return ReadBytes(pByteValue, 1);
}
XBOX::VError VHTTPWebsocketHandler::ReadHeader(bool* found)
{
	VError			l_err;

	memset(&fFrame,0,sizeof(ws_frame_t));
	*found = false;
	fFrame.buf_len = 2;
//printf("ReadHeader called\n");

	l_err = ReadBytes((void *)fFrame.header, &fFrame.buf_len);
	if (!l_err && fFrame.buf_len)
	{
		// extensions not handled
		if (fFrame.header[0] & 0x70)
		{
			DebugMsg("VHTTPWebsocketHandler::ReadHeader RFC6455 EXTENSIONS NOT HANDLED!!!!\n");
			l_err = VE_INVALID_PARAMETER;
		}
		if (!l_err)
		{
			fFrame.opcode = (ws_opcode_t)(fFrame.header[0] & 0x0F);
		
			fFrame.masked = (fFrame.header[1] & 0x80);
			fFrame.len = (sLONG8)(fFrame.header[1] & 0x7F);
			if (fFrame.len == 127)
			{
				fFrame.buf_len = 8;
				l_err = ReadBytes((void *)(fFrame.header+2), &fFrame.buf_len);
				if ( !l_err && (fFrame.buf_len != 8) )
				{
					l_err = VE_STREAM_CANNOT_READ;
				}
				if (!l_err)
				{
					fFrame.len = 0;
					for(int l_i=0;l_i<8;l_i+=2)
					{
						fFrame.len = 65536*fFrame.len + (256*fFrame.header[2+l_i]+fFrame.header[3+l_i]);
					}
					DebugMsg("ReadHeader frame.len=%lld\n",fFrame.len);
				}
			}
			else
			{
				if (fFrame.len == 126)
				{
					fFrame.buf_len = 2;
					l_err = ReadBytes((void *)(fFrame.header+2), &fFrame.buf_len);
					if ( !l_err && (fFrame.buf_len != 2) )
					{
						l_err = VE_STREAM_CANNOT_READ;
					}
					if (!l_err)
					{
						fFrame.len = 256*fFrame.header[2]+fFrame.header[3];
						DebugMsg("ReadHeader frame.len=%d\n",fFrame.len);
					}
				}
				else
				{
					DebugMsg("ReadHeader frame.len=%d\n",fFrame.len);
				}
			}
			if (!l_err && fFrame.masked)
			{
				fFrame.buf_len = 4;
				l_err = ReadBytes((void *)fFrame.msk, &fFrame.buf_len);
				if ( !l_err && (fFrame.buf_len != 4) )
				{
					l_err = VE_STREAM_CANNOT_READ;
				}
			}
			*found = true;
		}
	}
	return l_err;
}
Esempio n. 25
0
HRESULT DataTargetReader::Read64(ULONG64* pUlong64Value)
{
    Align(8);
    return ReadBytes((BYTE*)pUlong64Value, sizeof(ULONG64));
}
XBOX::VError VHTTPWebsocketHandler::ReadMessage( void* inData, uLONG* ioLength, bool* outIsTerminated )
{

	bool			l_header_found;
	uLONG			length;
	VError			l_err;

	if (!fEndpt)
	{
		xbox_assert((fEndpt != NULL));
		return VE_INVALID_PARAMETER;
	}

	l_err = VE_OK;

	if (!fBytesToRead)
	{
		l_err = ReadHeader(&l_header_found);
		if (l_err)
		{
			DebugMsg("ERR2\n");
		}
		if (!l_err && !l_header_found)
		{
			*ioLength = 0;
		}

		// not fragmented ?
		if (!l_err && (*ioLength) && (fFrame.header[0] & 0x80))
		{
			fBytesToRead = fFrame.len;
			fCurt = XBOX_LONG8(0);
			switch(fFrame.opcode)
			{
				case CONTINUATION_FRAME:
					DebugMsg("ERR3\n");
					l_err = VE_UNIMPLEMENTED;
					break;
				case CONNEXION_CLOSE:
					if (fFrame.len >= 126)
					{
						DebugMsg("ERR4\n");
						l_err = VE_INVALID_PARAMETER;
					}
					else
					{
						l_err = VE_STREAM_EOF;
					/*// close the socket
					goto NOK;
					while (!l_err && (fBytesToRead > 0))
					{
						length = (uLONG)( *ioLength >=fBytesToRead ? fBytesToRead : *ioLength);
						l_err = ReadBytes(inData,&length);
						if (l_err)
						{
							DebugMsg("ERR 5\n");
						}
						else
						{
							fBytesToRead -= length;
							*ioLength = length;
						}
					}*/
					}
					break;
				case TEXT_FRAME:
				case BIN_FRAME:
					break;
				default:
					break;
			}
		}
		else
		{
			if (!l_err && *(ioLength) )
			{
				DebugMsg("Fragmentation not handled ERR6\n");
			}
		}
	}
	//DebugMsg("ReadMessage req_len=%d ToRead=%lld\n",*ioLength,fBytesToRead);
	if (!l_err && fBytesToRead)
	{
//printf("...... bef ReadMessage req_len=%d ToRead=%lld\n",*ioLength,fBytesToRead);
		*ioLength = ( *ioLength >=fBytesToRead ? ((uLONG)fBytesToRead) : *ioLength);
//printf("...... aft ReadMessage req_len=%d ToRead=%lld\n",*ioLength,fBytesToRead);
		l_err = ReadBytes(inData,ioLength);
		if (l_err)
		{
			DebugMsg("ERR1\n");
		}
		else
		{
			fBytesToRead -= *ioLength;
//printf("...... ....... aft ReadMessage read_len=%d ToRead=%lld\n",*ioLength,fBytesToRead);
			if (fFrame.masked)
			{
				for(uLONG l_i=0; l_i<*ioLength; l_i++)
				{
					((unsigned char *)inData)[l_i] ^= fFrame.msk[fCurt % 4];
					fCurt++;
				}
			}

			*outIsTerminated = !(fBytesToRead);
		}
	}
	if (l_err)
	{
		/*fEndpt = NULL;*/
		Close();
	}
	return l_err;

}
Esempio n. 27
0
HRESULT CUnpacker::Unpack(IInStream *inStream, const CResource &resource,
    ISequentialOutStream *outStream, ICompressProgressInfo *progress)
{
  RINOK(inStream->Seek(resource.Offset, STREAM_SEEK_SET, NULL));

  CLimitedSequentialInStream *limitedStreamSpec = new CLimitedSequentialInStream();
  CMyComPtr<ISequentialInStream> limitedStream = limitedStreamSpec;
  limitedStreamSpec->SetStream(inStream);

  if (!copyCoder)
  {
    copyCoderSpec = new NCompress::CCopyCoder;
    copyCoder = copyCoderSpec;
  }
  if (!resource.IsCompressed())
  {
    if (resource.PackSize != resource.UnpackSize)
      return S_FALSE;
    limitedStreamSpec->Init(resource.PackSize);
    return copyCoder->Code(limitedStreamSpec, outStream, NULL, NULL, progress);
  }
  if (resource.UnpackSize == 0)
    return S_OK;
  UInt64 numChunks = (resource.UnpackSize + kChunkSize - 1) >> kChunkSizeBits;
  unsigned entrySize = ((resource.UnpackSize > (UInt64)1 << 32) ? 8 : 4);
  UInt64 sizesBufSize64 = entrySize * (numChunks - 1);
  UInt32 sizesBufSize = (UInt32)sizesBufSize64;
  if (sizesBufSize != sizesBufSize64)
    return E_OUTOFMEMORY;
  if (sizesBufSize > sizesBuf.GetCapacity())
  {
    sizesBuf.Free();
    sizesBuf.SetCapacity(sizesBufSize);
  }
  RINOK(ReadBytes(inStream, (Byte *)sizesBuf, sizesBufSize));
  const Byte *p = (const Byte *)sizesBuf;
  
  if (!lzxDecoder)
  {
    lzxDecoderSpec = new NCompress::NLzx::CDecoder(true);
    lzxDecoder = lzxDecoderSpec;
    RINOK(lzxDecoderSpec->SetParams(kChunkSizeBits));
  }
  
  UInt64 baseOffset = resource.Offset + sizesBufSize64;
  UInt64 outProcessed = 0;
  for (UInt32 i = 0; i < (UInt32)numChunks; i++)
  {
    UInt64 offset = 0;
    if (i > 0)
    {
      if (entrySize == 4)
        offset = GetUInt32FromMem(p);
      else
        offset = GetUInt64FromMem(p);
      p += entrySize;
    }
    UInt64 nextOffset = resource.PackSize - sizesBufSize64;
    if (i + 1 < (UInt32)numChunks)
      if (entrySize == 4)
        nextOffset = GetUInt32FromMem(p);
      else
        nextOffset = GetUInt64FromMem(p);
    if (nextOffset < offset)
      return S_FALSE;

    RINOK(inStream->Seek(baseOffset + offset, STREAM_SEEK_SET, NULL));
    UInt64 inSize = nextOffset - offset;
    limitedStreamSpec->Init(inSize);

    if (progress)
    {
      RINOK(progress->SetRatioInfo(&offset, &outProcessed));
    }
    
    UInt32 outSize = kChunkSize;
    if (outProcessed + outSize > resource.UnpackSize)
      outSize = (UInt32)(resource.UnpackSize - outProcessed);
    UInt64 outSize64 = outSize;
    lzxDecoderSpec->SetKeepHistory(false);
    ICompressCoder *coder = (inSize == outSize) ? copyCoder : lzxDecoder;
    RINOK(coder->Code(limitedStreamSpec, outStream, NULL, &outSize64, NULL));
    outProcessed += outSize;
  }
  return S_OK;
}
Esempio n. 28
0
NS_IMETHODIMP
nsBinaryInputStream::ReadByteArray(uint32_t aLength, uint8_t* *_rval)
{
  return ReadBytes(aLength, reinterpret_cast<char **>(_rval));
}
Esempio n. 29
0
static HRESULT
ReadWavHeader(FILE *fpr, WWMFPcmFormat *format_return, DWORD *dataBytes_return)
{
    HRESULT hr = E_FAIL;
    BYTE buff[16];
    int chunkBytes = 0;
    int fmtChunkSize = 0;
    short shortValue;
    int intValue;

    HRG(ReadBytes(fpr, 12U, buff));

    if (0 != memcmp(buff, "RIFF", 4)) {
        printf("file is not riff wave file\n");
        goto end;
    }
    if (0 != memcmp(&buff[8], "WAVE", 4)) {
        printf("file is not riff wave file\n");
        goto end;
    }

    for (;;) {
        HRG(ReadBytes(fpr, 4U, buff));

        if (0 == memcmp(buff, "fmt ", 4)) {
            // fmt chunk

            // chunkSize size==4
            HRG(ReadInt32(fpr, &fmtChunkSize));
            if (16 != fmtChunkSize && 18 != fmtChunkSize && 40 != fmtChunkSize) {
                printf("unrecognized format");
                goto end;
            }
            // audioFormat size==2
            HRG(ReadInt16(fpr, &shortValue));
            if (1 == shortValue) {
                format_return->sampleFormat = WWMFBitFormatInt;
            } else if (3 == shortValue) {
                format_return->sampleFormat = WWMFBitFormatFloat;
            } else if (0xfffe == (unsigned short)shortValue) {
                // SampleFormat is written on WAVEFORMATEXTENSIBLE
                format_return->sampleFormat = WWMFBitFormatUnknown;
            } else {
                printf("unrecognized format");
                goto end;
            }

            // numChannels size==2
            HRG(ReadInt16(fpr, &shortValue));
            format_return->nChannels = shortValue;

            // sampleRate size==4
            HRG(ReadInt32(fpr, &intValue));
            format_return->sampleRate = intValue;

            // byteRate size==4
            HRG(ReadInt32(fpr, &intValue));

            // blockAlign size==2
            HRG(ReadInt16(fpr, &shortValue));

            // bitspersample size==2
            HRG(ReadInt16(fpr, &shortValue));
            format_return->bits = shortValue;
            format_return->validBitsPerSample = shortValue;

            if (16 < fmtChunkSize) {
                // subchunksize
                HRG(ReadInt16(fpr, &shortValue));
                if (0 == shortValue) {
                    hr = S_OK;
                    goto end;
                } else if (22 == shortValue) {
                    // validbitspersample
                    HRG(ReadInt16(fpr, &shortValue));
                    format_return->validBitsPerSample = shortValue;

                    // dwChannelMask
                    HRG(ReadInt32(fpr, (int*)&format_return->dwChannelMask));

                    // format GUID
                    HRG(ReadBytes(fpr, 16U, buff));
                    if (0 == memcmp(buff, &MFAudioFormat_Float, 16)) {
                        format_return->sampleFormat = WWMFBitFormatFloat;
                    } else if (0 == memcmp(buff, &MFAudioFormat_PCM, 16)) {
                        format_return->sampleFormat = WWMFBitFormatInt;
                    } else {
                        printf("unrecognized format guid");
                        goto end;
                    }
                } else {
                    printf("unrecognized format");
                    goto end;
                }
            }

        } else if (0 == memcmp(buff, "data", 4)) {
            // data chunk
            HRG(ReadInt32(fpr, (int*)dataBytes_return));
            break;
        } else {
            // skip this chunk
            HRG(ReadInt32(fpr, &chunkBytes));
            if (chunkBytes < 4) {
                printf("E: chunk bytes == %d\n", chunkBytes);
                goto end;
            }
            fseek(fpr, chunkBytes, SEEK_CUR);
        }

    }
end:
    if (S_OK == hr && format_return->sampleFormat == WWMFBitFormatUnknown) {
        printf("unrecognized format");
        hr = E_FAIL;
    }

    return hr;
}
//=================================================================================================
axByte axDataBufferReader::ReadByte()
{
	axByte bResult;
	ReadBytes((axBytes)&bResult, axSizeOf(axByte));
	return bResult;
}