STDMETHODIMP CRegistrator::Cut(BSTR FirmID, LONG CutType, LONG* ErrorCode) { *ErrorCode = E_SUCCESS; CRegistratorInfo* regInfo = m_RegistratorList.GetInfo(FirmID); if(!regInfo) { *ErrorCode = E_NOT_FOUND; return S_OK; } // открываем документ BYTE nDocumentStatus; if(!GetDocumentStatus(regInfo->hCommPort, &nDocumentStatus, ErrorCode)) return S_OK; // если документ не открыт if((nDocumentStatus & 0x0F) == 0) { if(!OpenDocument(regInfo->hCommPort, 1, '1', szCashierStoredName, ErrorCode)) return CheckPaperStatus(regInfo, ErrorCode); if(!PrintBuffer(FirmID, ErrorCode)) return CheckPaperStatus(regInfo, ErrorCode); } if(CloseDocInternal(regInfo, ErrorCode)) m_ReceiptLines.RemoveAll(); // PassCommand(regInfo->hCommPort, (LPBYTE) "25", NULL, 0, nReceivedMessage, ErrorCode); return CheckPaperStatus(regInfo, ErrorCode); }
STDMETHODIMP CECR::MoveCash(BSTR FirmID, LONG Money, LONG DirectionIn, LONG* ErrorCode) { DWORD dwDocType; DirectionIn ? dwDocType = CashInDocument : dwDocType = CashOutDocument; // открыть документ OpenDocument(FirmID, DEP_NO, ErrorCode, dwDocType); if (*ErrorCode == E_SUCCESS) { PrintBuffer(FirmID, ErrorCode); if (*ErrorCode == E_SUCCESS) { InitCmd(); // команда to_numeric(214, m_Cmd, 3, m_Len); //SETTENDER // пароль to_char(OPERATOR_PASSWD, m_Cmd + m_Len, 4, m_Len); // тип оплаты to_numeric(0, m_Cmd + m_Len, 2, m_Len); // сумма to_smoney(Money, m_Cmd + m_Len, 10, m_Len); m_RspLen = 11; m_ECRList.PassCmd(FirmID, m_Cmd, m_Len, m_Rsp, m_RspLen, ErrorCode); if (*ErrorCode == E_SUCCESS) Cut(FirmID, 1, ErrorCode); } } return S_OK; }
STDMETHODIMP CECR::Cut(BSTR FirmID, LONG CutType, LONG* ErrorCode) { if(!bDocOpened) { OpenDocument(FirmID, DEP_NO, ErrorCode, NonFiskDocument); if (*ErrorCode == E_SUCCESS) PrintBuffer(FirmID, ErrorCode); } InitCmd(); // команда to_numeric(215, m_Cmd, 3, m_Len); //CLOSE // пароль to_char(OPERATOR_PASSWD, m_Cmd + m_Len, 4, m_Len); // обрезать чек to_numeric(CutType, m_Cmd + m_Len, 1, m_Len); m_RspLen = 0; m_ECRList.PassCmd(FirmID, m_Cmd, m_Len, m_Rsp, m_RspLen, ErrorCode); if (*ErrorCode == E_SUCCESS) { ClearPrintBuffer(); bDocOpened = FALSE; } return S_OK; }
int WriteToken (int inSocket, const char *inTokenValue, size_t inTokenLength) { int err = 0; u_int32_t tokenLength = htonl (inTokenLength); if (!inTokenValue) { err = EINVAL; } if (!err) { err = WriteBuffer (inSocket, (char *) &tokenLength, 4); } if (!err) { err = WriteBuffer (inSocket, inTokenValue, inTokenLength); } if (!err) { printf ("Wrote token:\n"); PrintBuffer (inTokenValue, inTokenLength); } else { printError (err, "WriteToken failed"); } return err; }
STDMETHODIMP CRegistrator::DoReturn(BSTR FirmID, BSTR ReturnText, LONG Quantity, LONG Price, LONG DepNo, LONG* ErrorCode) { *ErrorCode = E_SUCCESS; CRegistratorInfo* regInfo = m_RegistratorList.GetInfo(FirmID); if(!regInfo) { *ErrorCode = E_NOT_FOUND; return S_OK; } LONG nAmount = 0; // проверяем состояние документа BYTE nDocumentStatus; if(!GetDocumentStatus(regInfo->hCommPort, &nDocumentStatus, ErrorCode)) return S_OK; // если документ не открыт if((nDocumentStatus & 0x0F) == 0) { // открываем документ if(!OpenDocument(regInfo->hCommPort, DepNo, '3', szCashierStoredName, ErrorCode)) return CheckPaperStatus(regInfo, ErrorCode); if(!PrintBuffer(FirmID, ErrorCode)) return CheckPaperStatus(regInfo, ErrorCode); m_nReturnAmount = 0; } if(RegisterInternal(regInfo->hCommPort, ReturnText, Quantity, Price, DepNo, &nAmount, ErrorCode)) m_nReturnAmount += nAmount; return CheckPaperStatus(regInfo, ErrorCode); }
void test_buffer() { MxStringBuffer buf = {0}; MxStatus status = MxStatusOK; printf(" -- String buffer ----------\n"); printf("Initialising buffer...\n"); if ((status = MxStringBufferInitWithCharacters(&buf, "Original contents", 17)) != MxStatusOK) dieWithStatus("Initialising", status); PrintBuffer(&buf); if ((status = MxStringBufferInsertAtPoint(&buf, "Prefix: ", 0)) != MxStatusOK) dieWithStatus("Insert", status); PrintBuffer(&buf); if ((status = MxStringBufferInsertInt(&buf, 200)) != MxStatusOK) dieWithStatus("Insert int", status); if ((status = MxStringBufferInsert(&buf, " ")) != MxStatusOK) dieWithStatus("Inserting space", status); if ((status = MxStringBufferInsertInt(&buf, -200)) != MxStatusOK) dieWithStatus("Insert int 2", status); if ((status = MxStringBufferInsert(&buf, " ")) != MxStatusOK) dieWithStatus("Inserting space 2", status); if ((status = MxStringBufferInsertInt(&buf, 0)) != MxStatusOK) dieWithStatus("Insert int 3", status); if ((status = MxStringBufferInsert(&buf, " ")) != MxStatusOK) dieWithStatus("Inserting space 3", status); PrintBuffer(&buf); printf("\n\nAs cstr: %s\n", MxStringBufferAsCStr(&buf)); if ((status = MxStringBufferWipe(&buf)) != MxStatusOK) dieWithStatus("Wiping", status); }
void PrintTPM2B_ATTEST( TPM2B_ATTEST *attest ) { TPMS_ATTEST *s_att = (TPMS_ATTEST *)&attest->t.attestationData[0]; printf( "ATTEST_2B:\n" ); printf( "\tsize = 0x%4.4x\n", attest->t.size ); //already little endian printf( "\tattestationData(TPMS_ATTEST):\n" ); printf( "\t\tmagic = 0x%8.8x\n", ntohl(s_att->magic) );//big endian printf( "\t\ttype = 0x%4.4x\n", ntohs(s_att->type) ); printf( "\t\tqualifiedSigner(NAME_2B):\n" ); printf( "\t\t\tsize = 0x%4.4x\n", ntohs(s_att->qualifiedSigner.t.size) ); printf( "\t\t\tname = " ); PrintBuffer( s_att->qualifiedSigner.b.buffer, ntohs(s_att->qualifiedSigner.b.size) ); s_att = (TPMS_ATTEST *)(((BYTE *)s_att) - sizeof(s_att->qualifiedSigner.t) + ntohs(s_att->qualifiedSigner.t.size) + 2); printf( "\t\textraData(DATA_2B):\n" ); printf( "\t\t\tsize = 0x%4.4x\n", ntohs(s_att->extraData.t.size) ); printf( "\t\t\tbuffer = " ); PrintBuffer( s_att->extraData.b.buffer, ntohs(s_att->extraData.b.size) ); s_att = (TPMS_ATTEST *)(((BYTE *)s_att) - sizeof(s_att->extraData.t) + ntohs(s_att->extraData.t.size) + 2); printf( "\t\tclockInfo(TPMS_CLOCK_INFO):\n" ); printf( "\t\t\tclock = 0x%16.16lx\n", s_att->clockInfo.clock ); printf( "\t\t\tresetCount = 0x%8.8x\n", ntohl(s_att->clockInfo.resetCount) ); printf( "\t\t\trestartCount = 0x%8.8x\n", ntohl(s_att->clockInfo.restartCount) ); printf( "\t\t\tsafe = 0x%2.2x\n", s_att->clockInfo.safe ); s_att = (TPMS_ATTEST *)(((BYTE *)s_att) - 7); printf( "\t\tfirmwareVersion = 0x%16.16lx\n", s_att->firmwareVersion ); printf( "\t\tattested(TPMS_QUOTE_INFO):\n" ); printf( "\t\t\tpcrSelect(TPML_PCR_SELECTION):\n" ); printf( "\t\t\t\tcount = 0x%8.8x\n", ntohl(s_att->attested.quote.pcrSelect.count) ); for ( UINT32 i = 0; i < ntohl(s_att->attested.quote.pcrSelect.count); i++ ) { TPMS_PCR_SELECTION *s = &s_att->attested.quote.pcrSelect.pcrSelections[i]; printf( "\t\t\t\tpcrSelections[%d](TPMS_PCR_SELECTION):\n", i ); printf( "\t\t\t\t\thash = 0x%4.4x\n", ntohs(s->hash) ); printf( "\t\t\t\t\tsizeofSelect = 0x%2.2x\n", s->sizeofSelect ); printf( "\t\t\t\t\tpcrSelect = " ); PrintBuffer( s->pcrSelect, s->sizeofSelect ); } s_att = (TPMS_ATTEST *)(((BYTE *)s_att) - sizeof(s_att->attested.quote.pcrSelect) + ntohl(s_att->attested.quote.pcrSelect.count) * sizeof(TPMS_PCR_SELECTION) + 4 ); printf( "\t\t\tpcrDigest(DIGEST_2B):\n" ); printf( "\t\t\t\tsize = 0x%4.4x\n", ntohs(s_att->attested.quote.pcrDigest.t.size) ); printf( "\t\t\t\tbuffer = " ); PrintBuffer( s_att->attested.quote.pcrDigest.b.buffer, ntohs(s_att->attested.quote.pcrDigest.b.size) ); }
// // Function: Rcv_ProcessCommandSDU // // Description: Process Command Message Data // // Arguments: // // Name Type Direction Description // ----------- ----------- ----------- ----------------------------------- // NewDataBlock DataRecord * OUT Block of data ( For return status ) // Buff t_uchar * IN Buffer with data to process // Len int IN Length of buffer // // Return Values: // // Name Explanation // ----------- ------------------------------------------------------------------- // RM_COMMAND For distinct from data buffer // int Rcv_ProcessCommandSDU( DataRecord *NewDataBlock, t_uchar *Buff, int Len ) { //Buff is only data block - without [SOH], [INTEGRITY] and [EOT] int RetStatus = RM_SUCCESS; PrintBuffer( "[CMND][Length][SDU Tag][Operator][Operands]:", Buff, Len ); NewDataBlock->extendedStatus = RM_COMMAND; //Everything is OK return( RetStatus ); //Command SDU }//end Rcv_ProcessCommandSDU
void PrintOpCode(unsigned int operandToNumber, unsigned int format){ if(whichPass == 2){ if(LOCCTR[0] != previousLOCCTR){ //Address got changed, new line PrintBuffer(1); } if(ptrOutputBuffer == 0){ //If empty buffer, mark 'T' and start address sprintf(outputBufferPointer,"T%06X00", LOCCTR[0]); ptrOutputBuffer+=9; } if((ptrOutputBuffer+format) >= BUFSIZE - 2){ //Buffer is about to overflow PrintBuffer(1); sprintf(outputBufferPointer,"T%06X00", LOCCTR[0]); ptrOutputBuffer+=9; } switch(format){ //Print machine code to buffer case 1: sprintf(outputBufferPointer+ptrOutputBuffer,"%02X",operandToNumber); ptrOutputBuffer+=2; break; case 2: sprintf(outputBufferPointer+ptrOutputBuffer,"%04X",operandToNumber); ptrOutputBuffer+=4; break; case 3: sprintf(outputBufferPointer+ptrOutputBuffer,"%06X",operandToNumber); ptrOutputBuffer+=6; break; case 4: sprintf(outputBufferPointer+ptrOutputBuffer,"%08X",operandToNumber); ptrOutputBuffer+=8; break; } previousLOCCTR = LOCCTR[0]+format; if(LOCCTR[0]+format == endAddress){ PrintBuffer(1); } } else { return; } }
int WriteEncryptedToken (int inSocket, const gss_ctx_id_t inContext, const char *inToken, size_t inTokenLength) { int err = 0; OM_uint32 majorStatus; OM_uint32 minorStatus = 0; gss_buffer_desc outputBuffer = { 0, NULL }; if (!inContext) { err = EINVAL; } if (!inToken ) { err = EINVAL; } if (!err) { gss_buffer_desc inputBuffer = { inTokenLength, (char *) inToken }; int encrypt = 1; /* do encryption and integrity protection */ int encrypted = 0; /* did mechanism encrypt/integrity protect? */ majorStatus = gss_wrap (&minorStatus, inContext, encrypt, GSS_C_QOP_DEFAULT, &inputBuffer, &encrypted, &outputBuffer); if (majorStatus != GSS_S_COMPLETE) { printGSSErrors ("gss_wrap", majorStatus, minorStatus); err = minorStatus ? minorStatus : majorStatus; } else if (!encrypted) { fprintf (stderr, "WARNING! Mechanism does not support encryption!"); err = EAUTH; /* You may not want to fail here. */ } } if (!err) { printf ("Unencrypted token:\n"); PrintBuffer (inToken, inTokenLength); err = WriteToken (inSocket, outputBuffer.value, outputBuffer.length); } if (!err) { } else { printError (err, "WriteToken failed"); } if (outputBuffer.value) { gss_release_buffer (&minorStatus, &outputBuffer); } return err; }
void PrintTPMT_SIGNATURE( TPMT_SIGNATURE *sig ) { printf( "TPMT_SIGNATURE:\n" ); printf( "\tsigAlg = 0x%4.4x\n", sig->sigAlg ); printf( "\tsignature(TPMU_SIGNATURE):\n" ); switch ( sig->sigAlg ) { case TPM_ALG_RSASSA: case TPM_ALG_RSAPSS: printf( "\t\tTPMS_SIGNATURE_RSA:\n" ); printf( "\t\t\thash = 0x%4.4x\n", sig->signature.rsassa.hash ); printf( "\t\t\tsig(PUBLIC_KEY_RSA_2B):\n" ); printf( "\t\t\t\tsize = 0x%4.4x\n", sig->signature.rsassa.sig.t.size ); printf( "\t\t\t\tbuffer = " ); PrintSizedBuffer( &sig->signature.rsassa.sig.b ); break; case TPM_ALG_ECDSA: case TPM_ALG_ECDAA: case TPM_ALG_SM2: case TPM_ALG_ECSCHNORR: printf( "\t\tTPMS_SIGNATURE_ECC:\n" ); printf( "\t\t\thash = 0x%4.4x\n", sig->signature.ecdsa.hash); printf( "\t\t\tsignatureR(TPM2B_ECC_PARAMETER):\n" ); printf( "\t\t\t\tsize = 0x%4.4x\n", sig->signature.ecdsa.signatureR.t.size ); printf( "\t\t\t\tbuffer = " ); PrintSizedBuffer( &sig->signature.ecdsa.signatureR.b ); printf( "\t\t\tsignatureS(TPM2B_ECC_PARAMETER):\n" ); printf( "\t\t\t\tsize = 0x%4.4x\n", sig->signature.ecdsa.signatureS.t.size ); printf( "\t\t\t\tbuffer = " ); PrintSizedBuffer( &sig->signature.ecdsa.signatureS.b ); break; case TPM_ALG_HMAC: printf( "\t\tTPMS_HA:\n" ); printf( "\t\t\thashAlg = 0x%4.4x\n", sig->signature.hmac.hashAlg); printf( "\t\t\tdigest = " ); UINT16 size = 0; switch ( sig->signature.hmac.hashAlg ) { case TPM_ALG_SHA1: size = SHA1_DIGEST_SIZE; break; case TPM_ALG_SHA256: size = SHA256_DIGEST_SIZE; break; case TPM_ALG_SHA384: size = SHA384_DIGEST_SIZE; break; case TPM_ALG_SHA512: size = SHA512_DIGEST_SIZE; break; case TPM_ALG_SM3_256: size = SM3_256_DIGEST_SIZE; break; } PrintBuffer( (BYTE *)&sig->signature.hmac.digest, size ); break; } }
STDMETHODIMP CRegistrator::MoveCash(BSTR FirmID, LONG Money, LONG DirectionIn, LONG* ErrorCode) { *ErrorCode = E_SUCCESS; CRegistratorInfo* regInfo = m_RegistratorList.GetInfo(FirmID); if(!regInfo) { *ErrorCode = E_NOT_FOUND; return S_OK; } BYTE nSentMessage[MESSAGE_SIZE], nReceivedMessage[MESSAGE_SIZE]; DWORD dwMessageLen = 0; // проверяем состояние документа BYTE nDocumentStatus; if(!GetDocumentStatus(regInfo->hCommPort, &nDocumentStatus, ErrorCode)) return S_OK; // если документ не открыт if((nDocumentStatus & 0x0F) == 0) { // открываем документ if(!OpenDocument(regInfo->hCommPort, 1, (DirectionIn == 1) ? '4' : '5', szCashierStoredName, ErrorCode)) return CheckPaperStatus(regInfo, ErrorCode); if(!PrintBuffer(FirmID, ErrorCode)) return CheckPaperStatus(regInfo, ErrorCode); } // формируем текст команды memset(nSentMessage, 0, MESSAGE_SIZE); // название или тип купюры nSentMessage[dwMessageLen++] = FS; // сумма CHAR lpAmount[MESSAGE_SIZE]; memset(lpAmount, 0, MESSAGE_SIZE); sprintf(lpAmount, "%.2f", Money / 100.0); memcpy(nSentMessage + dwMessageLen, lpAmount, strlen(lpAmount)); dwMessageLen += (DWORD)strlen(lpAmount); if(PassCommand(regInfo->hCommPort, (LPBYTE) "36", nSentMessage, dwMessageLen, nReceivedMessage, ErrorCode)) CloseDocInternal(regInfo, ErrorCode); return CheckPaperStatus(regInfo, ErrorCode); }
// // Function: Resp_ProcessSyntaxSDU // // Description: Process Responce Message Data with SYNTAX status // // Arguments: // // Name Type Direction Description // ----------- ----------- ----------- ----------------------------------- // pNode QueueNodeDef * IN Node in QUEUE ( For check for what command this responce ) // Buff t_uchar * IN Buffer with data to process // Len int IN Length of buffer // MessageBuf char * OUT Buffer to return formatted string // // Return Values: // // Name Explanation // ----------- --------------------------------------------------------------- // RetStatus Error code // static int Resp_ProcessSyntaxSDU( QueueNodeDef *pNode, t_uchar *Buff, int Len, char *MessageBuf ) { int RetStatus = RM_SUCCESS; SyntaxErrorCode SyntaxType = Buff[EXT_RESULT_CODE]; #ifdef RM_HEAP char *TempBuf = (char *)Mem_Allocate( MAX_LENGTH_STR ); #else char TempBuf[MAX_LENGTH_STR]; #endif QueueNodeDef *pHead = QueueGetHead(SEND_QUEUE); VRM_StateDef *Statistics = (VRM_StateDef *)(pHead->Message.DataBuffer); if ( pNode->Message.DataBuffer != NULL ) PrintBuffer( "[E] Syntax error in command:", pNode->Message.DataBuffer, pNode->Message.DataLength ); RetStatus = Resp_CheckCommandType( pNode, Buff, Len, MessageBuf ); switch( SyntaxType ) { case INVALID: //ASCII 'b' //Invalid option in command Statistics->SYNTAX_CODE.INVALID++; Statistics->LAST_UPDATED_FIELD = POS_INVALID; sprintf( TempBuf, "%s Invalid option in command\n", MessageBuf ); strcpy( MessageBuf, TempBuf );//for DOS compatability break; case TOO_LONG: //ASCII 'c' //Data too long Statistics->SYNTAX_CODE.TOO_LONG++; Statistics->LAST_UPDATED_FIELD = POS_TOO_LONG; sprintf( TempBuf, "%s Data too long\n", MessageBuf ); strcpy( MessageBuf, TempBuf );//for DOS compatability break; default: Statistics->SYNTAX_CODE.UNDEFINED++; Statistics->LAST_UPDATED_FIELD = POS_UNDEFINED_SYNTAX_CODE; sprintf( TempBuf, "%s UNKNOWN = %04X HEX\n", MessageBuf, SyntaxType ); strcpy( MessageBuf, TempBuf );//for DOS compatability break; }//end switch #ifdef RM_HEAP Mem__Free( TempBuf ); #endif return( RetStatus ); //Responce SDU }//end Resp_ProcessSyntaxSDU
STDMETHODIMP CRegistrator::SuspendReceipt(BSTR bstrMessage, CHAR cSeparator, LONG* ErrorCode) { *ErrorCode = E_SUCCESS; CRegistratorInfo* regInfo = m_RegistratorList.GetDefault(); CHAR szSpaces[51], szStars[51]; // печатает корешок отложенного чека ZeroMemory(szSpaces, 51); ZeroMemory(szStars, 51); // заполняем строки пробелами и разделителями memset(szSpaces, 32, STRING_LEN); memset(szStars, 32, STRING_LEN); // открываем документ BYTE nDocumentStatus; if(!GetDocumentStatus(regInfo->hCommPort, &nDocumentStatus, ErrorCode)) return S_OK; // если документ не открыт if((nDocumentStatus & 0x0F) == 0) { if(!OpenDocument(regInfo->hCommPort, 1, '1', szCashierStoredName, ErrorCode)) return CheckPaperStatus(regInfo, ErrorCode); if(!PrintBuffer(regInfo->ID, ErrorCode)) return CheckPaperStatus(regInfo, ErrorCode); } // печатаем текстовое сообщение PrintString(regInfo->ID, BSTR(CComBSTR(szSpaces)), 0, 1, ErrorCode); PrintString(regInfo->ID, bstrMessage, 0, 2, ErrorCode); PrintString(regInfo->ID, BSTR(CComBSTR(szSpaces)), 0, 1, ErrorCode); PrintString(regInfo->ID, BSTR(CComBSTR("Предъявите этот")), 0, 2, ErrorCode); PrintString(regInfo->ID, BSTR(CComBSTR("листок кассиру для")), 0, 2, ErrorCode); PrintString(regInfo->ID, BSTR(CComBSTR("продолжения расчета")), 0, 2, ErrorCode); PrintString(regInfo->ID, BSTR(CComBSTR(szSpaces)), 0, 1, ErrorCode); PrintString(regInfo->ID, BSTR(CComBSTR(szStars)), 0, 1, ErrorCode); if(CloseDocInternal(regInfo, ErrorCode)) m_ReceiptLines.RemoveAll(); return CheckPaperStatus(regInfo, ErrorCode); }
void PackageAllTxBuffer(const SearchDefine *sd) { printf("\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); printf("\n>Packaging all Tx buffer..."); if (sd && sd->Meters) { Meter *mt = sd->Meters; do { PackageTxBuffer(mt); printf("\n>Packaged: MeterID=%s, NodeAddress=0x%02X, TxBuffer: 0x", mt->ID, mt->NodeAddress); PrintBuffer(mt->PackageBuffer.TxBuffer, mt->PackageBuffer.TxLength); } while ((mt = mt->Next)); } printf("\n>DONE"); printf("\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); }
STDMETHODIMP CECR::SuspendReceipt(BSTR bstrMessage, CHAR cSeparator, LONG* ErrorCode) { CHAR szSpaces[51], szStars[51]; CECRConnection *pConnection = m_ECRList.GetDefault(); if (pConnection == NULL) { *ErrorCode = E_NOT_FOUND; return S_OK; } // печатает корешок отложенного чека ZeroMemory(szSpaces, 51); ZeroMemory(szStars, 51); // заполняем строки пробелами и разделителями memset(szSpaces, 32, m_ECRList.GetStringLen()); memset(szStars, 32, m_ECRList.GetStringLen()); // печатаем текстовое сообщение PrintString(pConnection->m_ID, BSTR(CComBSTR(szSpaces)), 0, 1, ErrorCode); PrintString(pConnection->m_ID, bstrMessage, 0, 2, ErrorCode); PrintString(pConnection->m_ID, BSTR(CComBSTR(szSpaces)), 0, 1, ErrorCode); PrintString(pConnection->m_ID, BSTR(CComBSTR("Предъявите этот")), 0, 2, ErrorCode); PrintString(pConnection->m_ID, BSTR(CComBSTR("листок кассиру для")), 0, 2, ErrorCode); PrintString(pConnection->m_ID, BSTR(CComBSTR("продолжения расчета")), 0, 2, ErrorCode); PrintString(pConnection->m_ID, BSTR(CComBSTR(szSpaces)), 0, 1, ErrorCode); PrintString(pConnection->m_ID, BSTR(CComBSTR(szStars)), 0, 1, ErrorCode); // открыть документ OpenDocument(pConnection->m_ID, DEP_NO, ErrorCode, NonFiskDocument); if (*ErrorCode == E_SUCCESS) { PrintBuffer(pConnection->m_ID, ErrorCode); if (*ErrorCode == E_SUCCESS) { Cut(pConnection->m_ID, 1, ErrorCode); ClearPrintBuffer(); } } return S_OK; }
STDMETHODIMP CECR::DoReturn(BSTR FirmID, BSTR ReturnText, LONG Quantity, LONG Price, LONG DepNo, LONG* ErrorCode) { CW2A szGoodName(ReturnText); m_ECRList.Win1251ToCP866(szGoodName); // открыть документ OpenDocument(FirmID, DEP_NO, ErrorCode, ReturnDocument); if (*ErrorCode == E_SUCCESS) { PrintBuffer(FirmID, ErrorCode); if (*ErrorCode == E_SUCCESS) { InitCmd(); // команда to_numeric(209, m_Cmd, 3, m_Len); //SETITEM // пароль to_char(OPERATOR_PASSWD, m_Cmd + m_Len, 4, m_Len); // код отдела to_numeric(DepNo, m_Cmd + m_Len, 3, m_Len); // штрих-код товара to_bchar("", m_Cmd + m_Len, 0, m_Len); // внутренний учетный код товара to_bchar("", m_Cmd + m_Len, 0, m_Len); // название товара to_bchar(szGoodName, m_Cmd + m_Len, strlen(szGoodName), m_Len); // цена товара to_money(Price, m_Cmd + m_Len, 10, m_Len); // количество товара to_numeric(Quantity, m_Cmd + m_Len, 8, m_Len); // стоимость тары to_money(0, m_Cmd + m_Len, 10, m_Len); // размерность to_bchar("", m_Cmd + m_Len, 0, m_Len); m_RspLen = 5; m_ECRList.PassCmd(FirmID, m_Cmd, m_Len, m_Rsp, m_RspLen, ErrorCode); } } return S_OK; }
int ReadToken (int inSocket, char **outTokenValue, size_t *outTokenLength) { int err = 0; char *token = NULL; u_int32_t tokenLength = 0; if (!outTokenValue ) { err = EINVAL; } if (!outTokenLength) { err = EINVAL; } if (!err) { err = ReadBuffer (inSocket, 4, (char *) &tokenLength); } if (!err) { tokenLength = ntohl (tokenLength); token = malloc (tokenLength); memset (token, 0, tokenLength); err = ReadBuffer (inSocket, tokenLength, token); } if (!err) { printf ("Read token:\n"); PrintBuffer (token, tokenLength); *outTokenLength = tokenLength; *outTokenValue = token; token = NULL; /* only free on error */ } else { printError (err, "ReadToken failed"); } if (token) { free (token); } return err; }
int main(int argc, char* argv[]) { int test_font = 0; // set to 1 to print on text console if (argc!=2) { Help(argv[0]); } if (test_font) { InitBuffer(80, 30); } else { InitFrameBuffer(320, 200); } PrintChars(argv[1], test_font); if (test_font) { PrintBuffer(); } return 0; }
//***************************************************************************** // // Run the AES encryption/decryption example. // //***************************************************************************** int main(void) { unsigned char pucBlockBuf[16]; const unsigned *puKey; unsigned char pucTempIV[16]; // // Set the clocking to run directly from the crystal. // ROM_SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ); // // Initialize the UART interface. // ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA); GPIOPinConfigure(GPIO_PA0_U0RX); GPIOPinConfigure(GPIO_PA1_U0TX); ROM_GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1); UARTStdioInit(0); UARTprintf("\033[2JAES encryption/decryption using a pre-expanded key\n"); // // Print the plain text title // UARTprintf("Plain Text:"); PrintBuffer((unsigned char *)g_pcPlainText, sizeof(g_pcPlainText)); // // Get the expanded key to use for encryption // puKey = AESExpandedEncryptKeyData(); // // Generate the initialization vector needed for CBC mode. A temporary // copy is made that will be used with the crypt function because the crypt // function will modify the IV that is passed. // AESGenerateIV(g_pucIV, 1); memcpy(pucTempIV, g_pucIV, 16); // // Encrypt the plaintext message using CBC mode // aes_crypt_cbc(puKey, AES_ENCRYPT, 16, pucTempIV, (unsigned char *)g_pcPlainText, pucBlockBuf); // // Print the encrypted block to the display. Note that it will appear as // nonsense data. // UARTprintf("Encrypted:"); PrintBuffer(pucBlockBuf, sizeof(pucBlockBuf)); // // Get the expanded key to use for decryption // puKey = AESExpandedDecryptKeyData(); // // Decrypt the message using CBC mode // memcpy(pucTempIV, g_pucIV, 16); aes_crypt_cbc(puKey, AES_DECRYPT, 16, pucTempIV, pucBlockBuf, pucBlockBuf); // // Print the decrypted block to the display. It should be the same text // as the original message. // UARTprintf("Decrypted:"); PrintBuffer(pucBlockBuf, sizeof(pucBlockBuf)); // // Finished. // while(1) { } }
//Edits the current file void MenuEdit(list *FileBuffer, WINDOW *my_menu_win){ //Printing the existing file in the buffer to the window PrintBuffer(FileBuffer, my_menu_win); int x = 0, y = 2, c, choice = 0; int ymax = 2; //Creating temporary buffers char str[100][MAXCHAR], string[MAXCHAR]; int i = 0, j = 0; char ch; int ln = 2; node *p; //Copying the contents of the buffer into the 2D temporary buffer p = FileBuffer->head; while(p){ strcpy(&str[ln][0], p->string); p = p->next; ln++; } //If the buffer was non-empty, the contents of the temp buffer will be rewritten FreeBuffer(FileBuffer); InitialiseBuffer(FileBuffer); ymax = ln; y = ymax; x = 0; //Taking input from the user while((c = wgetch(my_menu_win)) != KEY_F(6) ||(c = wgetch(my_menu_win)) != KEY_F(3) ){ switch(c){ case KEY_UP: if (y > 2){ y--; wmove(my_menu_win, y, x); ln--; } break; case KEY_DOWN: y++; if (y > ymax) ymax = y; wmove(my_menu_win, y, x); ln++; break; case KEY_LEFT: if (x > 0){ x--; wmove(my_menu_win, y, x); i--; } break; case KEY_RIGHT: if (x < MAXCHAR){ x++; wmove(my_menu_win, y, x); i++; } break; case KEY_BACKSPACE: case 8: if (x > 0){ x--; wmove(my_menu_win, y, x); i--; } mvwprintw(my_menu_win, y, x, " "); str[y][x] = ' '; break; case 10: case 13: str[y][x] = '\n'; y++; ln++; if (y > ymax) ymax = y; x = 0; wmove(my_menu_win, y, x); break; //Escape case 27: choice = 1; break; default: str[y][x] = c; //Printing the character read to the screen mvwprintw(my_menu_win, y, x, "%c", c); x++; wmove(my_menu_win, y, x); break; } //If the user has pressed escape if (choice) break; } //Copying from temp buffer to permanent buffer for (i = 2; i < ymax ; i++){ //for each character that was read for (j = 0; str[i][j] != '\n'; j++){ string[j] = str[i][j]; } string[j] = '\0'; //Reinserting the strings from the temp buffer to the file buffer AppendtoBuffer(FileBuffer, string); } }
char* TANSIParser::ParseANSIBuffer(char* pszBuffer, char* pszBufferEnd) { if(InPrintMode) { return PrintBuffer(pszBuffer, pszBufferEnd); } unsigned char tmpc = *(unsigned char *)pszBuffer; if(tmpc == 27) { return ParseEscape(pszBuffer, pszBufferEnd); } // if((fast_write && tmpc < 32) || // !print_ctrl && (tmpc < 32 || (EightBit_Ansi && // (tmpc > 128 && tmpc < 128 + ' ')))) { // We shouldn't print ctrl characters when fast write is enabled // and ctrl chars are disabled (Paul Brannan 9/1/98) if(tmpc < 32) { // From the Linux kernel (Paul Brannan 12/5/98): /* A bitmap for codes <32. A bit of 1 indicates that the code * corresponding to that bit number invokes some special action * (such as cursor movement) and should not be displayed as a * glyph unless the disp_ctrl mode is explicitly enabled. */ const long CTRL_ACTION = 0x0d00ff81; const long CTRL_ALWAYS = 0x0800f501; if(!(((print_ctrl?CTRL_ALWAYS:CTRL_ACTION)>>tmpc)&1)) { Console.WriteString((char *)&tmpc, 1); pszBuffer++; return pszBuffer; } switch (tmpc) { case 0: pszBuffer++; break; // I.Ioannou 5/30/98 case 7: Console.Beep(); pszBuffer++; break; // destructive backspace case 8: // Added option for destructive backspace (Paul Brannan 5/13/98) // Changed to ConWriteCtrlString so that the cursor position can be // updated (Paul Brannan 5/25/98) if(ini.get_dstrbksp()) { Console.WriteCtrlChar('\b'); Console.WriteString(" ", 1); Console.WriteCtrlChar('\b'); } else Console.WriteCtrlChar('\b'); pszBuffer++; break; // horizontal tab case 9: { pszBuffer++; int x = Console.GetCursorX(); if(x != -1) Console.SetCursorPosition(tab_stops[x], Console.GetCursorY()); } break; // Line Feed Char case 10: // Test for local echo (Paul Brannan 8/25/98) if(Network.get_local_echo() || newline_mode) // && Console.WriteCtrlChar('\x0d'); Console.WriteCtrlChar('\x0a'); pszBuffer++; break; // form feed case 12: pszBuffer++; Console.ClearScreen(); Console.SetRawCursorPosition(Console.GetCursorX(), 1); // changed fm 1 break; case 13: Console.WriteCtrlChar('\x0d'); pszBuffer++; break; case 14: // shift out of alternate chararcter set pszBuffer++; Charmap.setmap(map_G1); // Paul Brannan 6/25/98 current_map = 1; break; case 15: // shift in pszBuffer++; Charmap.setmap(map_G0); // Paul Brannan 6/25/98 current_map = 0; break; // Paul Brannan 9/1/98 - Is this okay? default: pszBuffer++; } return pszBuffer; } // added by I.Ioannou 06 April, 1997 // In 8 bit systems the server may send 0x9b instead of ESC[ // Well, this will produce troubles in Greek 737 Code page // which uses 0x9b as the small "delta" - and I thing that there // is another European country with the same problem. // If we have to stay 8-bit clean we may have to // give the ability of ROM characters (ESC[11m), // for striped 8'th bit (ESC[12m) as SCO does, // or a parameter at compile (or run ?) time. // We now check for a flag in the ini file (Paul Brannan 5/13/98) // We also handle any 8-bit ESC sequence (Paul Brannan 6/28/98) if(ini.get_eightbit_ansi() && (tmpc > 128 && tmpc < 128 + ' ')) { // There's a chance the sequence might not parse. If this happens // then pszBuffer will be one character too far back, since // ParseEscape is expecting two characters, not one. // In that case we must handle it. char *pszCurrent = pszBuffer; pszBuffer = ParseEscape(pszBuffer, pszBufferEnd); if(pszBuffer < pszCurrent) pszBuffer = pszCurrent; } char* pszCurrent = pszBuffer + 1; // I.Ioannou 04 Sep 1997 FIXME with ESC[11m must show chars < 32 // Fixed (Paul Brannan 6/28/98) while ((pszCurrent < pszBufferEnd) && (!iscntrl(*pszCurrent))) { // I.Ioannou 04 Sep 1997 strip on high bit if ( (inGraphMode) && (*pszCurrent > (char)32) ) *pszCurrent |= 0x80 ; pszCurrent++; } // Note that this may break dumpfiles slightly. // If 'B' is set to anything other than ASCII, this will cause problems // (Paul Brannan 6/28/98) if(current_map != 'B' && Charmap.enabled) Charmap.translate_buffer(pszBuffer, pszCurrent); last_char = *(pszCurrent-1); // TITUS++: Remember last char if(fast_write) { pszBuffer += Console.WriteStringFast(pszBuffer, pszCurrent - pszBuffer); } else { pszBuffer += Console.WriteString(pszBuffer, pszCurrent - pszBuffer); } return pszBuffer; }
// // Function: Resp_DisplayFormatted // // Description: Process Responce Message Data // // Arguments: // // Name Type Direction Description // ----------- ----------- ----------- ----------------------------------- // pNode QueueNodeDef * IN Node in QUEUE ( For check for what command this responce ) // Buff t_uchar * IN Buffer with data to process // Len int IN Length of buffer // // Return Values: // // Name Explanation // ----------- --------------------------------------------------------------- // RetStatus Error code // int Resp_DisplayFormatted( QueueNodeDef *pNode, t_uchar *Buff, int Len ) { int RetStatus = RM_SUCCESS; time_t ltime = 0; #ifdef RM_HEAP char *TempBuf = (char *)Mem_Allocate( MAX_LENGTH_STR ); char *MessageBuf = (char *)Mem_Allocate( MAX_LENGTH_STR ); #else char TempBuf[MAX_LENGTH_STR]; char TimeBuf[MAX_LENGTH_STR]; char MessageBuf[MAX_LENGTH_STR]; #endif QueueNodeDef *pHead = QueueGetHead(SEND_QUEUE); VRM_StateDef *Statistics = (VRM_StateDef *)(pHead->Message.DataBuffer); RetStatus = Buff[RESULT_CODE]; MessageBuf[0] = '\0'; sprintf( MessageBuf, "Length = %04X HEX, SDU Tag = %04X HEX, Result Code =", Len - RESPONCE_DATA_OVERHEAD, pNode->InternalID ); //Get current time string _strtime( TimeBuf ); switch( RetStatus ) { case SUCCESS: //SUCCESS == '1' Statistics->RESP.SUCCESS++; Statistics->LAST_UPDATED_FIELD = POS_SUCCESS; sprintf( TempBuf, "%s SUCCESS\n Details:", MessageBuf ); strcpy( MessageBuf, TempBuf );//for DOS compatability sprintf( TempBuf, "[S] Response: SUCCESS, SENT: %ld, RESP: %ld, DIFF: %ld, TIME: %s", pNode->TimeStamp, time( <ime ), time( <ime ) - pNode->TimeStamp, TimeBuf ); Resp_ProcessSuccessSDU( pNode, Buff, Len, MessageBuf ); RetStatus = RM_SUCCESS; break; case XFAIL: //XFAIL == '2' Statistics->RESP.XFAIL++; Statistics->LAST_UPDATED_FIELD = POS_XFAIL; sprintf( TempBuf, "%s XFAIL \n Details:", MessageBuf ); strcpy( MessageBuf, TempBuf );//for DOS compatability sprintf( TempBuf, "[E] Response: XFAIL, SENT: %ld, RESP: %ld, TIME: %s", pNode->TimeStamp, time( <ime ), TimeBuf ); Resp_ProcessXfailSDU( pNode, Buff, Len, MessageBuf ); RetStatus = RM_ERROR_GENERAL; break; case SYNTAX: //SYNTAX == '3' Statistics->RESP.SYNTAX++; Statistics->LAST_UPDATED_FIELD = POS_SYNTAX; sprintf( TempBuf, "%s SYNTAX \n Details:", MessageBuf ); strcpy( MessageBuf, TempBuf );//for DOS compatability sprintf( TempBuf, "[E] Response: SYNTAX ERROR, SENT: %ld, RESP: %ld, TIME: %s", pNode->TimeStamp, time( <ime ), TimeBuf ); Resp_ProcessSyntaxSDU( pNode, Buff, Len, MessageBuf ); RetStatus = RM_ERROR_GENERAL; break; default: Statistics->RESP.UNDEFINED++; Statistics->LAST_UPDATED_FIELD = POS_UNDEFINED_RESP; sprintf( TempBuf, "%s UNKNOWN = %04X HEX\n", MessageBuf, RetStatus ); strcpy( MessageBuf, TempBuf );//for DOS compatability strcpy( TempBuf, "[E] Response: UNKNOWN" ); break; }//end switch //Print all messages formatted in MessageBuf PrintLogMessage( TempBuf, "", 0 ); PrintBuffer( "[RESP][Length][SDU Tag][Result Code][Responce Information]", Buff, Len ); PrintLogMessage( MessageBuf, "", 0 ); #ifdef RM_HEAP Mem__Free( MessageBuf ); Mem__Free( TempBuf ); #endif return( RetStatus ); //Responce SDU }//end Resp_DisplayFormatted
bool GetHWID(DWORD * hwid) { VU("GetHWID"); CHwInfo smbios2; DWORD hwid_l[3] = {0, 0, 0}; //old method, w2k+ only... // //SMBiosData smbios; // //if (smbios.FetchSMBiosData()) //{ // DWORD dwSize = 0; // BYTE * table = NULL; // // table = smbios.GetTable(1, dwSize); // info("returned size %d table %08X", dwSize, table); // if (dwSize > 4) // { // hwid_l[0] = hwid_l[0] ^ GetCRC32(table, dwSize); // hwid_l[1] = hwid_l[1] ^ GetCRC32(table+2, dwSize-2); // hwid_l[2] = hwid_l[2] ^ GetCRC32(table+4, dwSize-4); // info("--- table 1 -----"); // PrintBuffer(table, dwSize, 16); // } // table = smbios.GetTable(2, dwSize); // info("returned size %d table %08X", dwSize, table); // if (dwSize > 4) // { // hwid_l[0] = hwid_l[0] ^ GetCRC32(table, dwSize); // hwid_l[1] = hwid_l[1] ^ GetCRC32(table+2, dwSize-2); // hwid_l[2] = hwid_l[2] ^ GetCRC32(table+4, dwSize-4); // info("--- table 2 -----"); // PrintBuffer(table, dwSize, 16); // } // table = smbios.GetTable(4, dwSize); // info("returned size %d table %08X", dwSize, table); // if (dwSize > 4) // { // hwid_l[0] = hwid_l[0] ^ GetCRC32(table, dwSize); // hwid_l[1] = hwid_l[1] ^ GetCRC32(table+2, dwSize-2); // hwid_l[2] = hwid_l[2] ^ GetCRC32(table+4, dwSize-4); // info("--- table 4 -----"); // PrintBuffer(table, dwSize, 16); // } // table = smbios.GetTable(11, dwSize); // info("returned size %d table %08X", dwSize, table); // if (dwSize > 4) // { // hwid_l[0] = hwid_l[0] ^ GetCRC32(table, dwSize); // hwid_l[1] = hwid_l[1] ^ GetCRC32(table+2, dwSize-2); // hwid_l[2] = hwid_l[2] ^ GetCRC32(table+4, dwSize-4); // info("--- table 11 ----"); // PrintBuffer(table, dwSize, 16); // } // info("main hwid done, result: %08X %08X %08X", hwid_l[0], hwid_l[1], hwid_l[2]); //} //hwid_l[0] = 0; //hwid_l[1] = 0; //hwid_l[2] = 0; if (smbios2.GetSMBiosData()) { DWORD dwSize = 0; BYTE * table = NULL; table = smbios2.GetSMBiosStructure(1, dwSize); info("returned size %d table %08X", dwSize, table); if (dwSize > 4 && table != NULL) { hwid_l[0] = hwid_l[0] ^ GetCRC32(table, dwSize); hwid_l[1] = hwid_l[1] ^ GetCRC32(table+2, dwSize-2); hwid_l[2] = hwid_l[2] ^ GetCRC32(table+4, dwSize-4); info("--- table 1 -----"); PrintBuffer(table, dwSize, 16); } table = smbios2.GetSMBiosStructure(2, dwSize); info("returned size %d table %08X", dwSize, table); if (dwSize > 4 && table != NULL) { hwid_l[0] = hwid_l[0] ^ GetCRC32(table, dwSize); hwid_l[1] = hwid_l[1] ^ GetCRC32(table+2, dwSize-2); hwid_l[2] = hwid_l[2] ^ GetCRC32(table+4, dwSize-4); info("--- table 2 -----"); PrintBuffer(table, dwSize, 16); } table = smbios2.GetSMBiosStructure(4, dwSize); info("returned size %d table %08X", dwSize, table); if (dwSize > 4 && table != NULL) { hwid_l[0] = hwid_l[0] ^ GetCRC32(table, dwSize); hwid_l[1] = hwid_l[1] ^ GetCRC32(table+2, dwSize-2); hwid_l[2] = hwid_l[2] ^ GetCRC32(table+4, dwSize-4); info("--- table 4 -----"); PrintBuffer(table, dwSize, 16); } table = smbios2.GetSMBiosStructure(11, dwSize); info("returned size %d table %08X", dwSize, table); if (dwSize > 4 && table != NULL) { hwid_l[0] = hwid_l[0] ^ GetCRC32(table, dwSize); hwid_l[1] = hwid_l[1] ^ GetCRC32(table+2, dwSize-2); hwid_l[2] = hwid_l[2] ^ GetCRC32(table+4, dwSize-4); info("--- table 11 ----"); PrintBuffer(table, dwSize, 16); } info("main hwid done, result: %08X %08X %08X", hwid_l[0], hwid_l[1], hwid_l[2]); } else { hwid_l[0] = GetHWIDchunk(1); hwid_l[1] = GetHWIDchunk(2); hwid_l[2] = GetHWIDchunk(3); info("secondary hwid done, result: %08X %08X %08X", hwid_l[0], hwid_l[1], hwid_l[2]); } g_HWID_Bak[0] = GetTickCount(); g_HWID_Bak[1] = hwid_l[0] ^ g_HWID_Bak[0]; g_HWID_Bak[2] = hwid_l[1] ^ g_HWID_Bak[0]; g_HWID_Bak[3] = hwid_l[2] ^ g_HWID_Bak[0]; hwid[0] = 0; hwid[1] = hwid_l[0]; hwid[2] = hwid_l[1]; hwid[3] = hwid_l[2]; return true; VE(); }
int ReadEncryptedToken (int inSocket, const gss_ctx_id_t inContext, char **outTokenValue, size_t *outTokenLength) { int err = 0; char *token = NULL; size_t tokenLength = 0; OM_uint32 majorStatus; OM_uint32 minorStatus = 0; gss_buffer_desc outputBuffer = { 0 , NULL}; char *unencryptedToken = NULL; if (!inContext ) { err = EINVAL; } if (!outTokenValue ) { err = EINVAL; } if (!outTokenLength) { err = EINVAL; } if (!err) { err = ReadToken (inSocket, &token, &tokenLength); } if (!err) { gss_buffer_desc inputBuffer = { tokenLength, token}; int encrypted = 0; /* did mechanism encrypt/integrity protect? */ majorStatus = gss_unwrap (&minorStatus, inContext, &inputBuffer, &outputBuffer, &encrypted, NULL /* qop_state */); if (majorStatus != GSS_S_COMPLETE) { printGSSErrors ("gss_unwrap", majorStatus, minorStatus); err = minorStatus ? minorStatus : majorStatus; } else if (!encrypted) { fprintf (stderr, "WARNING! Mechanism not using encryption!"); err = EAUTH; /* You may not want to fail here. */ } } if (!err) { unencryptedToken = malloc (outputBuffer.length); if (unencryptedToken == NULL) { err = ENOMEM; } } if (!err) { memcpy (unencryptedToken, outputBuffer.value, outputBuffer.length); printf ("Unencrypted token:\n"); PrintBuffer (unencryptedToken, outputBuffer.length); *outTokenLength = outputBuffer.length; *outTokenValue = unencryptedToken; unencryptedToken = NULL; /* only free on error */ } else { printError (err, "ReadToken failed"); } if (token ) { free (token); } if (outputBuffer.value) { gss_release_buffer (&minorStatus, &outputBuffer); } if (unencryptedToken ) { free (unencryptedToken); } return err; }
//***************************************************************************** // // Run the AES encryption/decryption example. // //***************************************************************************** int main(void) { unsigned char pucBlockBuf[16]; // // Set the clocking to run directly from the crystal. // ROM_SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ); // // Initialize the UART interface. // ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA); GPIOPinConfigure(GPIO_PA0_U0RX); GPIOPinConfigure(GPIO_PA1_U0TX); ROM_GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1); UARTStdioInit(0); UARTprintf("\033[2JAES encryption/decryption using a normal key\n"); // // Print the plain text title // UARTprintf("Plain Text:"); PrintBuffer((unsigned char *)g_pcPlainText, sizeof(g_pcPlainText)); // // Set the key to use for encryption // aes_setkey_enc(&g_sAESCtx, g_pucKey, 128); // // Encrypt the plaintext message using ECB mode // aes_crypt_ecb(&g_sAESCtx, AES_ENCRYPT, (unsigned char *)g_pcPlainText, pucBlockBuf); // // Print the encrypted block to the display. Note that it will // appear as nonsense data. // UARTprintf("Encrypted:"); PrintBuffer(pucBlockBuf, sizeof(pucBlockBuf)); // // Set the key to use for decryption // aes_setkey_dec(&g_sAESCtx, g_pucKey, 128); // // Decrypt the message // aes_crypt_ecb(&g_sAESCtx, AES_DECRYPT, pucBlockBuf, pucBlockBuf); // // Print the decrypted block to the display. It should be the same text // as the original message. // UARTprintf("Decrypted:"); PrintBuffer(pucBlockBuf, sizeof(pucBlockBuf)); // // Finished. // while(1) { } }
DWORD GetHWIDchunk(int chunk) { VU("GetHWIDchunk"); int res = -1; switch (chunk) { case 1: { //CPUID char cpudata[0x50]; memset(cpudata, 0, 0x50); __asm { pushad lea edi, cpudata add edi, 0x4C mov esi, 0x80000004 mov eax, 0x80000000 cpuid cmp eax, esi jl errora loopa: mov eax, esi cpuid mov [edi], edx mov [edi-4], ecx mov [edi-8], ebx mov [edi-12], eax sub edi, 0x10 dec esi cmp esi, 0x7FFFFFFF jne loopa mov res, 1 jmp exita errora: mov res, 0 exita: popad } PrintBuffer((BYTE *)cpudata, 0x50, 16); info("GetHWIDchunk(%d) %d res", chunk, res); if (res = 1) return GetCRC32(cpudata, 0x50); info("GetHWIDchunk() Fail, returning default for request %d.", chunk); return 0xBAADD00D; } break; case 2: { //windows installation date char windir[256]; memset(windir, 0, 256); GetWindowsDirectoryA(windir, 255); info("GetHWIDchunk() Windows folder = %s", windir); struct _stat32 f_stats; if (_stat32(windir, &f_stats) == 0) { char timebuf[256]; _ctime32_s(timebuf, 26, &f_stats.st_ctime); info("GetHWIDchunk() Windows folder (%s) creation date = %s", windir, timebuf); if (strstr(timebuf, V(" 201")) == NULL && strstr(timebuf, V(" 200")) == NULL) return 0xBAADD00D; return f_stats.st_ctime ^ GetCRC32(windir, 20); } info("GetHWIDchunk() Fail, returning default for request %d.", chunk); return 0xBAADD00D; } break; case 3: { char compname[256]; memset(compname, 0, 256); DWORD maxlen = 256; GetComputerNameA(compname, &maxlen); return GetCRC32(compname, sizeof(compname)); } break; default: return 0; } return 0; VE(); }
int quote(TPM_HANDLE akHandle, PCR_LIST pcrList, TPMI_ALG_HASH algorithmId) { UINT32 rval; TPM2B_DATA qualifyingData; UINT8 qualDataString[] = { 0x00, 0xff, 0x55, 0xaa }; TPMT_SIG_SCHEME inScheme; TPML_PCR_SELECTION pcrSelection; TPMS_AUTH_RESPONSE sessionDataOut; TSS2_SYS_CMD_AUTHS sessionsData; TSS2_SYS_RSP_AUTHS sessionsDataOut; TPM2B_ATTEST quoted = { { sizeof(TPM2B_ATTEST)-2, } }; TPMT_SIGNATURE signature; TPMS_AUTH_COMMAND *sessionDataArray[1]; TPMS_AUTH_RESPONSE *sessionDataOutArray[1]; sessionDataArray[0] = &sessionData; sessionDataOutArray[0] = &sessionDataOut; sessionsDataOut.rspAuths = &sessionDataOutArray[0]; sessionsData.cmdAuths = &sessionDataArray[0]; sessionsDataOut.rspAuthsCount = 1; sessionsData.cmdAuthsCount = 1; sessionData.sessionHandle = TPM_RS_PW; sessionData.nonce.t.size = 0; *( (UINT8 *)((void *)&sessionData.sessionAttributes ) ) = 0; if (sessionData.hmac.t.size > 0 && hexPasswd) { sessionData.hmac.t.size = sizeof(sessionData.hmac) - 2; if (hex2ByteStructure((char *)sessionData.hmac.t.buffer, &sessionData.hmac.t.size, sessionData.hmac.t.buffer) != 0) { printf( "Failed to convert Hex format password for AK Passwd.\n"); return -1; } } if(!qualifedData.t.size) { qualifyingData.t.size = sizeof( qualDataString ); memcpy( &qualifyingData.t.buffer[0], qualDataString, sizeof( qualDataString ) ); } else { qualifyingData = qualifedData; // shallow copy ok since there are no pointers } inScheme.scheme = TPM_ALG_NULL; pcrSelection.count = 1; pcrSelection.pcrSelections[0].hash = algorithmId; pcrSelection.pcrSelections[0].sizeofSelect = 3; // Clear out PCR select bit field pcrSelection.pcrSelections[0].pcrSelect[0] = 0; pcrSelection.pcrSelections[0].pcrSelect[1] = 0; pcrSelection.pcrSelections[0].pcrSelect[2] = 0; // Now set the PCR you want for(int l=0;l<pcrList.size; l++) { UINT32 pcrId = pcrList.id[l]; pcrSelection.pcrSelections[0].pcrSelect[( pcrId/8 )] |= ( 1 << ( pcrId) % 8); } memset( (void *)&signature, 0, sizeof(signature) ); rval = Tss2_Sys_Quote(sysContext, akHandle, &sessionsData, &qualifyingData, &inScheme, &pcrSelection, "ed, &signature, &sessionsDataOut ); if(rval != TPM_RC_SUCCESS) { printf("\nQuote Failed ! ErrorCode: 0x%0x\n\n", rval); return -1; } printf( "\nquoted:\n " ); PrintSizedBuffer( (TPM2B *)"ed ); //PrintTPM2B_ATTEST("ed); printf( "\nsignature:\n " ); PrintBuffer( (UINT8 *)&signature, sizeof(signature) ); //PrintTPMT_SIGNATURE(&signature); FILE *fp = fopen(outFilePath,"w+"); if(NULL == fp) { printf("OutFile: %s Can Not Be Created !\n",outFilePath); return -2; } if(fwrite("ed, calcSizeofTPM2B_ATTEST("ed), 1 ,fp) != 1) { fclose(fp); printf("OutFile: %s Write quoted Data In Error!\n",outFilePath); return -3; } if(fwrite(&signature, calcSizeofTPMT_SIGNATURE(&signature), 1, fp) != 1) { fclose(fp); printf("OutFile: %s Write signature Data In Error!\n",outFilePath); return -4; } fclose(fp); return 0; }
// // Function: Rcv_ProcessHeap // // Description: Extract All Data SDU's from Heap and Insert Them Into Receive Queue // // Arguments: // // Name Type Direction Description // ----------- ----------- ----------- ----------------------------------- // UnProcessedData HeapBuffDef * IN Data buffer to process // // Return Values: // // Name Explanation // ----------- ---------------------------------------------------------------- // RetStatus Last Rcv_ProcessSDU status // static int Rcv_ProcessHeap( HeapBuffDef *UnProcessedData, DataRecord *pModemStatus ) { int RetStatus = RM_SUCCESS; int i; t_uchar *pCurr = UnProcessedData->DataBuffer; t_uchar *pEnd = UnProcessedData->DataBuffer + UnProcessedData->DataLength; #ifdef RM_HEAP t_uchar *Buff = (t_uchar *)Mem_Allocate(MAX_LENGTH_MSG); #else t_uchar Buff[MAX_LENGTH_MSG]; #endif while ( pCurr < pEnd ) { //Find SOH and EOT and copy data between to Buff[] ( include SOH and EOT ) //Decode Buff[] //Check integrity of Buff[] //If integruty is OK - process data of Buff[] //-- Find first SOH --------------------------------------------- while( (*pCurr) != SOH && pCurr < pEnd ) pCurr++; if ( pCurr >= pEnd ) //or Length <= 0 { //SOH no found - BAD DATA UnProcessedData->DataLength = 0; // RetStatus = RM_ERROR_NO_DATA; break; //No Data In UnProcessedData }//end if //-- Copy to buffer till EOT or end of Data --------------------- i=0; Buff[i++] = *pCurr; //*pCurr = SOH do{ pCurr++; Buff[i++] = *pCurr; }while( (*pCurr) != EOT && pCurr < pEnd ); if ( pCurr >= pEnd ) break; //No Data - It's OK. EOT may be in next packet //Shift My Heap for ONE message left ( i bytes left ) UnProcessedData->DataLength = Data_BuffShiftLeft( UnProcessedData->DataBuffer, i, UnProcessedData->DataLength ); //Adjust End and Current pCurr = UnProcessedData->DataBuffer; pEnd = UnProcessedData->DataBuffer + UnProcessedData->DataLength; //Replace DLE to normal character sequence //Not important SOH and EOT - they not DLE Data_DecodeSpecialCaraters( Buff, &i ); //Buff[] ==> [SOH][DATA][INTEGRITY][EOT] //Buff+1 ==> [DATA][INTEGRITY][EOT] //i-2 ==> [DATA][INTEGRITY] // [SOH] + [EOT] = 2 bytes if ( Data_CheckIntegrity( Buff+1, i-2 ) != RM_SUCCESS ) { PrintBuffer( "[E] RECEIVED BAD Buffer ( [SOH][DATA][INTEGRITY][EOT] ) :", Buff, i ); continue; //Bad SDU }//end if ////////////////////////////////////////////////// // And at last we can check SDU - what is it? //Buff[] ==> [SOH][DATA][INTEGRITY][EOT] //Buff+1 ==> [DATA][INTEGRITY][EOT] //i-4 ==> [DATA] // [SOH] + [INTEGRITY] + [EOT] = 4 bytes RetStatus = Rcv_ProcessSDU( pModemStatus, Buff+1, i-4 ); }//End While #ifdef RM_HEAP Mem__Free( Buff ); #endif return( RetStatus ); }//end Rcv_ProcessHeap
byte Dynamixel::txRxPacket(byte bID, byte bInst, byte bTxParaLen){ //#define TRY_NUM 2//;;2 mDXLtxrxStatus = 0; byte bTxLen, bRxLenEx, bTryCount; mBusUsed = 1; mRxLength = bRxLenEx = 0; for(bTryCount = 0; bTryCount < gbDXLNumberTxRxAttempts; bTryCount++)//for(bTryCount = 0; bTryCount < TRY_NUM; bTryCount++) { //gbDXLReadPointer = gbDXLWritePointer; mDxlDevice->read_pointer = mDxlDevice->write_pointer;//[ROBOTIS]BufferClear050728 bTxLen = this->txPacket(bID, bInst, bTxParaLen); if (bTxLen == (bTxParaLen+4+2)){ mDXLtxrxStatus = (1<<COMM_TXSUCCESS); } // else{ // return 0; // } if(bInst == INST_PING){ if(bID == BROADCAST_ID){ mRxLength = bRxLenEx = 255; // } else{ mRxLength = bRxLenEx = 6; // basic response packet length } } else if(bInst == INST_READ){ //mRxLength = bRxLenEx = 6+mParamBuffer[1]; // basic response packet length + requested data length in read instruction if (gbDXLStatusReturnLevel>0) mRxLength = bRxLenEx = 6+mParamBuffer[1]; else mRxLength = bRxLenEx = 0; } else if( bID == BROADCAST_ID ){ mRxLength = bRxLenEx = 0; // no response packet in case broadcast id break; } else{ //mRxLength = bRxLenEx = 6; //basic response packet length if (gbDXLStatusReturnLevel>1) mRxLength = bRxLenEx = 6+mParamBuffer[1]; else mRxLength = bRxLenEx = 0; } if(bRxLenEx){//(gbpValidServo[bID] > 0x81 || bInst != INST_WRITE)) //ValidServo = 0x80|RETURN_LEVEL mRxLength = this->rxPacket(bRxLenEx); //TxDStringC("gbRxLength = ");TxDHex8C(mRxLength);TxDStringC("\r\n"); //TxDStringC("bRxLenEx = ");TxDHex8C(bRxLenEx);TxDStringC("\r\n"); // if(gbRxLength != bRxLenEx) //&& bRxLenEx != 255) before Ver 1.11e if((mRxLength != bRxLenEx) && (bRxLenEx != 255)) // after Ver 1.11f { //TxDStringC(" Length mismatch!!\r\n"); unsigned long ulCounter; word wTimeoutCount; ulCounter = 0; wTimeoutCount = 0; //TxDStringC("\r\n TEST POINT 0"); while(ulCounter++ < RX_TIMEOUT_COUNT2) { //if(gbDXLReadPointer != gbDXLWritePointer) if(this->available()) //data is available in dxl bus { mDxlDevice->read_pointer = mDxlDevice->write_pointer;// gbDXLWritePointer; //BufferClear ulCounter = 0; if(wTimeoutCount++ > 100 ) { //uDelay(0);// porting ydh added break; //porting ydh 100->245 //;;;;;; min max µÚ¹Ù²ñ found at Ver 1.11e } nDelay(NANO_TIME_DELAY);// porting ydh added 20120210. } //uDelay(0);// porting ydh added nDelay(NANO_TIME_DELAY);// porting ydh added } //TxDStringC("\r\n TEST POINT 111"); mDxlDevice->read_pointer = mDxlDevice->write_pointer; //BufferClear } else{ //TxDStringC("\r\n TEST POINT 6"); break; } }//bRxLenEx is exist } //TxDStringC("\r\n TEST POINT 2");//TxDString("\r\n Err ID:0x"); mBusUsed = 0; if((mRxLength != bRxLenEx) && (mTxBuffer[2] != BROADCAST_ID)) { //TxDByteC('3');// //TxDStringC("Rx Error\r\n");//TxDString("\r\n Err ID:0x"); #ifdef PRINT_OUT_COMMUNICATION_ERROR_TO_USART2 //TxDString("\r\n Err ID:0x"); //TxDHex8(bID); TxDStringC("\r\n ->[DXL]Err: "); PrintBuffer(mTxBuffer,bTxLen); TxDStringC("\r\n <-[DXL]Err: "); PrintBuffer(mRxBuffer,mRxLength); #endif #ifdef PRINT_OUT_TRACE_ERROR_PRINT_TO_USART2 //TxDString("\r\n {[ERROR:");TxD16Hex(0x8100);TxDByte(':');TxD16Hex(bID);TxDByte(':');TxD8Hex(bInst);TxDByte(']');TxDByte('}'); //TxDByte(bID);TxDByte(' '); //TxDByte(bInst);TxDByte(' '); //TxDByte(gbpParameter[0]);TxDByte(' '); //TxDByte(gbpParameter[1]);TxDByte(' '); #endif return 0; }else if((mRxLength == 0) && (mTxBuffer[4] == INST_PING)){ //[ROBOTIS] 2013-11-22 correct response for ping instruction return 0; } //TxDString("\r\n TEST POINT 4");//TxDString("\r\n Err ID:0x"); #ifdef PRINT_OUT_PACKET_TO_USART2 TxDStringC("\r\n ->[TX Buffer]: "); printBuffer(mTxBuffer,bTxLen); TxDStringC("\r\n <-[RX Buffer]: "); printBuffer(mRxBuffer,mRxLength); #endif mDXLtxrxStatus = (1<<COMM_RXSUCCESS); //gbLengthForPacketMaking =0; return 1; }