Esempio n. 1
0
CCard *BeidCardGetInstance(unsigned long ulVersion, const char *csReader,
	SCARDHANDLE hCard, CContext *poContext, CPinpad *poPinpad)
{
	CCard *poCard = NULL;

	if ((ulVersion % 100) == (PLUGIN_VERSION % 100))
	{
		unsigned long ulLockCount = 1;
		try {
			bool bNeedToSelectApplet = false;
			CByteArray oData;
			CByteArray oCmd(40);
			unsigned char tucSelectApp[] = {0x00, 0xA4, 0x04, 0x0C};
			oCmd.Append(tucSelectApp, sizeof(tucSelectApp));
			oCmd.Append((unsigned char) sizeof(BELPIC_AID));
			oCmd.Append(BELPIC_AID, sizeof(BELPIC_AID));
			long lRetVal;
			// Don't remove these brackets, CAutoLock dtor must be called!
			//{
			//don't use autolock when card might be reset
				//CAutoLock oAutLock(&poContext->m_oPCSC, hCard);
				
				poContext->m_oPCSC.BeginTransaction(hCard);
				oData = poContext->m_oPCSC.Transmit(hCard, oCmd, &lRetVal);
				if (lRetVal == SCARD_E_COMM_DATA_LOST || lRetVal == SCARD_E_NOT_TRANSACTED)
				{
					poContext->m_oPCSC.Recover(hCard, &ulLockCount);
					
					bNeedToSelectApplet = BeidCardSelectApplet(poContext, hCard);
					if (bNeedToSelectApplet)// try again to select the belpic app
						oData = poContext->m_oPCSC.Transmit(hCard, oCmd,&lRetVal);
				}
				if (oData.Size() == 2 && oData.GetByte(0) == 0x6A &&
					(oData.GetByte(1) == 0x82 || oData.GetByte(1) == 0x86))
				{
					// Perhaps the applet is no longer selected; so try to select it
					// first; and if successfull then try to select the Belpic AID again
					bNeedToSelectApplet = BeidCardSelectApplet(poContext, hCard);
					if (bNeedToSelectApplet)
						oData = poContext->m_oPCSC.Transmit(hCard, oCmd,&lRetVal);
				}

				bool bIsBeidCard = oData.Size() == 2 && oData.GetByte(0) == 0x90 && oData.GetByte(1) == 0x00;

				if (bIsBeidCard)
					poCard = new CBeidCard(hCard, poContext, poPinpad, oData,
					bNeedToSelectApplet ? ALW_SELECT_APPLET : TRY_SELECT_APPLET);
#ifdef __APPLE__
				else {
					// On Mac, if an unknown asynchronous card is inserted,
					// we don't return NULL but a CUnknownCard instance.
					// Reason: if we return NULL then the SISCardPlugin who
					// will be consulted next in card of a ACR38U reader
					// causes the reader/driver to get in a strange state
					// (if no SIS card is present) and if then a CUnknownCard
					// is instantiated, it will throw an exception if e.g.
					// SCardStatus() is called.
					// Remark: this trick won't work if synchronous card
					// (other then the SIS card is inserted).
					if(ulLockCount)
					{
						poContext->m_oPCSC.EndTransaction(hCard);
					}
					return new CUnknownCard(hCard, poContext, poPinpad, CByteArray());
				}
#endif
			//}
			if(ulLockCount)
			{
				poContext->m_oPCSC.EndTransaction(hCard);
			}
		}
		catch(...)
		{
			if(ulLockCount)
			{
				poContext->m_oPCSC.EndTransaction(hCard);
			}
			//printf("Exception in cardPluginBeid.CardGetInstance()\n");
		}
	}

	return poCard;
}
//
//    ScanExceptions
//    ==============
//
//    Scan for applications which have been proven to not be picked up by any 'standard' methods
//
//	  Currently this includes:
//		Sophos SweepNT
//		Novell Client
//
void CApplicationInstanceList::ScanExceptions ()
{
	CString applicationName;
	CString publisher;
	CString productID;
	CString productGUID("");
	CString version("");

	HKEY hKey;
	
	CString strExceptionKey = "SOFTWARE\\Sophos\\SweepNT";

	// See if we have the SOPHOS Sweep NT primary registry key
	if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, strExceptionKey, 0, KEY_READ, &hKey) == ERROR_SUCCESS) 
	{
		// OK so it's probably installed - get any display version
		CString strDisplayVersion = CReg::GetItemString(HKEY_LOCAL_MACHINE, strExceptionKey.GetBuffer(0), "Version");	
		RegCloseKey (hKey);

		applicationName = "Sophos SweepNT";
		publisher = "Sophos Inc.";
		productID = "|" + strDisplayVersion + "|" + publisher;

		// Valid application so add to our list
		AddApplicationInstance(applicationName, publisher, productGUID, productID, version);
	}

	// Novell Client
	strExceptionKey = "Software\\Novell\\NetWareWorkstation\\CurrentVersion";
	if (ERROR_SUCCESS == RegOpenKeyEx (HKEY_LOCAL_MACHINE, strExceptionKey, 0, KEY_READ, &hKey)) 
	{
		// OK so it's probably installed - get the Display Name
		applicationName = CReg::GetItemString(HKEY_LOCAL_MACHINE, strExceptionKey.GetBuffer(0), "Title");	
		RegCloseKey (hKey);
		publisher = "Novell Inc.";
		productID = "";

		// ...and then the version
		int nMajorVersion = CReg::GetItemInt(HKEY_LOCAL_MACHINE, strExceptionKey.GetBuffer(0), "MajorVersion");	
		int nMinorVersion = CReg::GetItemInt(HKEY_LOCAL_MACHINE, strExceptionKey.GetBuffer(0), "MinorVersion");	
		CString strBuildNumber = CReg::GetItemString(HKEY_LOCAL_MACHINE, strExceptionKey.GetBuffer(0), "");	

		// format the version
		version.Format("%d.%d %s" ,nMajorVersion ,nMinorVersion ,strBuildNumber);

		// Valid application so add to our list
		AddApplicationInstance(applicationName, publisher, productGUID, productID, version);
	}

	// IE (Bug #525)
	strExceptionKey = "SOFTWARE\\Microsoft\\Internet Explorer";
	if (ERROR_SUCCESS == RegOpenKeyEx (HKEY_LOCAL_MACHINE, strExceptionKey, 0, KEY_READ, &hKey)) 
	{
		// OK so it's probably installed - get the Display Name
		applicationName = "Internet Explorer";	
		RegCloseKey (hKey);

		publisher = "Microsoft Corporation, Inc.";
		version = CReg::GetItemString(HKEY_LOCAL_MACHINE, strExceptionKey.GetBuffer(0), "svcVersion");
		if (version == "")
			version = CReg::GetItemString(HKEY_LOCAL_MACHINE, strExceptionKey.GetBuffer(0), "Version");
		productID = CReg::GetItemString(HKEY_LOCAL_MACHINE ,"SOFTWARE\\Microsoft\\Internet Explorer\\Registration" ,PRODUCTID);

		CByteArray arrayDigitalProductID;
		
		// Using the passed in 
		if (CReg::GetItemBinary (HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Internet Explorer\\Registration", DIGITALPRODUCTID ,arrayDigitalProductID))
		{
			// if we have an empty DigitalPRoductID we will hit an exception
			// so check here that the byte array larger size is > 1
			if (arrayDigitalProductID.GetSize() > 1)
				productGUID = DecodeDigitalProductKey(arrayDigitalProductID);
		}		

		// Valid application so add to our list
		CApplicationInstance newApplication;
		CApplicationSerial newSerial;

		newApplication.Name(applicationName);
		newApplication.Publisher(publisher);
		newApplication.Version(version);
		newApplication.Guid(productGUID);
		newApplication.Source("Windows Installer Key");

		newSerial.ApplicationName(applicationName);
		newSerial.ProductId(productID);
		newSerial.CdKey(productGUID);
		newApplication.Serial(newSerial);		

		// ...add to our list
		_listApplicationInstances.Add(newApplication);
	}
}
int CPartFileConvert::performConvertToeMule(CString folder)
{
	BOOL bWorking;
	CString filepartindex,newfilename;
	CString buffer;
	UINT fileindex;
	CFileFind finder;
	
	CString partfile=folder;
	folder.Delete(folder.ReverseFind('\\'),folder.GetLength());
	partfile=partfile.Mid(partfile.ReverseFind('\\')+1,partfile.GetLength());


	UpdateGUI(0,GetResString(IDS_IMP_STEPREADPF),true);

	filepartindex=partfile.Left(partfile.Find('.'));
	//int pos=filepartindex.ReverseFind('\\');
	//if (pos>-1) filepartindex=filepartindex.Mid(pos+1,filepartindex.GetLength()-pos);

	UpdateGUI(4,GetResString(IDS_IMP_STEPBASICINF));

	CPartFile* file=new CPartFile();
	pfconverting->partmettype=file->LoadPartFile(folder,partfile,true);

	switch (pfconverting->partmettype) {
		case PMT_UNKNOWN:
		case PMT_BADFORMAT:
			delete file;
			return CONV_BADFORMAT;
			break;
	}

	CString oldfile=folder+_T("\\")+partfile.Left(partfile.GetLength()- ((pfconverting->partmettype==PMT_SHAREAZA)?3:4) );

	pfconverting->size=file->GetFileSize();
	pfconverting->filename=file->GetFileName();
	pfconverting->filehash= EncodeBase16( file->GetFileHash() ,16);
	UpdateGUI(pfconverting);

	if (theApp.downloadqueue->GetFileByID(file->GetFileHash())!=0) {
		delete file;
		return CONV_ALREADYEXISTS;
	}
	
	if (pfconverting->partmettype==PMT_SPLITTED ) {
		try {
			CByteArray ba;
			ba.SetSize(PARTSIZE);

			CFile inputfile;
			int pos1,pos2;
			CString filename;

			// just count
			UINT maxindex=0;
			UINT partfilecount=0;
			bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*.part"));
			while (bWorking)
			{
				bWorking = finder.FindNextFile();
				++partfilecount;
				buffer=finder.GetFileName();
				pos1=buffer.Find('.');
				pos2=buffer.Find('.',pos1+1);
				fileindex=_tstoi(buffer.Mid(pos1+1,pos2-pos1) );
				if (fileindex==0) continue;
				if (fileindex>maxindex) maxindex=fileindex;
			}
			float stepperpart;
			if (partfilecount>0) {
				stepperpart=(80.0f / partfilecount );
				if (maxindex*PARTSIZE<=pfconverting->size) pfconverting->spaceneeded=maxindex*PARTSIZE;
					else pfconverting->spaceneeded=((pfconverting->size / PARTSIZE) * PARTSIZE)+(pfconverting->size % PARTSIZE);
			} else {
				stepperpart=80.0f;
				pfconverting->spaceneeded=0;
			}
			
			UpdateGUI(pfconverting);

			if (GetFreeDiskSpaceX(thePrefs.GetTempDir()) < (maxindex*PARTSIZE) ) {
				delete file;
				return CONV_OUTOFDISKSPACE;
			}

			// create new partmetfile, and remember the new name
			file->CreatePartFile();
			newfilename=file->GetFullName();

			UpdateGUI(8,GetResString(IDS_IMP_STEPCRDESTFILE));
			file->m_hpartfile.SetLength( pfconverting->spaceneeded );

			uint16 curindex=0;
			bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*.part"));
			while (bWorking)
			{
				bWorking = finder.FindNextFile();
				
				//stats
				++curindex;
				buffer.Format(GetResString(IDS_IMP_LOADDATA),curindex,partfilecount);
				UpdateGUI( 10+(curindex*stepperpart) ,buffer);

				filename=finder.GetFileName();
				pos1=filename.Find('.');
				pos2=filename.Find('.',pos1+1);
				fileindex=_tstoi(filename.Mid(pos1+1,pos2-pos1) );
				if (fileindex==0) continue;

				uint32 chunkstart=(fileindex-1) * PARTSIZE ;

				// open, read data of the part-part-file into buffer, close file
				inputfile.Open(finder.GetFilePath(),CFile::modeRead|CFile::shareDenyWrite);
				uint32 readed=inputfile.Read( ba.GetData() ,PARTSIZE);
				inputfile.Close();

				buffer.Format(GetResString(IDS_IMP_SAVEDATA),curindex,partfilecount);
				UpdateGUI( 10+(curindex*stepperpart) ,buffer);

				// write the buffered data
				file->m_hpartfile.Seek(chunkstart, CFile::begin );
				file->m_hpartfile.Write(ba.GetData(),readed);
			}
		}
		catch(CFileException* error) {
			CString strError(GetResString(IDS_IMP_IOERROR));
			TCHAR szError[MAX_CFEXP_ERRORMSG];
			if (error->GetErrorMessage(szError, ARRSIZE(szError))){
				strError += _T(" - ");
				strError += szError;
			}
			LogError(false, _T("%s"), strError);
			error->Delete();
			delete file;
			return CONV_IOERROR;
		}
		file->m_hpartfile.Close();
	}
	// import an external common format partdownload
	else //if (pfconverting->partmettype==PMT_DEFAULTOLD || pfconverting->partmettype==PMT_NEWOLD || Shareaza  ) 
	{
		
		if (!pfconverting->removeSource) 
			pfconverting->spaceneeded=GetDiskFileSize(oldfile);

		UpdateGUI(pfconverting);

		if (!pfconverting->removeSource && (GetFreeDiskSpaceX(thePrefs.GetTempDir()) < pfconverting->spaceneeded) ) {
			delete file;
			return CONV_OUTOFDISKSPACE;
		}

		file->CreatePartFile();
		newfilename=file->GetFullName();

		file->m_hpartfile.Close();

		bool ret=false;
		UpdateGUI( 92 ,GetResString(IDS_COPY));
		DeleteFile(newfilename.Left(newfilename.GetLength()-4));

		if (!PathFileExists(oldfile)) {
			// data file does not exist. well, then create a 0 byte big one
			HANDLE hFile = CreateFile( newfilename.Left(newfilename.GetLength()-4) ,    // file to open
							GENERIC_WRITE,          // open for reading
							FILE_SHARE_READ,       // share for reading
							NULL,                  // default security
							CREATE_NEW,         // existing file only
							FILE_ATTRIBUTE_NORMAL, // normal file
							NULL);                 // no attr. template
			 
			ret= !(hFile == INVALID_HANDLE_VALUE) ;

			CloseHandle(hFile);
		}
			else 
		if (pfconverting->removeSource) 
			ret=MoveFile( oldfile, newfilename.Left(newfilename.GetLength()-4) );
		else 
			ret=CopyFile( oldfile, newfilename.Left(newfilename.GetLength()-4) ,false);

		if (!ret) {
			file->DeleteFile();
			//delete file;
			return CONV_FAILED;
		}

	}


	UpdateGUI( 94 ,GetResString(IDS_IMP_GETPFINFO));

	DeleteFile(newfilename);
	if (pfconverting->removeSource)
		MoveFile(folder+_T("\\")+partfile,newfilename);
	else CopyFile(folder+_T("\\")+partfile,newfilename,false);

	for (int i = 0; i < file->hashlist.GetSize(); i++)
		delete[] file->hashlist[i];
	file->hashlist.RemoveAll();
	while (file->gaplist.GetCount()>0 ) {
		delete file->gaplist.GetAt(file->gaplist.GetHeadPosition());
		file->gaplist.RemoveAt(file->gaplist.GetHeadPosition());
	}

	if (!file->LoadPartFile(thePrefs.GetTempDir(),file->GetPartMetFileName(),false)) {
		//delete file;
		file->DeleteFile();
		return CONV_BADFORMAT;
	}

	if (pfconverting->partmettype==PMT_NEWOLD || pfconverting->partmettype==PMT_SPLITTED ) {
		file->completedsize=file->transfered;
		file->m_iGainDueToCompression = 0;
		file->m_iLostDueToCorruption = 0;
	}

	UpdateGUI( 100 ,GetResString(IDS_IMP_ADDDWL));

	theApp.downloadqueue->AddDownload(file,thePrefs.AddNewFilesPaused());
	file->SavePartFile();
	
	if (file->GetStatus(true) == PS_READY)
		theApp.sharedfiles->SafeAddKFile(file); // part files are always shared files


	if (pfconverting->removeSource) {

		bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*"));
		while (bWorking)
		{
			bWorking = finder.FindNextFile();
			_tunlink(finder.GetFilePath());
		}

		if (pfconverting->partmettype==PMT_SPLITTED)
			RemoveDirectory(folder+_T("\\"));
	}

	return CONV_OK;
}
Esempio n. 4
0
CByteArray CBeidCard::Ctrl(long ctrl, const CByteArray & oCmdData)
{
	CAutoLock oAutoLock(this);

	switch(ctrl)
    {
    case CTRL_BEID_GETCARDDATA:
        return m_oCardData;
    case CTRL_BEID_GETSIGNEDCARDDATA:
		if (m_ucAppletVersion < 0x17)
			throw CMWEXCEPTION(EIDMW_ERR_NOT_SUPPORTED);
		else
		{
			if (m_selectAppletMode == ALW_SELECT_APPLET)
				SelectApplet();
			m_ucCLA = 0x80;
			CByteArray oRet = SendAPDU(0xE4, 0x02, 0x00, 0x9C);
			m_ucCLA = 0;
			getSW12(oRet, 0x9000);
			oRet.Chop(2);
			return oRet;
		}
    case CTRL_BEID_GETSIGNEDPINSTATUS:
		// oCmdData must contain:
		// - the pin reference (1 byte)
		if (m_ucAppletVersion < 0x17)
			throw CMWEXCEPTION(EIDMW_ERR_NOT_SUPPORTED);
		else
		{
			if (m_selectAppletMode == ALW_SELECT_APPLET)
				SelectApplet();
			unsigned char ucPinRef = oCmdData.GetByte(0);
			m_ucCLA = 0x80;
			CByteArray oRet = SendAPDU(0xEA, 0x02, ucPinRef, 0x81);
			m_ucCLA = 0;
			if (ShouldSelectApplet(0xEA, getSW12(oRet)))
			{
				if (SelectApplet())
				{
					m_selectAppletMode = ALW_SELECT_APPLET;
					m_ucCLA = 0x80;
					CByteArray oRet = SendAPDU(0xEA, 0x02, ucPinRef, 0x81);
					m_ucCLA = 0;
				}
			}
			getSW12(oRet, 0x9000);
			oRet.Chop(2);
			return oRet;
		}
	case CTRL_BEID_INTERNAL_AUTH:
		// oCmdData must contain:
		// - the key reference (1 byte)
		// - the challenge to be signed (20 bytes)
		if (oCmdData.Size() != 21)
			throw CMWEXCEPTION(EIDMW_ERR_PARAM_BAD);
		else
		{
			if (m_selectAppletMode == ALW_SELECT_APPLET)
				SelectApplet();
			unsigned char ucKeyRef = oCmdData.GetByte(0);
			CByteArray oData(22);
			oData.Append(0x94);
			oData.Append(0x14);
			oData.Append(oCmdData.GetBytes() + 1, 20);
			CByteArray oRet = SendAPDU(0x88, 0x02, ucKeyRef, oData);
			if (ShouldSelectApplet(0x88, getSW12(oRet)))
			{
				if (SelectApplet())
				{
					m_selectAppletMode = ALW_SELECT_APPLET;
					CByteArray oRet = SendAPDU(0x88, 0x02, ucKeyRef, oData);
				}
			}
			getSW12(oRet, 0x9000);
			oRet.Chop(2);
			return oRet;
		}
    default:
        MWLOG(LEV_WARN, MOD_CAL, L"Ctrl(): Unknown CRTL code %d (0x%0x) specified", ctrl, ctrl);
		throw CMWEXCEPTION(EIDMW_ERR_PARAM_BAD);
    }
}
Esempio n. 5
0
CTobCompiler::EToken CTobCompiler::CompilePass1()
{
    EToken r, LastToken;
    CString str, buf, sizebuf;
    CByteArray* bin;
    SValueType* val;
    SExpression* exp;

    for(;;)
    {
        BOOL bSkipGetToken = FALSE;
        if ((r = GetToken(str)) <= 0) return r;
_SkipGetToken:
        if (r == SYM_DEF)
        {
/*
            if (m_bin.GetSize() > 0)
            {
                m_err = "const token can not defined after data";
                return ERR_NORMAL;
            }
*/
            if ((r = GetToken(str)) < 0) return r;
            if (r != SYM_TOKEN)
            {
                m_err = "not found token after '@'";
                return ERR_NORMAL;
            }

            if (str == "_IGNORECASE")
            {
                m_Option.bIgnoreCase = TRUE;
                continue;
            }

            if ((r = GetToken(buf)) < 0) return r;
            if (r == SYM_BIN)
            {
                bin = new CByteArray;
                if ((r = GetBinary(*bin)) < 0) { delete bin; return r; }
                AddMap(m_binmap, str, bin);
            }
            else if (r == SYM_STR)
            {
                bin = new CByteArray;
                if ((r = GetString(*bin)) < 0) { delete bin; return r; }
                AddMap(m_binmap, str, bin);
            }
            else if (r == SYM_INT)
            {
                ULONG Length;
                BOOL bHex = (buf[0] == '0' && buf[1] == 'x');

                r = GetToken(sizebuf);
                LastToken = r;
                if (r == SYM_TYPE)
                {
                    r = GetToken(sizebuf);
                    if (r != SYM_TOKEN)
                    {
                        m_err = "not found type after ':'";
                        return ERR_NORMAL;
                    }

                    Length = GetSizeFromType(sizebuf[0]);
                    if (Length == -1)
                    {
                        m_err.Format("unknown type '%c' after ':'", sizebuf[0]);
                        return ERR_NORMAL;
                    }
                }
                else
                {
                    Length = -1;
                }
                val = new SValueType((int)strtoul(buf, NULL, bHex ? 16 : 10), Length);
                AddMap(m_valmap, str, val);

                if (Length == -1)
                    bSkipGetToken = TRUE;

                r = SYM_INT;
            }
            else if (r == SYM_FLOAT)
            {
                AddMap(m_valmap, str, new SValueType(atof(buf)));
            }
            else
            {
                m_err.Format("not found '[' or ''' or '\"' or number after '@%s'", (LPCTSTR)str);
                return ERR_NORMAL;
            }

            if (m_Option.bIgnoreCase)
                str.MakeUpper();

            if (str == "_DEFI")
            {
                if (r != SYM_INT || val->ival < 1 || val->ival > 4)
                {
                    m_err = "_DEFI must be 1/2/3/4";
                    return ERR_NORMAL;
                }
                m_Option.DefInt = val->ival;
            }
            else if (str == "_DEFF")
            {
                if (r != SYM_INT || val->ival != 4 && val->ival != 8)
                {
                    m_err = "_DEFF must be 4/8";
                    return ERR_NORMAL;
                }
                m_Option.DefFloat = val->ival;
            }
            else if (str == "_MOD")
            {
                if (r != SYM_INT)
                {
                    m_err = "_MOD must be number";
                    return ERR_NORMAL;
                }

                while (m_bin.GetSize() % val->ival)
                    m_bin.Add(0);
            }
            else if (str == "_INCLUDE")
            {
                FILE *fsrc;
                WCHAR szPath[MAX_PATH];
                CByteArray *bin;

                if (m_Option.bIgnoreCase)
                    str.MakeLower();

                if (!m_binmap.Lookup(str, bin))
                    continue;

                m_binmap.RemoveKey(str);

                MultiByteToWideChar(
                    CP_GB2312,
                    0,
                    (LPSTR)bin->GetData(),
                    -1,
                    szPath,
                    countof(szPath));

                delete bin;

                fsrc = m_fsrc;
                m_fsrc = _wfopen(szPath, L"rb");
                if (m_fsrc == NULL)
                {
                    m_fsrc = fsrc;
                    m_err.Format("can't open include file '%S'", szPath);
                    return ERR_SEVERE;
                }
                else
                {
                    EToken r;
                    for(;;)
                    {
                        r = CompilePass1();
                        if (r == ERR_EOF)
                            break;

                        if (r < 0)
                        {
                            if (!ErrorHandlerInternal(GetErrorString(m_err)))
                                break;
                        }

                        if (r == ERR_SEVERE)
                            break;
                    }

                    fclose(m_fsrc);
                    m_fsrc = fsrc;
                    if (r < 0)
                        return r;
                }
            }

            if (bSkipGetToken)
            {
                str = sizebuf;
                r = LastToken;
                goto _SkipGetToken;
            }
        }
        else if (r == SYM_BIN)
        {
            if ((r = GetBinary(m_bin)) < 0) return r;
        }
        else if (r == SYM_STR)
        {
            if ((r = GetString(m_bin)) < 0) return r;
        }
        else if (r == SYM_TOKEN)
        {
            if (!m_binmap.Lookup(str, bin))
            {
                m_err.Format("unknown token '%s'", (LPCTSTR)str);
                return ERR_NORMAL;
            }
            m_bin.Append(*bin);
        }
        else if (r == SYM_LABEL)
        {
            if ((r = GetToken(str)) < 0) return r;
            if (r != SYM_TOKEN)
            {
                m_err = "not found token after '#'";
                return ERR_NORMAL;
            }
            if (m_valmap.Lookup(str, val))
            {
                m_err.Format("already defined label token '%s'", (LPCTSTR)str);
                return ERR_NORMAL;
            }
            m_valmap.SetAt(str, new SValueType(m_bin.GetSize()));
        }
        else if (r == SYM_EXP_BEGIN)
        {
            int i = m_exparr.GetSize();
            do
            {
                int len = m_Option.DefInt;
                BOOL hastype = FALSE;
                exp = new SExpression(m_bin.GetSize(), m_line);
                for(;;)
                {
                    if ((r = GetToken(buf)) < 0)
                    {
                        delete exp;
                        return r;
                    }

                    if (r == SYM_TOKEN)
                    {
                        val = NULL;
                        if (!hastype && len > 0 && m_valmap.Lookup(buf, val) && val->isfloat)
                            len = -m_Option.DefFloat;
                        exp->m_item.Add(buf);
                        if (val != NULL && val->m_size != -1)
                            len = val->isfloat ? -val->m_size : val->m_size;
                    }
                    else if (r == SYM_ADD)
                    {
                        exp->m_item.Add("+");
                    }
                    else if (r == SYM_SUB)
                    {
                        exp->m_item.Add("-");
                    }
                    else if (r == SYM_DEF)
                    {
                        exp->m_item.Add("@");
                    }
                    else if (r == SYM_INT)
                    {
                        exp->m_item.Add(buf);
                    }
                    else if (r == SYM_FLOAT)
                    {
                        if (!hastype && len > 0)
                            len = -m_Option.DefFloat;
                        exp->m_item.Add(buf);
                    }
                    else if (r == SYM_TYPE)
                    {
                        int newlen;
                        if ((r = GetToken(buf)) < 0) { delete exp; return r; }
                        if (r != SYM_TOKEN)
                        {
                            delete exp;
                            m_err = "not found type after ':'";
                            return ERR_NORMAL;
                        }

                        newlen = GetSizeFromType(buf[0]);
                        if (newlen == -1)
                        {
                            delete exp;
                            m_err.Format("unknown type '%c' after ':'", buf[0]);
                            return ERR_NORMAL;
                        }

                        if (hastype && newlen != len)
                        {
                            delete exp;
                            m_err = "found different types in one expression";
                            return ERR_NORMAL;
                        }
                        hastype = TRUE;
                        len = newlen;
                    }
                    else if (r == SYM_BIN)
                    {
                        if (exp->m_item.GetSize() > 0)
                        {
                            delete exp;
                            m_err = "found different types in one expression";
                            return ERR_NORMAL;
                        }
                        if ((r = GetBinary(m_bin)) < 0) { delete exp; return r; }
                    }
                    else if (r == SYM_STR)
                    {
                        if (exp->m_item.GetSize() > 0)
                        {
                            delete exp;
                            m_err = "found different types in one expression";
                            return ERR_NORMAL;
                        }
                        if ((r = GetString(m_bin)) < 0) { delete exp; return r; }
                    }
                    else if (r == SYM_NEXT || r == SYM_EXP_END)
                    {
                        break;
                    }
                    else
                    {
                        delete exp;
                        m_err.Format("unknown or bad symbol1 '%s' in expression", (LPCTSTR)str);
                        return ERR_NORMAL;
                    }
                }
                if (exp->m_item.GetSize() <= 0)
                {
                    delete exp;
                }
                else
                {
                    exp->m_size = len;
                    m_exparr.Add(exp);
                    if (len < 0) len = -len;
                    while(len--)
                        m_bin.Add(0);
                }
            }
            while(r != SYM_EXP_END);
            for(int j = m_exparr.GetSize(); i < j; ++i)
                m_exparr[i]->m_self = m_bin.GetSize();
        }
        else
        {
            m_err.Format("unknown or bad symbol2 '%s'", (LPCTSTR)str);
            return ERR_NORMAL;
        }
    }
}
Esempio n. 6
0
bool CPkiCard::PinCmd(tPinOperation operation, const tPin & Pin,
        const std::string & csPin1, const std::string & csPin2,
        unsigned long & ulRemaining, const tPrivKey *pKey)
{
	// No standard for Logoff, so each card has to implement
	// it's own command here.
	if (operation == PIN_OP_LOGOFF )
		return LogOff(Pin);

	bool bRet = false;
	std::string csReadPin1, csReadPin2;
	const std::string *pcsPin1 = &csPin1;
	const std::string *pcsPin2 = &csPin2;
	bool bAskPIN = csPin1.empty();
	bool bUsePinpad = bAskPIN ? m_poPinpad->UsePinpad(operation) : false;

bad_pin:
     //If no Pin(s) provided and it's no Pinpad reader -> ask Pins
    if (bAskPIN && !bUsePinpad)
	{
        showPinDialog(operation, Pin, csReadPin1, csReadPin2, pKey);
		pcsPin1 = &csReadPin1;
		pcsPin2 = &csReadPin2;
	}

    CByteArray oPinBuf = MakePinBuf(Pin, *pcsPin1, bUsePinpad);
    if (operation != PIN_OP_VERIFY)
        oPinBuf.Append(MakePinBuf(Pin, *pcsPin2, bUsePinpad));

    CByteArray oAPDU = MakePinCmd(operation, Pin); // add CLA, INS, P1, P2
    oAPDU.Append((unsigned char) oPinBuf.Size());  // add P3
    oAPDU.Append(oPinBuf);

	CByteArray oResp;
	bool bSelected = false;

	// Don't remove these brackets!!
	{
		CAutoLock autolock(this);

		// Select the path where the Pin is, if necessary
		if (!Pin.csPath.empty() && !bSelected && Pin.csPath != "3F00")
		{
			SelectFile(Pin.csPath);
			bSelected = true;
		}

		// Send the command
		if (csPin1.empty() && bUsePinpad)
			oResp = m_poPinpad->PinCmd(operation, Pin,
			PinUsage2Pinpad(Pin, pKey), oAPDU, ulRemaining);
		else
			oResp = SendAPDU(oAPDU);
	}

    unsigned long ulSW12 = getSW12(oResp);
    if (ulSW12 == 0x9000)
        bRet = true;
    else if (ulSW12 == 0x6983)
        ulRemaining = 0;
    else if (ulSW12 / 16 == 0x63C)
        ulRemaining = ulSW12 % 16;
	else
		throw CMWEXCEPTION(m_poContext->m_oPCSC.SW12ToErr(ulSW12));

#ifndef NO_DIALOGS
	// Bad PIN: show a dialog to ask the user to try again
	// PIN blocked: show a dialog to tell the user
	if (bAskPIN && !bRet)
	{
		DlgPinUsage usage = PinUsage2Dlg(Pin, pKey);
		DlgRet dlgret = DlgBadPin(usage, utilStringWiden(Pin.csLabel).c_str(), ulRemaining);
		if (0 != ulRemaining && DLG_RETRY == dlgret)
			goto bad_pin;
	}
#endif

	// If PIN command OK and no SSO, then state that we have now
	// verified this PIN, this info is needed in the Sign() method
	if (bRet && !m_poContext->m_bSSO)
	{
		bool bFound = false;
		for (size_t i = 0; i < m_verifiedPINs.size() && !bFound; i++)
			bFound = (m_verifiedPINs[i] == Pin.ulID);
		if (!bFound)
			m_verifiedPINs.push_back(Pin.ulID);
	}

	return bRet;
}
Esempio n. 7
0
BOOL bGetMsgInfoFromMsgStr( CONST CString& omSendMsgLine,
                            PSTCANDATA psCANData,
                            BOOL bHexON)
{
    CString omStrTemp       ="";
    CString omStrMsgID      ="";
    CString omStrDLC        ="";
    CString omStrData       ="";
    CString omStrMsgIDType  ="";
    CHAR* pcStopString      = nullptr;
    BOOL nReturn            = FALSE;

    CByteArray omByteArrayDataTx;
    // Get the string before first white space charactor
    omStrTemp = omSendMsgLine.SpanExcluding("\t ");
    if(omStrTemp.IsEmpty()==0)
    {
        INT nIndex = omStrTemp.GetLength();
        if(nIndex>0)
        {
            // Remove the time stamp string
            omStrTemp = omSendMsgLine.Right(omSendMsgLine.GetLength() -
                                            nIndex -1);
            if(omStrTemp.IsEmpty() ==0)
            {
                omStrTemp.TrimLeft();
                omStrTemp.TrimRight();
                // Get the message ID after removing Tx/Rx string
                omStrMsgID = omStrTemp.SpanExcluding("\t ");
                if( omStrMsgID.Compare("Tx") == 0 )
                {
                    psCANData->m_ucDataType = TX_FLAG;
                }
                else
                {
                    psCANData->m_ucDataType = RX_FLAG;
                }
                nIndex     = omStrMsgID.GetLength();
                omStrTemp  = omStrTemp.Right(omStrTemp.GetLength() - nIndex - 1);
                omStrTemp.TrimLeft();
                // Channel ID
                omStrMsgID = omStrTemp.SpanExcluding("\t ");
                UCHAR ucChannel    =
                    (UCHAR) strtol( (LPCTSTR )omStrMsgID,&pcStopString ,10);
                nIndex     = omStrMsgID.GetLength();
                omStrTemp  = omStrTemp.Right(omStrTemp.GetLength() - nIndex -1);

                omStrTemp.TrimLeft();
                // Get the message with name
                omStrMsgID = omStrTemp.SpanExcluding("\t ");
                // Get the rest of the string.
                nIndex     = omStrMsgID.GetLength();
                omStrTemp  = omStrTemp.Right(omStrTemp.GetLength() - nIndex -1);
                omStrTemp.TrimLeft();

                // Get message ID string after removing any message name.
                omStrMsgID = omStrMsgID.SpanExcluding(defMSGID_NAME_DELIMITER);
                UINT unMsgID = 0;
                if( bHexON == TRUE)
                {
                    unMsgID    =
                        (UINT) strtol( (LPCTSTR )omStrMsgID,&pcStopString ,16);
                }
                else
                {
                    unMsgID    =
                        (UINT) strtol( (LPCTSTR )omStrMsgID,&pcStopString ,10);
                }

                // Get the message ID Type
                omStrMsgIDType = omStrTemp.SpanExcluding("\t ");
                // Message Id type is EXTENDED
                if(omStrMsgIDType.Find(defMSGID_EXTENDED) != -1)
                {
                    psCANData->m_uDataInfo.m_sCANMsg.m_ucEXTENDED = 1;
                }// Message Id type is STD
                else if(omStrMsgIDType.Find(defMSGID_STD)!= -1)
                {
                    psCANData->m_uDataInfo.m_sCANMsg.m_ucEXTENDED = 0;
                }
                // Message Id type is RTR
                if(omStrMsgIDType.Find(defMSGID_RTR)!= -1)
                {
                    psCANData->m_uDataInfo.m_sCANMsg.m_ucRTR = 1;
                }
                else
                {
                    psCANData->m_uDataInfo.m_sCANMsg.m_ucRTR = 0;
                }
                nIndex     = omStrMsgIDType.GetLength();
                omStrTemp  = omStrTemp.Right(omStrTemp.GetLength() - nIndex -1);
                omStrTemp.TrimLeft();

                // Get the DLC
                omStrDLC   = omStrTemp.SpanExcluding("\t ");
                nIndex     = omStrDLC.GetLength();
                UINT unDLC = (UINT) strtol((LPCTSTR)omStrDLC,&pcStopString ,16);
                omStrTemp  = omStrTemp.Right(omStrTemp.GetLength() - nIndex -1);

                omStrTemp.TrimLeft();
                // Get the data string
                omStrData  = omStrTemp;

                // Check if Message ID and DLC is valid.
                if(unMsgID>0 && unDLC<=8 && unDLC>0)
                {
                    nIndex = omStrData.GetLength();
                    vConvStrtoByteArray(&omByteArrayDataTx,
                                        omStrData.GetBuffer(nIndex),bHexON);
                    omStrData.ReleaseBuffer(nIndex);
                    INT nTotalData = (INT)omByteArrayDataTx.GetSize();
                    // Check if String to Byte array conversion
                    // has return a valid data
                    if(nTotalData<=8 )
                    {

                        for(INT i = 0; i<nTotalData; i++)
                        {
                            psCANData->m_uDataInfo.m_sCANMsg.m_ucData[i] =
                                omByteArrayDataTx.GetAt(i);
                        }
                        psCANData->m_uDataInfo.m_sCANMsg.m_unMsgID = unMsgID;
                        psCANData->m_uDataInfo.m_sCANMsg.m_ucDataLen   = (UCHAR)unDLC;
                        psCANData->m_uDataInfo.m_sCANMsg.m_ucChannel = ucChannel;
                        nReturn    = TRUE;
                    }
                }
            }
        }
    }
    return nReturn;
}
Esempio n. 8
0
BOOL CTobCompiler::CompileFile(LPWSTR fsrcname, LPWSTR fdstname, F_ErrorHandler ErrorHandler)
{
    WChar szOutput[MAX_PATH];
    CString err;
    BOOL haserr = FALSE;

    Reset();

    m_line = 1;

    m_fsrc = _wfopen(fsrcname, L"rb");
    if (!m_fsrc)
    {
        m_err.Format("can't open src file '%S'", fsrcname);
        (this->*ErrorHandler)(GetErrorString(err));
        return FALSE;
    }

    for(;;)
    {
        EToken r = CompilePass1();
        if (r == ERR_EOF)
            break;

        if (r < 0)
        {
            haserr = TRUE;
            if (!(this->*ErrorHandler)(GetErrorString(err)))
                return FALSE;
        }

        if (r == ERR_SEVERE)
            return FALSE;
    }

    fclose(m_fsrc);
    m_fsrc = 0;

    if (!CompilePass2(ErrorHandler) || haserr)
        return FALSE;

    if (fdstname == NULL)
    {
        CByteArray* bin;
        if (m_binmap.Lookup("_FILE", bin) && bin->GetSize() > 0)
        {
            MultiByteToWideChar(
                CP_GB2312,
                0,
                (LPSTR)bin->GetData(),
                bin->GetSize(),
                szOutput,
                countof(szOutput));
            fdstname = szOutput;
        }
        else
        {
            LPWSTR pszExtension;

            lstrcpyW(szOutput, fsrcname);
            pszExtension = findextw(szOutput);
            !lstrcmpiW(pszExtension, L".bin") ? lstrcatW(pszExtension, L".bin") : lstrcpyW(pszExtension, L".bin");
            fdstname = szOutput;
        }
    }

    m_fdst = _wfopen(fdstname, L"wb");
    if (m_fdst == NULL)
    {
        m_err.Format("can't create dst file '%S'", fdstname);
        (this->*ErrorHandler)(GetErrorString(err));
        return FALSE;
    }

    if (m_bin.GetSize() > 0 && fwrite(m_bin.GetData(), m_bin.GetSize(), 1, m_fdst) != 1)
    {
        fclose(m_fdst); m_fdst = 0;
        m_err.Format("can't write dst file '%S'", fdstname);
        (this->*ErrorHandler)(GetErrorString(err));
        return FALSE;
    }

    fclose(m_fdst);
    m_fdst = NULL;

    return TRUE;
}
Esempio n. 9
0
// Write Operation
void CFanmotorDlg::wreg(int reg_addr, int datr)
{
	success=1;

	VARIANT r;
	CByteArray baData;
	CStringArray dataStr;

	//separate input 2 bytes datr into 1byte + 1byte
	int datrH=datr/256;
	int datrL=datr%256;

	CString regstring;
	regstring.Format(_T("%02x "),reg_addr);
	CString strinputH;
    strinputH.Format(_T("%02x "),datrH);
	CString strinputL;
    strinputL.Format(_T("%02x"),datrL);

	CString str = regstring+strinputH+strinputL;

	
	int timeout_counter=0;

	if(this->virtual_board)
	{
		WriteVirtualBoardReg(reg_addr, datr, fOTP);
		return;
	}


	int parseResult = ParseString(dataStr,str);
	if (parseResult != -1){
		AfxMessageBox(L"Incorrect Data (\""+dataStr[parseResult]+L"\") is Typed. Please correct it",
						MB_ICONERROR | MB_OK,0);
		return;
	}
	else{
		if (dataStr.GetSize() == 0) {
			AfxMessageBox(L"Type some HEX data to send!",MB_ICONERROR | MB_OK,0);
			return;
		}
	}
	for (int i=0; i<dataStr.GetSize(); i++) {
		WCHAR *ch,*buf;
		buf = dataStr[i].GetBuffer(dataStr[i].GetLength());
		BYTE dataByte = (BYTE)wcstol(buf,&ch,16);
		dataStr[i].ReleaseBuffer();
		baData.Add(dataByte);
	}

	COleVariant data(baData); // Create array of Data
	// Send Data To Bridge

	r = Bridge->SendIICdata(L"0000011", 0x49, data);//spi comm, no acknowledge signal return to r.cannot check connection success.

	//do{
	//	timeout_counter++;
	//	if (timeout_counter == TIMEOUT){
	//		DisplayInforMessageBox((LPCWSTR)L"Error", (LPCWSTR)L"Device is not available.\nPlease check your hardware connection and power supply!");
	//		success = 0;
	//	}
	//	r = Bridge->SendIICdata(L"0000011", 0x49, data); 
	//}while ((r.bVal != 34) && (timeout_counter != TIMEOUT));

    Sleep(20);
end:;
}
Esempio n. 10
0
BOOL ConvertStringToSendData(const CString & s, CByteArray & msg)
    {
#ifdef _UNICODE
     int n = ::WideCharToMultiByte(CP_UTF8, 0, s, -1, NULL, 0, NULL, NULL);
     if(n == 0)
        { /* failed */
         //DWORD err = ::GetLastError();
         msg.SetSize(0);
         return FALSE;
        } /* failed */
     else
        { /* success */
         msg.SetSize(n);
         n = ::WideCharToMultiByte(CP_UTF8, 0, s, -1, (LPSTR)msg.GetData(), n, NULL, NULL);
         if(n == 0)
            { /* conversion failed */
             DWORD err = ::GetLastError();
             msg.SetSize(0);
             return FALSE;
            } /* conversion failed */
         else
            { /* use multibyte string */
             msg.SetSize(n - 1);
             return TRUE;
            } /* use multibyte string */
        } /* success */
#else // ANSI
     CArray<WCHAR, WCHAR> wc;

     int n = ::MultiByteToWideChar(CP_ACP, 0, s, -1, NULL, 0);
     if(n == 0)
        { /* failed */
         DWORD err = ::GetLastError();
         msg.SetSize(0);
         return FALSE;
        } /* failed */
     else
        { /* success */
         wc.SetSize(n);
         n = ::MultiByteToWideChar(CP_ACP, 0, s, -1, wc.GetData(), n);
        } /* success */     

     n = ::WideCharToMultiByte(CP_UTF8, 0, wc.GetData(), -1, NULL, 0, NULL, NULL);
     if(n == 0)
        { /* failed */
         DWORD err = ::GetLastError();
         msg.SetSize(0);
         return FALSE;
        } /* failed */
     else
        { /* success */
         msg.SetSize(n);
         n = ::WideCharToMultiByte(CP_UTF8, 0, wc.GetData(), -1, (LPSTR)msg.GetData(), n, NULL, NULL);
         if(n == 0)
            { /* conversion failed */
             DWORD err = ::GetLastError();
             msg.SetSize(0);
             return FALSE;
            } /* conversion failed */
         else
            { /* use multibyte string */
             msg.SetSize(n - 1);
             return TRUE;
            } /* use multibyte string */
        } /* success */
#endif
    } // ConvertStringToSendData
Esempio n. 11
0
/**
* @brief 从7张牌中分析出5张最大牌型
* @param bHandCards[]     要分析的手牌
* @param nCount           手牌张数
* @param bPublicCards[]   要分析公共牌
* @param nPublicCount     公共牌张数
* @param bResultCard[]    返回分析得到的数据牌
* @return 牌型
*/
int CUpGradeGameLogic::AnalysisCard(BYTE bHandCards[], int nHandCount, BYTE bPublicCards[], int nPublicCount, BYTE bResultCard[])
{
    if ((nHandCount + nPublicCount) != 7)
    {
        return 0;
    }
    
    int i, j;
    CByteArray arrCards;

    for (i = 0; i < nHandCount; i++)
    {
        arrCards.Add(bHandCards[i]);
    }
    
    for (i = 0; i < nPublicCount; i++)
    {
        arrCards.Add(bPublicCards[i]);
    }

    BYTE bCard[5] = {0};
    int nCardKind[21] = {0};

    //// 21种组成方法
    //BYTE bIndex[21][5] = {0, 1, 2, 3, 4, \
    //                      0, 1, 2, 3, 5, \
    //                      0, 1, 2, 3, 6, \
    //                      0, 1, 2, 4, 5, \
    //                      0, 1, 2, 4, 6, \
    //                      0, 1, 2, 5, 6, \
    //                      0, 1, 3, 4, 5, \
    //                      0, 1, 3, 4, 6, \
    //                      0, 1, 3, 5, 6, \
    //                      0, 1, 4, 5, 6, \
    //                      0, 2, 3, 4, 5, \
    //                      0, 2, 3, 4, 6, \
    //                      0, 2, 3, 5, 6, \
    //                      0, 2, 4, 5, 6, \
    //                      0, 3, 4, 5, 6, \
    //                      1, 2, 3, 4, 5, \
    //                      1, 2, 3, 4, 6, \
    //                      1, 2, 3, 5, 6, \
    //                      1, 2, 4, 5, 6, \
    //                      1, 3, 4, 5, 6, \
    //                      2, 3, 4, 5, 6, \
    //                     };

	// 21种组成方法
	BYTE bIndex[21][7] = {0, 1, 2, 3, 4, 5, 6,
		                  0, 1, 2, 3, 5, 4, 6,
		                  0, 1, 2, 3, 6, 4, 5,
		                  0, 1, 2, 4, 5, 3, 6,
		                  0, 1, 2, 4, 6, 3, 5,
		                  0, 1, 2, 5, 6, 3, 4,
		                  0, 1, 3, 4, 5, 2, 6,
		                  0, 1, 3, 4, 6, 2, 5,
		                  0, 1, 3, 5, 6, 2, 4, 
		                  0, 1, 4, 5, 6, 2, 3, 
		                  0, 2, 3, 4, 5, 1, 6, 
		                  0, 2, 3, 4, 6, 1, 5, 
		                  0, 2, 3, 5, 6, 1, 4, 
		                  0, 2, 4, 5, 6, 1, 3, 
		                  0, 3, 4, 5, 6, 1, 2, 
		                  1, 2, 3, 4, 5, 0, 6, 
		                  1, 2, 3, 4, 6, 0, 5, 
		                  1, 2, 3, 5, 6, 0, 4, 
		                  1, 2, 4, 5, 6, 0, 3, 
		                  1, 3, 4, 5, 6, 0, 2, 
		                  2, 3, 4, 5, 6, 0, 1
						 };

    for (i = 0; i < 21; i++)
    {	
        for (j = 0; j < 5; j++)
        {
            // 按牌下标取出5张牌
            bCard[j] = arrCards.GetAt(bIndex[i][j]);
        }
      
        // 获取牌型
        nCardKind[i] = GetCardShape(bCard, 5);

		//CString str;
		//str.Format("dxh: 第%d种方法, 牌型: %d",  i, nCardKind[i]);
		//OutputDebugString(str);
    }

    // 取最大牌型位置
    int nMax = 0;
    for (i = 1; i < 21; i++)
    {
        if (nCardKind[i] > nCardKind[nMax])
        {
            nMax = i;
        }
    }

    BYTE bCompareCard1[5], bCompareCard2[5];
    int nCompareMax = nMax;

    // 找出最大牌型后, 再找出相同牌型最大牌组合(牌型一样情况下, 则会比大小, 所以这里就需要取最大的相同的牌型)
    for (i = 0; i < 21; i++)
    {
        if (i == nMax)
        {
            continue;
        }

        for (j = 0; j < 5; j++)
        {
            bCompareCard1[j] = arrCards.GetAt(bIndex[i][j]);
            bCompareCard2[j] = arrCards.GetAt(bIndex[nCompareMax][j]);
        }
        
        // 比牌(-1:输, 0:和, 1:赢)
        if (CompareCard(bCompareCard1, 5, bCompareCard2, 5) > 0)
        {
            nCompareMax = i;
        }
    }

    // 从7张手牌中取出5终最终牌型
    for (i = 0; i < 7; i++)
    {
        bResultCard[i] = arrCards.GetAt(bIndex[nCompareMax][i]);
    }

	CString str;
	str.Format("dxh: 当前最大牌型索引: %d, 牌型ID:%d", nCompareMax, nCardKind[nCompareMax]);
	OutputDebugString(str);

    return nCardKind[nCompareMax];
}
Esempio n. 12
0
CByteArray CHash::Hash(tHashAlgo algo, const CByteArray & data)
{
	return Hash(algo, data, 0, data.Size());
}
Esempio n. 13
0
void CHash::Update(const CByteArray & data)
{
	Update(data, 0, data.Size());
}
Esempio n. 14
0
CByteArray CPinpadLibOldBeid::PinCmd(SCARDHANDLE hCard, unsigned long ulControl,
	CByteArray oCmd, unsigned char ucPintype, unsigned char ucOperation)
{
	if (ulControl == CCID_IOCTL_GET_FEATURE_REQUEST)
	{
		unsigned char tucFeatures[] = {0x06, 0x04, 0x00, 0x31, 0x32, 0x33, 0x07, 0x04, 0x00 ,0x31, 0x32, 0x33};
		return CByteArray(tucFeatures, sizeof(tucFeatures));
	}

	SCR_Card xCard = {
		hCard,
		tcsLangs[m_iLangIdx],
		{NULL, 0},
		NULL
	};
	unsigned char tucStatus[2];
	long lRet = SCARD_F_INTERNAL_ERROR;

	if (ucOperation == EIDMW_PP_OP_VERIFY)
	{
		SCR_PinUsage xPinUsage = {
			ucPintype == EIDMW_PP_TYPE_SIGN ? SCR_USAGE_SIGN: SCR_USAGE_AUTH,
			ucPintype == EIDMW_PP_TYPE_SIGN ? "SIG" : "AUT",
			ucPintype == EIDMW_PP_TYPE_SIGN ? tcsUsageSig[m_iLangIdx] : tcsUsageAuth[m_iLangIdx]
		};

		lRet = m_pVerifyPin(&xCard, oCmd.GetByte(22), &xPinUsage, &xApp, tucStatus);
	}
	else if (ucOperation == EIDMW_PP_OP_CHANGE)
	{
		lRet = m_pChangePin(&xCard, oCmd.GetByte(27), &xApp, tucStatus);	
	}
	else
		throw CMWEXCEPTION(EIDMW_ERR_PIN_OPERATION);

	CByteArray oResp(2);
	switch(lRet)
	{
	case SCARD_S_SUCCESS:
		if (tucStatus[0] == 0xEC && tucStatus[1] == 0xD2)
			oResp.Append(tucErrTimeout, sizeof(tucErrTimeout));
		else if (tucStatus[0] == 0xEC && tucStatus[1] == 0xD6)
			oResp.Append(tucErrCancel, sizeof(tucErrCancel));
		else
			oResp.Append(tucStatus, 2);
		break;
	case SCARD_E_CANCELLED:
		oResp.Append(tucErrCancel, sizeof(tucErrCancel));
		break;
	case SCARD_W_REMOVED_CARD:
		throw CMWEXCEPTION(EIDMW_ERR_NO_CARD);
		break;
	case SCR_I_PIN_CHECK_FAILED:
		oResp.Append(tucErrPinsDiffer, sizeof(tucErrPinsDiffer));
		break;
	default:
		oResp.Append(tucErrGeneral, sizeof(tucErrGeneral));
	}

	return oResp;
}
Esempio n. 15
0
void CByteArray::Append(const CByteArray & oByteArray)
{
    Append(oByteArray.GetBytes(), oByteArray.Size());
}
Esempio n. 16
0
BOOL CDaoFieldExchange::CompareValue(void* pvSrc, void* pvDest,
	DWORD dwDataType)
{
	BOOL bDirty = FALSE;

	switch (dwDataType)
	{
	default:
		ASSERT(FALSE);
		break;

	case AFX_RFX_TEXT:
		if (*(CString*)pvDest != *(CString*)pvSrc)
			bDirty = TRUE;
		break;

	case AFX_RFX_BINARY:
		{
			CByteArray* pByteArraySrc = (CByteArray*)pvSrc;
			CByteArray* pByteArrayDest = (CByteArray*)pvDest;

			int nSize = pByteArraySrc->GetSize();
			// If sizes don't compare, must be dirty
			if (nSize != pByteArrayDest->GetSize())
				bDirty = TRUE;
			else
			{
				// If sizes compare, compare the data
				if (memcmp(&pByteArrayDest[0], &pByteArraySrc[0], nSize) != 0)
					bDirty = TRUE;
			}
		}
		break;

	case AFX_RFX_LONGBINARY:
		{
			CLongBinary* pLongBinarySrc = (CLongBinary*)pvSrc;
			CLongBinary* pLongBinaryDest = (CLongBinary*)pvDest;

			BYTE* pbSrc = (BYTE*)::GlobalLock(pLongBinarySrc->m_hData);
			BYTE* pbDest = (BYTE*)::GlobalLock(pLongBinaryDest->m_hData);

			// If sizes don't compare, must be dirty
			if (pLongBinarySrc->m_dwDataLength !=
				pLongBinaryDest->m_dwDataLength)
			{
				bDirty = TRUE;
			}
			else
			{
				// If sizes compare, compare the data
				if (memcmp(pbDest, pbSrc, pLongBinarySrc->m_dwDataLength) != 0)
					bDirty = TRUE;
			}

			::GlobalUnlock(pLongBinarySrc->m_hData);
			::GlobalUnlock(pLongBinaryDest->m_hData);
		}
		break;

	case AFX_RFX_BOOL:
		if (*(BOOL*)pvDest != *(BOOL*)pvSrc)
			bDirty = TRUE;
		break;

	case AFX_RFX_BYTE:
		if (*(BYTE*)pvDest != *(BYTE*)pvSrc)
			bDirty = TRUE;
		break;

	case AFX_RFX_SHORT:
		if (*(short*)pvDest != *(short*)pvSrc)
			bDirty = TRUE;
		break;

	case AFX_RFX_LONG:
		if (*(long*)pvDest != *(long*)pvSrc)
			bDirty = TRUE;
		break;

	case AFX_RFX_CURRENCY:
		if (*(COleCurrency*)pvDest != *(COleCurrency*)pvSrc)
			bDirty = TRUE;
		break;

	case AFX_RFX_SINGLE:
		if (*(float*)pvDest != *(float*)pvSrc)
			bDirty = TRUE;
		break;

	case AFX_RFX_DOUBLE:
		if (*(double*)pvDest != *(double*)pvSrc)
			bDirty = TRUE;
		break;

	case AFX_RFX_DATE:
		if (*(COleDateTime*)pvDest != *(COleDateTime*)pvSrc)
			bDirty = TRUE;
		break;
	}

	return bDirty;
}
Esempio n. 17
0
//copy object into new object
CByteArray::CByteArray(const CByteArray & oByteArray)
{
    MakeArray(oByteArray.GetBytes(), oByteArray.Size());
}
Esempio n. 18
0
CTobCompiler::EToken CTobCompiler::GetString(CByteArray& bin)
{
    CByteArray temp;
    int c, d, e;
    for(;;)
    {
        if ((c = fgetc(m_fsrc)) < 0) break;
        if (c == '\n') ++m_line;
        else if (ms_tokentable[c] == 3)
        {
            m_err.Format("found invalid char 0x%02X in src file at %p", c, ftell(m_fsrc)-1);
            return ERR_NORMAL;
        }
        else if (c < ' ') continue;
        else if (c == '\'' || c == '"')
        {
            if ((d = fgetc(m_fsrc)) > 0)
            {
                if (d == ':')
                {
                    if ((d = fgetc(m_fsrc)) < 0) break;
                    e = GetSizeFromType(d);
                    if (e == -1)
                    {
                        m_err.Format("unknown type '%c' after ':'", d);
                        return ERR_NORMAL;
                    }

                    d = temp.GetSize();
                    for(int i = 0; i < e; ++i)
                        bin.Add(((BYTE*)&d)[i]);
                }
                else if (fseek(m_fsrc, -1, SEEK_CUR))
                {
                    m_err.Format("can not seek src file at %p", ftell(m_fsrc));
                    return ERR_SEVERE;
                }
            }
            bin.Append(temp);
            if (c == '"')
                bin.Add(0);

            if (m_Option.bIgnoreCase)
                strlwr((LPSTR)bin.GetData());
            return SYM_STR;
        }
        else if (c == '\\')
        {
            if ((c = fgetc(m_fsrc)) < 0) break;
            switch(CHAR_UPPER(c))
            {
                case 'N': c = '\n';   break;
                case 'R': c = '\r';   break;
                case 'T': c = '\t';   break;
                case '0': c = '\0';   break;
                case '1': c = '\x01'; break;
                case '2': c = '\x02'; break;
                case '3': c = '\x03'; break;
                case '4': c = '\x04'; break;
                case '5': c = '\x05'; break;
                case '6': c = '\x06'; break;
                case '7': c = '\x07'; break;
                case '8': c = '\x08'; break;
                case '9': c = '\x09'; break;
                case 'A': c = '\x0a'; break;
                case 'B': c = '\x0b'; break;
                case 'C': c = '\x0c'; break;
                case 'D': c = '\x0d'; break;
                case 'E': c = '\x0e'; break;
                case 'F': c = '\x0f'; break;
                case 'X':
                {
                    if ((c = fgetc(m_fsrc)) < 0) goto end_;
                    BYTE b0 = ms_hextable[c];
                    if (b0 == 16)
                    {
                        m_err.Format("bad hex char 0x%02X after '\\x'", b0);
                        return ERR_NORMAL;
                    }
                    if ((c = fgetc(m_fsrc)) < 0) goto end_;
                    BYTE b1 = ms_hextable[c];
                    if (b1 == 16)
                    {
                        m_err.Format("bad hex char 0x%02X after '\\x'", b1);
                        return ERR_NORMAL;
                    }
                    temp.Add((BYTE)((b0<<4) + b1));
                }
            }
        }
        if (c >= 0x81)
        {
            if ((d = fgetc(m_fsrc)) < 0) break;
            if (d < 0x40)
            {
                if (fseek(m_fsrc, -1, SEEK_CUR))
                {
                    m_err.Format("can not seek src file at %p", ftell(m_fsrc));
                    return ERR_SEVERE;
                }
                m_err.Format("found half wide char at %p", ftell(m_fsrc)-1);
                return ERR_NORMAL;
            }
            temp.Add((BYTE)c);
            temp.Add((BYTE)d);
        }
        else
        {
            temp.Add((BYTE)c);
        }
    }
end_:
    if (!feof(m_fsrc))
        m_err.Format("can not read src file at %p", ftell(m_fsrc));
    else
        m_err = "bad string at the end of src file";
    return ERR_SEVERE;
}
Esempio n. 19
0
void CPrefView::DoWithRgn(int ID)
{
	int MaxL=m_pM->m_robast-1; //m_pG->m_scale->GetGradation()-1;
	CByteArray* P;
	int ps=0;
	
	m_Grid.SetHighLight(0);
	CApprox Model;
	Model.SetDimention(2);
	int maxDim=m_Grid.GetCols()*m_Grid.GetRows();
	double *w=new double[maxDim];
	double **MX=Model.Matrix(maxDim,2);
	double xn[2];
	int NumPoints=0;
	int sl_ps=m_Slider.GetPos();
		
	CString	Buff=m_pG->m_scale->GetLex(ps);
	int xx=m_Grid.GetCol();		int yy=m_Grid.GetRow();
	int xs=m_Grid.GetColSel();	int ys=m_Grid.GetRowSel();
	int i0=min(ys,yy);	int i1=max(ys,yy);
	int j0=min(xs,xx);	int j1=max(xs,xx);
	if (ID==ID_MENUITEM_UNDO)
	{
		P=(CByteArray*)m_UndoP.RemoveTail();
		m_pM->m_P.Copy(*P);
		delete P;
		i0=1; i1=m_Grid.GetRows()-1;
		j0=1; j1=m_Grid.GetCols()-1;
	}
	else
	{
		P=new CByteArray();
		P->Copy(m_pM->m_P);
		m_UndoP.AddTail(P);
		if (m_UndoP.GetCount()>10)
		{
			P=(CByteArray*)m_UndoP.RemoveHead();
			delete P;
		}
	}

	if (ID==ID_MENUITEM_COPY) m_clP.SetSize(i1-i0+1);
	if (ID==ID_MENUITEM_INSERT)
	{
		if (m_clP.GetSize()==0)
		{
			AfxMessageBox("В буфере не данных!!!");
			return;
		}

		if ((i1==i0)&&(j1==j0)) 
		{
			i1=i0+m_clP.GetSize()-1;
			j1=j0+m_clP[0].GetSize()-1;
		}
		if ((m_clP.GetSize()!=(i1-i0+1))
			||(i1>=m_Grid.GetRows())||(j1>=m_Grid.GetCols()))
		{
			AfxMessageBox("Не верный размер области вставки");
			return;
		}
	}
	int n=m_pG->m_agr.GetCount();
	int* u= new int[n];
	for (int j=0; j<n; j++) u[j]=m_U[j];
	m_ComboX.GetWindowText(Buff);
	int x=GetIndex(Buff,m_pG);
	int y=0;
	m_ComboY.GetWindowText(Buff);
	if (Buff!="") y=GetIndex(Buff,m_pG);
	for (int i=i0; i<=i1; i++)
	{
		if (ID==ID_MENUITEM_COPY) m_clP[i-i0].SetSize(j1-j0+1);
		if ((ID==ID_MENUITEM_INSERT)&&(m_clP[i-i0].GetSize()!=(j1-j0+1)))
		{
			AfxMessageBox("Не верный размер области вставки");
			delete [] u;
			return;
		}
		m_Grid.SetRow(i);
		for (int j=j0; j<=j1; j++)
		{
			m_Grid.SetCol(j);
			u[x]=j-1;
			if (!Buff.IsEmpty()) u[y]=i-1;
			switch (ID)
			{
			case ID_MENUITEM_INCL:
				ps=m_pM->GetPreferance(u);
				if (ps<MaxL)  ps++;
				break;
			case ID_MENUITEM_DECL:
				ps=m_pM->GetPreferance(u);
				if ((ps>0)&&(ps<=MaxL))  ps--;
				break;
			case ID_MENUITEM_COPY:
				ps=m_pM->GetPreferance(u);
				m_clP[i-i0][j-j0]=ps;
				break;
			case ID_MENUITEM_INSERT:
				ps=m_clP[i-i0][j-j0];
				break;
			case ID_MENUITEM_CLEAR:
				ps=255;
				break;
			case ID_MENUITEM_UNDO:
				ps=m_pM->GetPreferance(u);
				break;
			case IDC_STATIC_SCALE:
				ps=sl_ps;
				break;
			case ID_MENUITEM_APPROX:
				ps=m_pM->GetPreferance(u);
				if (ps<=MaxL)
				{
					MX[NumPoints][0]=i; MX[NumPoints][1]=j;
					w[NumPoints++]=ps;
				}
			}
			m_pM->SetPreference(u,ps);
			SetBitmap(ps,MaxL,0,0);
		}
	}
	if ((ID==ID_MENUITEM_APPROX)&&
		((NumPoints>2)||((NumPoints==2)&&((i0==i1)||(j0==j1))))&&
		(NumPoints<maxDim)
		)
	{
		Model.SetNumPoints(NumPoints);
		Model.LoadPoints(MX,w);
		for (int i=i0; i<=i1; i++)
		{
			m_Grid.SetRow(i);
			for (int j=j0; j<=j1; j++)
			{
				m_Grid.SetCol(j);
				u[x]=j-1;
				if (!Buff.IsEmpty()) u[y]=i-1;
				ps=m_pM->GetPreferance(u);
				if (ps>MaxL) 
				{
					xn[0]=i; xn[1]=j;
					ps=(int) Model.GetPref(xn);
					if (ps<0) ps=0;
					if (ps>MaxL) ps=MaxL;
					m_pM->SetPreference(u,ps);
					SetBitmap(ps,MaxL,0,0);
				}
			}
		}
	}
	Model.RemoveMatrix(maxDim,2,MX);
	delete [] w;
	delete [] u;
	m_Grid.SetRow(yy);		m_Grid.SetCol(xx);
	m_Grid.SetColSel(xs);	m_Grid.SetRowSel(ys);
	
	int index=255;
	m_pG->m_scale->GetIndex(COleVariant((double)(m_pM->GetPreferance(m_U))),index, m_pM);
	Buff=m_pG->m_scale->GetLex(index);
	SetDlgItemText(IDC_EDIT_GOD,Buff);
	m_Grid.SetHighLight(1);
	GetDocument()->SetModifiedFlag();
}
Esempio n. 20
0
CTobCompiler::EToken CTobCompiler::CompilePass1()
{
	EToken r;
	CString str, buf;
	CByteArray* bin = 0;

	for(;;)
	{
		if((r = GetToken(str)) <= 0) return r;
		if(r == SYM_KEY)
		{
			if((r = GetToken(str)) < 0) return r;
			if(r != SYM_TOKEN)
			{
				m_err = "not found keyword after '.'";
				return ERR_NORMAL;
			}
			if(str == "def")
			{
				if((r = GetToken(str)) < 0) return r;
				if(r != SYM_TOKEN)
				{
					m_err = "not found token after '.def'";
					return ERR_NORMAL;
				}
				if((r = GetToken(buf)) < 0) return r;
				if(r == SYM_BIN)
				{
					bin = new CByteArray;
					if((r = GetBinary(*bin)) < 0) { delete bin; return r; }
				}
				else if(r == SYM_STR)
				{
					if((r = GetString(buf, false)) < 0) return r;
					bin = new CByteArray;
					for(LPCTSTR p = buf; *p; ++p) bin->Add(*(U8*)p);
					if(r == SYM_STRING) bin->Add(0);
				}
				else if(r == SYM_STRING)
				{
					if((r = GetString(buf, true)) < 0) return r;
					bin = new CByteArray;
					for(LPCTSTR p = buf; *p; ++p) bin->Add(*(U8*)p);
					if(r == SYM_STRING) bin->Add(0);
				}
				else
				{
					m_err = "not found '[' or ''' or '\"' after '.def <token>''";
					return ERR_NORMAL;
				}
				m_defbin.SetAt(str, bin);
				bin = 0;
			}
			else if(str == "change")
			{
				if((r = GetToken(str)) < 0) return r;
				if(r != SYM_STR)
				{
					m_err = "not found ''' after '.change'";
					return ERR_NORMAL;
				}
				if((r = GetString(str, false)) < 0) return r;
				if( str.IsEmpty() || str.GetLength()>2 || str.GetLength() == 2 && (U8)str[0]<0x80)
				{
					m_err = "only one character is allowed after '.change'";
					return ERR_NORMAL;
				}
				U16 c = (U8)str[0];
				if(str.GetLength() == 2) c = (c<<8) + (U8)str[1];
				if((r = GetToken(str)) < 0) return r;
				if(r == SYM_BIN)
				{
					CByteArray tmp;
					if((r = GetBinary(tmp)) < 0) return r;
					buf.Empty();
					int i, n = tmp.GetSize();
					for(i = 0; i < n; ++i)
					{
						U8 b = tmp.GetAt(i);
						if(!b) break;
						buf += (TCHAR)b;
					}
				}
				else if(r == SYM_STR)
				{
					if((r = GetString(buf, false)) < 0) return r;
				}
				else if(r == SYM_STRING)
				{
					if((r = GetString(buf, true)) < 0) return r;
				}
				else
				{
					m_err = "not found ''' or '\"' after '.change <char>'";
					return ERR_NORMAL;
				}
				m_change.SetAt(c, buf);
			}
			else if(str == "bit")
			{
				if((r = GetToken(str)) < 0) return r;
				if(r != SYM_TOKEN)
				{
					m_err = "not found parameter after '.bit'";
					return ERR_NORMAL;
				}
				int bit = atoi(str);
				if(bit!=8 && bit!=16 && bit!=24 && bit!=32)
				{
					m_err = "only '.bit 8/16/24/32' is available";
					return ERR_NORMAL;
				}
				m_bit_i = bit;
			}
			else if(str == "maxc")
			{
				if((r = GetToken(str)) < 0) return r;
				if(r != SYM_TOKEN)
				{
					m_err = "not found parameter after '.maxc'";
					return ERR_NORMAL;
				}
				m_maxc = atoi(str);
			}
			else if(str == "maxw")
			{
				if((r = GetToken(str)) < 0) return r;
				if(r != SYM_TOKEN)
				{
					m_err = "not found parameter after '.maxw'";
					return ERR_NORMAL;
				}
				m_maxw = atoi(str);
			}
			else if(str == "maxs")
			{
				if((r = GetToken(str)) < 0) return r;
				if(r != SYM_TOKEN)
				{
					m_err = "not found parameter after '.maxs'";
					return ERR_NORMAL;
				}
				m_maxs = atoi(str);
			}
			else
			{
				m_err.Format("unknwon keyword '%s' after '.'", (LPCTSTR)str);
				return ERR_NORMAL;
			}
		}
		else if(r == SYM_BIN)
		{
			if((r = GetBinary(m_bin)) < 0) return r;
		}
		else if(r == SYM_STR)
		{
			if((r = GetString(buf, false)) < 0) return r;
			for(LPCTSTR p=buf;* p; ++p) m_bin.Add(*(U8*)p);
			if(r == SYM_STRING) m_bin.Add(0);
		}
		else if(r == SYM_STRING)
		{
			if((r = GetString(buf, true)) < 0) return r;
			for(LPCTSTR p=buf;* p; ++p) m_bin.Add(*(U8*)p);
			if(r == SYM_STRING) m_bin.Add(0);
		}
		else if(r == SYM_TOKEN)
		{
			if(!m_defbin.Lookup(str, bin))
			{
				m_err.Format("not defined token '%s'", (LPCTSTR)str);
				return ERR_NORMAL;
			}
			m_bin.Append(*bin);
			bin = 0;
		}
		else if(r == SYM_ADDR)
		{
			if((r = GetToken(str)) < 0)
				return r;
			SExpInfo* ti = new SExpInfo(m_bin.GetSize(), m_line);
			if(r == SYM_EXP_BEGIN)
			{
				for(;;)
				{
					if((r = GetToken(buf)) < 0)
					{
						delete ti;
						return r;
					}
					if(r == SYM_TOKEN || r == SYM_NUM)
						ti->m_item.Add(buf);
					else if(r == SYM_ADD)
						ti->m_item.Add("+");
					else if(r == SYM_SUB)
						ti->m_item.Add("-");
					else if(r == SYM_ADDR)
						ti->m_item.Add("@");
					else if(r == SYM_EXP_END)
						break;
					else
					{
						delete ti;
						m_err.Format("found unknown token '%s' in expression", (LPCTSTR)buf);
						return ERR_NORMAL;
					}
				}
			}
			else if(r == SYM_TOKEN)
				ti->m_item.Add(str);
			else
			{
				delete ti;
				m_err = "not found token or expression after '@'";
				return ERR_NORMAL;
			}
			m_exp.Add(ti);
			for(int i = m_bit_i/8; i--;)
				m_bin.Add(0);
		}
		else if(r == SYM_LABEL)
		{
			if((r = GetToken(str)) < 0) return r;
			if(r != SYM_TOKEN)
			{
				m_err = "not found label after '#'";
				return ERR_NORMAL;
			}
			m_label.SetAt(str, m_bin.GetSize());
		}
		else
		{
			m_err = "unknown or bad symbol";
			return ERR_NORMAL;
		}
	}
}
Esempio n. 21
0
INT CADOParameters::Add(const CByteArray &arrBytes)
{
	return Add((arrBytes.GetData()), (INT)arrBytes.GetSize());
}