Example #1
0
int CmdHF14AReader(const char *Cmd)
{
	UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_NO_DISCONNECT, 0, 0}};
	SendCommand(&c);

	UsbCommand resp;
	WaitForResponse(CMD_ACK,&resp);
	
	iso14a_card_select_t card;
	memcpy(&card, (iso14a_card_select_t *)resp.d.asBytes, sizeof(iso14a_card_select_t));

	uint64_t select_status = resp.arg[0];		// 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS
	
	if(select_status == 0) {
		PrintAndLog("iso14443a card select failed");
		// disconnect
		c.arg[0] = 0;
		c.arg[1] = 0;
		c.arg[2] = 0;
		SendCommand(&c);
		return 0;
	}

	PrintAndLog("ATQA : %02x %02x", card.atqa[1], card.atqa[0]);
	PrintAndLog(" UID : %s", sprint_hex(card.uid, card.uidlen));
	PrintAndLog(" SAK : %02x [%d]", card.sak, resp.arg[0]);

	// Double & triple sized UID, can be mapped to a manufacturer.
	// HACK: does this apply for Ultralight cards?
	if ( card.uidlen > 4 ) {
		PrintAndLog("MANUFACTURER : %s", getTagInfo(card.uid[0]));
	}

	switch (card.sak) {
		case 0x00: PrintAndLog("TYPE : NXP MIFARE Ultralight | Ultralight C"); break;
		case 0x01: PrintAndLog("TYPE : NXP TNP3xxx Activision Game Appliance"); break;
		case 0x04: PrintAndLog("TYPE : NXP MIFARE (various !DESFire !DESFire EV1)"); break;
		case 0x08: PrintAndLog("TYPE : NXP MIFARE CLASSIC 1k | Plus 2k SL1"); break;
		case 0x09: PrintAndLog("TYPE : NXP MIFARE Mini 0.3k"); break;
		case 0x10: PrintAndLog("TYPE : NXP MIFARE Plus 2k SL2"); break;
		case 0x11: PrintAndLog("TYPE : NXP MIFARE Plus 4k SL2"); break;
		case 0x18: PrintAndLog("TYPE : NXP MIFARE Classic 4k | Plus 4k SL1"); break;
		case 0x20: PrintAndLog("TYPE : NXP MIFARE DESFire 4k | DESFire EV1 2k/4k/8k | Plus 2k/4k SL3 | JCOP 31/41"); break;
		case 0x24: PrintAndLog("TYPE : NXP MIFARE DESFire | DESFire EV1"); break;
		case 0x28: PrintAndLog("TYPE : JCOP31 or JCOP41 v2.3.1"); break;
		case 0x38: PrintAndLog("TYPE : Nokia 6212 or 6131 MIFARE CLASSIC 4K"); break;
		case 0x88: PrintAndLog("TYPE : Infineon MIFARE CLASSIC 1K"); break;
		case 0x98: PrintAndLog("TYPE : Gemplus MPCOS"); break;
		default: ;
	}

	// try to request ATS even if tag claims not to support it
	if (select_status == 2) {
		uint8_t rats[] = { 0xE0, 0x80 }; // FSDI=8 (FSD=256), CID=0
		c.arg[0] = ISO14A_RAW | ISO14A_APPEND_CRC | ISO14A_NO_DISCONNECT;
		c.arg[1] = 2;
		c.arg[2] = 0;
		memcpy(c.d.asBytes, rats, 2);
		SendCommand(&c);
		WaitForResponse(CMD_ACK,&resp);
		
	    memcpy(&card.ats, resp.d.asBytes, resp.arg[0]);
		card.ats_len = resp.arg[0];				// note: ats_len includes CRC Bytes
	} 

	if(card.ats_len >= 3) {			// a valid ATS consists of at least the length byte (TL) and 2 CRC bytes
		bool ta1 = 0, tb1 = 0, tc1 = 0;
		int pos;

		if (select_status == 2) {
			PrintAndLog("SAK incorrectly claims that card doesn't support RATS");
		}
		PrintAndLog(" ATS : %s", sprint_hex(card.ats, card.ats_len));
		PrintAndLog("       -  TL : length is %d bytes", card.ats[0]);
		if (card.ats[0] != card.ats_len - 2) {
			PrintAndLog("ATS may be corrupted. Length of ATS (%d bytes incl. 2 Bytes CRC) doesn't match TL", card.ats_len);
		}
		
		if (card.ats[0] > 1) {		// there is a format byte (T0)
			ta1 = (card.ats[1] & 0x10) == 0x10;
			tb1 = (card.ats[1] & 0x20) == 0x20;
			tc1 = (card.ats[1] & 0x40) == 0x40;
			int16_t fsci = card.ats[1] & 0x0f;
			PrintAndLog("       -  T0 : TA1 is%s present, TB1 is%s present, "
					"TC1 is%s present, FSCI is %d (FSC = %ld)",
				(ta1 ? "" : " NOT"), (tb1 ? "" : " NOT"), (tc1 ? "" : " NOT"),
				fsci,
				fsci < 5 ? (fsci - 2) * 8 : 
					fsci < 8 ? (fsci - 3) * 32 :
					fsci == 8 ? 256 :
					-1
				);
		}
		pos = 2;
		if (ta1) {
			char dr[16], ds[16];
			dr[0] = ds[0] = '\0';
			if (card.ats[pos] & 0x10) strcat(ds, "2, ");
			if (card.ats[pos] & 0x20) strcat(ds, "4, ");
			if (card.ats[pos] & 0x40) strcat(ds, "8, ");
			if (card.ats[pos] & 0x01) strcat(dr, "2, ");
			if (card.ats[pos] & 0x02) strcat(dr, "4, ");
			if (card.ats[pos] & 0x04) strcat(dr, "8, ");
			if (strlen(ds) != 0) ds[strlen(ds) - 2] = '\0';
			if (strlen(dr) != 0) dr[strlen(dr) - 2] = '\0';
			PrintAndLog("       - TA1 : different divisors are%s supported, "
					"DR: [%s], DS: [%s]",
					(card.ats[pos] & 0x80 ? " NOT" : ""), dr, ds);
			pos++;
		}
		if (tb1) {
			uint32_t sfgi = card.ats[pos] & 0x0F;
			uint32_t fwi = card.ats[pos] >> 4;
			PrintAndLog("       - TB1 : SFGI = %d (SFGT = %s%ld/fc), FWI = %d (FWT = %ld/fc)",
					(sfgi),
					sfgi ? "" : "(not needed) ",
					sfgi ? (1 << 12) << sfgi : 0,
					fwi,
					(1 << 12) << fwi
					);
			pos++;
		}
		if (tc1) {
			PrintAndLog("       - TC1 : NAD is%s supported, CID is%s supported",
					(card.ats[pos] & 0x01) ? "" : " NOT",
					(card.ats[pos] & 0x02) ? "" : " NOT");
			pos++;
		}
		if (card.ats[0] > pos) {
			char *tip = "";
			if (card.ats[0] - pos >= 7) {
				if (memcmp(card.ats + pos, "\xC1\x05\x2F\x2F\x01\xBC\xD6", 7) == 0) {
					tip = "-> MIFARE Plus X 2K or 4K";
				} else if (memcmp(card.ats + pos, "\xC1\x05\x2F\x2F\x00\x35\xC7", 7) == 0) {
					tip = "-> MIFARE Plus S 2K or 4K";
				}
			} 
			PrintAndLog("       -  HB : %s%s", sprint_hex(card.ats + pos, card.ats[0] - pos), tip);
			if (card.ats[pos] == 0xC1) {
				PrintAndLog("               c1 -> Mifare or (multiple) virtual cards of various type");
				PrintAndLog("                  %02x -> Length is %d bytes",
						card.ats[pos + 1], card.ats[pos + 1]);
				switch (card.ats[pos + 2] & 0xf0) {
					case 0x10:
						PrintAndLog("                     1x -> MIFARE DESFire");
						break;
					case 0x20:
						PrintAndLog("                     2x -> MIFARE Plus");
						break;
				}
				switch (card.ats[pos + 2] & 0x0f) {
					case 0x00:
						PrintAndLog("                     x0 -> <1 kByte");
						break;
					case 0x01:
						PrintAndLog("                     x0 -> 1 kByte");
						break;
					case 0x02:
						PrintAndLog("                     x0 -> 2 kByte");
						break;
					case 0x03:
						PrintAndLog("                     x0 -> 4 kByte");
						break;
					case 0x04:
						PrintAndLog("                     x0 -> 8 kByte");
						break;
				}
				switch (card.ats[pos + 3] & 0xf0) {
					case 0x00:
						PrintAndLog("                        0x -> Engineering sample");
						break;
					case 0x20:
						PrintAndLog("                        2x -> Released");
						break;
				}
				switch (card.ats[pos + 3] & 0x0f) {
					case 0x00:
						PrintAndLog("                        x0 -> Generation 1");
						break;
					case 0x01:
						PrintAndLog("                        x1 -> Generation 2");
						break;
					case 0x02:
						PrintAndLog("                        x2 -> Generation 3");
						break;
				}
				switch (card.ats[pos + 4] & 0x0f) {
					case 0x00:
						PrintAndLog("                           x0 -> Only VCSL supported");
						break;
					case 0x01:
						PrintAndLog("                           x1 -> VCS, VCSL, and SVC supported");
						break;
					case 0x0E:
						PrintAndLog("                           xE -> no VCS command supported");
						break;
				}
			}
		}
	} else {
void IncomingSession(HostStuff* phoststuff, char* buffer, DupFeedBackSession fse)
{
	pthread_mutex_lock(&phoststuff->cmd_lock);  
	
	//printf("cmd:%s\n", buffer);
	
	int len=strlen(buffer);
	if (len<=0) return;
  char *pos;
  if ((pos=strchr(buffer, '\n')) != NULL)
    *pos = '\0';
    
  char command[256];    
  if (-1==sscanf(buffer,"%s",command)) return;	
	
		string s_command=(const char*)command;
	
	  if (s_command=="Shutdown" || s_command=="Reboot")
	  {
	    SendCommand("Quit",phoststuff->fout);
	    if (s_command=="Shutdown")
	    {
	      PlaySound("shutdown.mp3");
	      system("sudo halt -p");
	    }
	    else if (s_command=="Reboot")
	    {
	      PlaySound("reboot.mp3");
	      system("sudo reboot");
	    }
	    exit(0);
	  }
	 	else if (s_command=="ResetCDWatch")
    {
      if (phoststuff->cfbInfo.m_CDStatusSocket.m_se.IsValid())
      {
        fse->FeedBack("playing\n");
        phoststuff->cfbInfo.m_CDStatusSocket.m_resetSocket=true;
	  		SendCommand("CurTrack",phoststuff->fout);
        sem_wait(&phoststuff->cfbInfo.m_CDStatusSocket.m_finish_sem);
        phoststuff->cfbInfo.m_CDStatusSocket.m_se=fse;
        sem_post(&phoststuff->cfbInfo.m_CDStatusSocket.m_start_sem);
      }
      else
      {
        fse->FeedBack("notplaying\n");
      }
    }
    else if (s_command=="ResetListWatch")
    {
      if (phoststuff->cfbInfo.m_ListStatusSocket.m_se.IsValid())
      {
        fse->FeedBack("playing\n");
        phoststuff->cfbInfo.m_ListStatusSocket.m_resetSocket=true;
	  		SendCommand("CurSong",phoststuff->fout);
        sem_wait(&phoststuff->cfbInfo.m_ListStatusSocket.m_finish_sem);
        phoststuff->cfbInfo.m_ListStatusSocket.m_se=fse;
        sem_post(&phoststuff->cfbInfo.m_ListStatusSocket.m_start_sem);
      }
      else
      {
        fse->FeedBack("notplaying\n");
      }
    }      
    else if (s_command=="test")
		{
			//((FeedBackSession*)fse)->FeedBack("Hello World!");
			fse->FeedBack("Hello World!");
		}      
		else if (s_command=="UpdatePod")
		{
			system("/home/pi/updatepod.sh");
		}     
	  else
  	{
  		SendCommand(buffer,phoststuff->fout);
      if (s_command=="PlayCD")
      {
        sem_wait(&phoststuff->cfbInfo.m_CDStatusSocket.m_finish_sem);
        phoststuff->cfbInfo.m_CDStatusSocket.m_resetSocket=false;
        phoststuff->cfbInfo.m_CDStatusSocket.m_se=fse;
        sem_post(&phoststuff->cfbInfo.m_CDStatusSocket.m_start_sem);
      }
      else if (s_command=="ListCD")
      {
        phoststuff->cfbInfo.m_CDListSocket.m_se=fse;
        sem_post(&phoststuff->cfbInfo.m_CDListSocket.m_start_sem);
        sem_wait(&phoststuff->cfbInfo.m_CDListSocket.m_finish_sem);
      }
			else if (s_command=="PlayList")
      {
        sem_wait(&phoststuff->cfbInfo.m_ListStatusSocket.m_finish_sem);
        phoststuff->cfbInfo.m_ListStatusSocket.m_resetSocket=false;
        phoststuff->cfbInfo.m_ListStatusSocket.m_se=fse;
        sem_post(&phoststuff->cfbInfo.m_ListStatusSocket.m_start_sem);
      }
			else if (s_command=="ListLists")
      {
        phoststuff->cfbInfo.m_ListListsSocket.m_se=fse;
        sem_post(&phoststuff->cfbInfo.m_ListListsSocket.m_start_sem);
        sem_wait(&phoststuff->cfbInfo.m_ListListsSocket.m_finish_sem);
      } 
    	else if (s_command=="ListSongs")
      {
        phoststuff->cfbInfo.m_ListSongsSocket.m_se=fse;
        sem_post(&phoststuff->cfbInfo.m_ListSongsSocket.m_start_sem);
        sem_wait(&phoststuff->cfbInfo.m_ListSongsSocket.m_finish_sem);
      } 
  	}
			
	pthread_mutex_unlock(&phoststuff->cmd_lock);  
}
Example #3
0
void CScreenProfile::HandleDlgCommand(uint32 dwCommand, uint16 nIndex)
{
	switch (dwCommand)
	{
	case CMD_LOAD:
		{
			SAFE_STRCPY(m_szOldProfile,m_szProfile);
			if (nIndex < m_pListCtrl->GetNumControls()) 
			{
				StringSet::iterator iter = m_ProfileList.begin();
				for (int i = 0; i < nIndex && iter != m_ProfileList.end(); ++i, ++iter);

				if (iter != m_ProfileList.end())
				{
					std::string profile = *iter;
					if (g_pLTClient->IsConnected() && stricmp(profile.c_str(), m_szProfile))
					{

						MBCreate mb;
						mb.eType = LTMB_YESNO;
						mb.pFn = LoadCallBack,
						mb.pData = (void *)nIndex;
						g_pInterfaceMgr->ShowMessageBox(IDS_CONFIRM_NEWPROFILE,&mb);
					}
					else
						SendCommand(CMD_CONFIRM,nIndex,CMD_LOAD);

				}
			}
		}
		break;
	case CMD_DELETE:
		{
			MBCreate mb;
			mb.eType = LTMB_YESNO;
			mb.pFn = DeleteCallBack,
			mb.pData = (void *)nIndex;
			g_pInterfaceMgr->ShowMessageBox(IDS_CONFIRM_DELETE_PROFILE,&mb);
		}
		break;
	case CMD_RENAME:
		SAFE_STRCPY(m_szOldProfile,m_szProfile);
		if (nIndex < m_pListCtrl->GetNumControls()) 
		{
			StringSet::iterator iter = m_ProfileList.begin();
			for (int i = 0; i < nIndex && iter != m_ProfileList.end(); ++i, ++iter);

			if (iter != m_ProfileList.end())
			{
				std::string profile = *iter;
				SAFE_STRCPY(szOldFN,profile.c_str());
				SAFE_STRCPY(m_szProfile, profile.c_str());
				bCreate = LTFALSE;
				MBCreate mb;
				mb.eType = LTMB_EDIT;
				mb.pFn = EditCallBack;
				mb.pString = m_szProfile;
				mb.nMaxChars = 16;
				mb.eInput = CLTGUIEditCtrl::kInputFileFriendly;
				g_pInterfaceMgr->ShowMessageBox(IDS_ENTER_PROFILE_NAME,&mb);
			}
		}
		break;
	}

};
Example #4
0
CSpoofRemote::~CSpoofRemote()
{
	if(IsConnected())
		SendCommand("exit");
}
void CSelectedUnits::GiveCommand(Command c,bool fromUser)
{
//	info->AddLine("Command given %i",c.id);
	if(gu->spectating || selectedUnits.empty())
		return;

	if(fromUser){		//add some statistics
		gs->players[gu->myPlayerNum]->currentStats->numCommands++;
		if(selectedGroup!=-1){
			gs->players[gu->myPlayerNum]->currentStats->unitCommands+=grouphandler->groups[selectedGroup]->units.size();
		} else {
			gs->players[gu->myPlayerNum]->currentStats->unitCommands+=selectedUnits.size();
		}
	}

	if(c.id==CMD_GROUPCLEAR){
		for(set<CUnit*>::iterator ui=selectedUnits.begin();ui!=selectedUnits.end();++ui){
			if((*ui)->group)
				(*ui)->SetGroup(0);
		}
		return;
	}

	if(selectedGroup!=-1 && (grouphandler->groups[selectedGroup]->ai || c.id==CMD_AISELECT)){
		grouphandler->groups[selectedGroup]->GiveCommand(c);
		return;
	}

	if(c.id==CMD_GROUPSELECT){
		SelectGroup((*selectedUnits.begin())->group->id);
		return;
	}

	if(c.id==CMD_GROUPADD){
		CGroup* group=0;
		for(set<CUnit*>::iterator ui=selectedUnits.begin();ui!=selectedUnits.end();++ui){
			if((*ui)->group){
				group=(*ui)->group;
				break;
			}
		}
		if(group){
			for(set<CUnit*>::iterator ui=selectedUnits.begin();ui!=selectedUnits.end();++ui){
				if(!(*ui)->group)
					(*ui)->SetGroup(group);
			}	
			SelectGroup(group->id);
		}
		return;
	}

	if(c.id==CMD_AISELECT){
		if(c.params[0]!=0){
			map<string,string>::iterator aai;
			int a=0;
			for(aai=grouphandler->availableAI.begin();aai!=grouphandler->availableAI.end() && a<c.params[0]-1;++aai){
				a++;
			}
			CGroup* group=grouphandler->CreateNewGroup(aai->first);

			for(set<CUnit*>::iterator ui=selectedUnits.begin();ui!=selectedUnits.end();++ui){
				(*ui)->SetGroup(group);
			}
			SelectGroup(group->id);
		}
		return;
	}
//	selectedUnitsAI.GiveCommand(c);

	SendCommand(c);

	if(!selectedUnits.empty()){
		set<CUnit*>::iterator ui = selectedUnits.begin();
		if((*ui)->unitDef->sounds.ok.id)
			sound->PlayUnitReply((*ui)->unitDef->sounds.ok.id, (*ui), (*ui)->unitDef->sounds.ok.volume, true);
	}
}
Example #6
0
gxSocketError gxsSMTPClient::SMTPRcptTo(const char *to_email_address)
// Function used to send the SMTP "RCPT TO" command. Returns zero if
// no errors occur.
{
  return SendCommand("RCPT TO:", "250", to_email_address);
}
Example #7
0
gxSocketError gxsSMTPClient::SMTPLogin(const char *domain_name) 
// Function used to send the SMTP "Hello" command. Returns zero if 
// no errors occur.
{
  return SendCommand("HELO", "250", domain_name);
}
char *PrinterSerial::Send( const char *command ) {
  strncpy( command_scratch, command, max_command_size );
  return SendCommand();
}
Example #9
0
bool MySensorsBase::WriteToHardware(const char *pdata, const unsigned char length)
{
	tRBUF *pCmd = (tRBUF *)pdata;
	if (pCmd->LIGHTING2.packettype == pTypeLighting2)
	{
		//Light command

		int node_id = pCmd->LIGHTING2.id4;
		int child_sensor_id = pCmd->LIGHTING2.unitcode;

		if (_tMySensorNode *pNode = FindNode(node_id))
		{
			int light_command = pCmd->LIGHTING2.cmnd;
			if ((pCmd->LIGHTING2.cmnd == light2_sSetLevel) && (pCmd->LIGHTING2.level == 0))
			{
				light_command = light2_sOff;
			}
			else if ((pCmd->LIGHTING2.cmnd == light2_sSetLevel) && (pCmd->LIGHTING2.level == 255))
			{
				light_command = light2_sOn;
			}

			if ((light_command == light2_sOn) || (light_command == light2_sOff))
			{
				std::string lState = (light_command == light2_sOn) ? "1" : "0";
				if (FindChildWithValueType(node_id, V_LOCK_STATUS) != NULL)
				{
					//Door lock
					SendCommand(node_id, child_sensor_id, MT_Set, V_LOCK_STATUS, lState);
				}
				else if ((FindChildWithValueType(node_id, V_SCENE_ON) != NULL) || (FindChildWithValueType(node_id, V_SCENE_OFF) != NULL))
				{
					//Scene Controller
					SendCommand(node_id, child_sensor_id, MT_Set, (light_command == light2_sOn) ? V_SCENE_ON : V_SCENE_OFF, lState);
				}
				else
				{
					//normal
					SendCommand(node_id, child_sensor_id, MT_Set, V_STATUS, lState);
				}
			}
			else if (light_command == light2_sSetLevel)
			{
				float fvalue = (100.0f / 15.0f)*float(pCmd->LIGHTING2.level);
				if (fvalue > 100.0f)
					fvalue = 100.0f; //99 is fully on
				int svalue = round(fvalue);

				std::stringstream sstr;
				sstr << svalue;
				SendCommand(node_id, child_sensor_id, MT_Set, V_PERCENTAGE, sstr.str());
			}
		}
		else {
			_log.Log(LOG_ERROR, "MySensors: Light command received for unknown node_id: %d", node_id);
			return false;
		}
	}
	else if (pCmd->LIGHTING2.packettype == pTypeLimitlessLights)
	{
		//RGW/RGBW command
		_tLimitlessLights *pLed = (_tLimitlessLights *)pdata;
		unsigned char ID1 = (unsigned char)((pLed->id & 0xFF000000) >> 24);
		unsigned char ID2 = (unsigned char)((pLed->id & 0x00FF0000) >> 16);
		unsigned char ID3 = (unsigned char)((pLed->id & 0x0000FF00) >> 8);
		unsigned char ID4 = (unsigned char)pLed->id & 0x000000FF;

		int node_id = (ID3 << 8) | ID4;
		int child_sensor_id = pLed->dunit;

		if (_tMySensorNode *pNode = FindNode(node_id))
		{
			bool bIsRGBW = (pNode->FindChildWithPresentationType(child_sensor_id, S_RGBW_LIGHT) != NULL);
			if (pLed->command == Limitless_SetRGBColour)
			{
				int red, green, blue;

				float cHue = (360.0f / 255.0f)*float(pLed->value);//hue given was in range of 0-255
				int Brightness = 100;
				int dMax = round((255.0f / 100.0f)*float(Brightness));
				hue2rgb(cHue, red, green, blue, dMax);
				std::stringstream sstr;
				sstr << std::setw(2) << std::uppercase << std::hex << std::setfill('0') << std::hex << red
					<< std::setw(2) << std::uppercase << std::hex << std::setfill('0') << std::hex << green
					<< std::setw(2) << std::uppercase << std::hex << std::setfill('0') << std::hex << blue;
				SendCommand(node_id, child_sensor_id, MT_Set, (bIsRGBW == true) ? V_RGBW : V_RGB, sstr.str());
			}
			else if (pLed->command == Limitless_SetColorToWhite)
			{
				std::stringstream sstr;
				int Brightness = 100;
				int wWhite = round((255.0f / 100.0f)*float(Brightness));
				if (!bIsRGBW)
				{
					sstr << std::setw(2) << std::uppercase << std::hex << std::setfill('0') << std::hex << wWhite
						<< std::setw(2) << std::uppercase << std::hex << std::setfill('0') << std::hex << wWhite
						<< std::setw(2) << std::uppercase << std::hex << std::setfill('0') << std::hex << wWhite;
				}
				else
				{
					sstr << "#000000"
						<< std::setw(2) << std::uppercase << std::hex << std::setfill('0') << std::hex << wWhite;
				}
				SendCommand(node_id, child_sensor_id, MT_Set, (bIsRGBW == true) ? V_RGBW : V_RGB, sstr.str());
			}
			else if (pLed->command == Limitless_SetBrightnessLevel)
			{
				float fvalue = pLed->value;
				int svalue = round(fvalue);
				if (svalue > 100)
					svalue = 100;
				std::stringstream sstr;
				sstr << svalue;
				SendCommand(node_id, child_sensor_id, MT_Set, V_PERCENTAGE, sstr.str());
			}
			else if ((pLed->command == Limitless_LedOff) || (pLed->command == Limitless_LedOn))
			{
				std::string lState = (pLed->command == Limitless_LedOn) ? "1" : "0";
				SendCommand(node_id, child_sensor_id, MT_Set, V_STATUS, lState);
			}
		}
		else
		{
			_log.Log(LOG_ERROR, "MySensors: Light command received for unknown node_id: %d", node_id);
			return false;
		}
	}
/// 收到一个headerLine后对应发下一个Command或连接数据通道(  edit code from shareaza )
BOOL CFtpClientReqSocket::OnHeaderLine ( CStringA& strHeader, CStringA& strValue )
{
    TRACE( ">> %s: %s\n", strHeader, strValue );
    m_bDecLaunchTimes = FALSE;
    m_bServerErr = FALSE;

    if( strHeader[0]=='4' )
    {
        m_bDecLaunchTimes = TRUE;
    }
    else if( strHeader[0]=='5' )
    {
        m_bServerErr = TRUE;
    }

    if( strHeader=="450" && m_FtpState==ftpABOR )
    {
        return TRUE;
    }
    else if( m_bDecLaunchTimes || m_bServerErr )
    {
        (DYNAMIC_DOWNCAST(CFtpClient,GetClient()))->OnCmdSocketErr(strHeader);
        return TRUE;
    }

    switch( m_FtpState )
    {
    case ftpConnecting:
        if ( strHeader == "220" ) // Connected
        {
            m_FtpState = ftpUSER;
            return SendCommand();
        }
        break;

    case ftpUSER:
        if ( strHeader == "331" )	// Access allowed
        {
            m_FtpState = ftpPASS;
            return SendCommand ();
        } else if( strHeader == "230" ) {	// no need pass
            m_FtpState = ftpSIZE_TYPE;  // ftpSIZE_TYPE
            return SendCommand();
        }

        // Wrong login or other errors
        // 530: This FTP server is anonymous only.
        break;

    case ftpPASS:
        if ( strHeader == "230" )	// Logged in
        {
            m_FtpState = ftpCWD;  // ftpSIZE_TYPE
            return SendCommand();
        }
        break;
    case ftpCWD:
        if ( strHeader == "250" )	// Type I setted
        {
            m_FtpState = ftpSIZE_TYPE;
            return SendCommand();
        }
        break;
    case ftpSIZE_TYPE:
        if ( strHeader == "200" )	// Type I setted
        {
            m_FtpState = ftpSIZE;
            return SendCommand();
        }
        break;
    case ftpSIZE:
        if ( strHeader == "213" )	// SIZE reply
        {
            uint64 ui64FileSize = _atoi64( strValue );
            if( (DYNAMIC_DOWNCAST(CFtpClient,GetClient()))->OnFileSizeKnown( ui64FileSize ) ) //can go on
            {
                m_FtpState = ftpRETR_PASVPORT;
                return SendCommand();
            }
            else
            {
                m_FtpState = ftpABOR; //< 对应的Peer不参与下载,socket abort 结束!
                return SendCommand();
            }
        }
        break;

    case ftpRETR_TYPE:
        if ( strHeader == "200" )	// Type I setted
        {
            m_FtpState = ftpRETR_PASVPORT;
            return SendCommand();
        }
        break;

    case ftpRETR_PASVPORT:
        if ( strHeader == "227" || strHeader == "200" )	// Entered passive or active mode
        {
            if ( m_bPassive )
            {
                SOCKADDR_IN host;
                if( !ParsePASVArgs( strValue, host ) )
                {
                    // Wrong PASV reply format
                    ASSERT( FALSE );
                    return FALSE;
                }
                else
                {
                    CFtpClientDataSocket *pClientDataSocket = (DYNAMIC_DOWNCAST(CFtpClient,GetClient()))->GetClientDataSocket(false);
                    if( NULL!=pClientDataSocket )
                        (DYNAMIC_DOWNCAST(CFtpClient,GetClient()))->CloseDataSocket();
                    pClientDataSocket = (DYNAMIC_DOWNCAST(CFtpClient,GetClient()))->GetClientDataSocket();
                    if( pClientDataSocket->Create() )
                    {
                        /// 按ftp服务器给的ip地址和端口开始连通数据通道.
                        pClientDataSocket->Connect( (SOCKADDR*)&host, sizeof host );
                        return TRUE;
                    }
                    else
                    {
                        m_FtpState = ftpABOR;
                    }
                    //return TRUE;
                }
            }
            else
            {
                m_FtpState = ftpABOR;
            }
            m_FtpState = ftpRETR_REST;
            return SendCommand();
        }
        break;

    case ftpRETR_REST:
        if ( strHeader == "350" )	// Offset setted
        {
            GetClient()->SetDownloadState( DS_DOWNLOADING ); //这时候就应该进入下载阶段了.

            m_FtpState = ftpRETR;
            return SendCommand (); /// ok,可以开始向ftp服务器请求要下载的文件了
        }
        break;

    case ftpRETR:
        if ( strHeader == "125" || strHeader == "150" )	// Transfer started
        {
            //GetClient()->SetDownloadState( DS_DOWNLOADING ); //放在这里可能数据已经来了,但该消息还没来.他们是异步的.
            m_FtpState = ftpDownloading;
            return TRUE; // Downloading
        }
        else if ( strHeader == "226" || strHeader == "426" )	// Transfer completed
        {
            m_FtpState = ftpABOR; // Aborting
            return FALSE;
        }

        break;

    case ftpABOR:
    {
        if( GetClient() && (DYNAMIC_DOWNCAST(CFtpClient,GetClient()))->PendingBlockReqCount()>0 )
        {
            m_FtpState = ftpRETR_REST; //ftpRETR_PASVPORT
            SendCommand();
        }
    }
    break;
    case ftpDownloading:
    {
        /// 下载中如果没出错,那就是下完了
    }
    break;
    case ftpClose:
    {
        if( GetClient() && (DYNAMIC_DOWNCAST(CFtpClient,GetClient()))->PendingBlockReqCount()>0 )
        {
            m_FtpState = ftpRETR_PASVPORT;
            SendCommand();
        }
    }
    break;
    default:
        ASSERT( FALSE ); // Really unexpected errors
    }

    return FALSE;
}
BOOL CFtpClientReqSocket::SendCommand( )
{
    CSourceURL &sourceUrl = (DYNAMIC_DOWNCAST(CFtpClient,GetClient()))->m_SourceURL;
    CStringA strLine;

    switch( m_FtpState )
    {
    case ftpUSER:// Sending login
    {
        strLine = "USER ";
        strLine += sourceUrl.m_sLogin;
        break;
    }
    case ftpPASS:// Sending password
    {
        strLine = "PASS ";
        strLine += sourceUrl.m_sPassword;
        break;
    }
    case ftpLIST_PASVPORT:// Selecting passive or active mode
    {
        if ( m_bPassive )
        {
            strLine = "PASV";
        }
        break;
    }
    case ftpSIZE:// Listing file size
    {
        strLine = "SIZE ";
        int pos = sourceUrl.m_sPath.ReverseFind( _T('/') );
        if( pos == -1 ) {
            pos = sourceUrl.m_sPath.ReverseFind( _T('\\') );
        }

        if( pos == -1 ) {
            strLine += sourceUrl.m_sPath;
        } else {
            strLine += (LPCTSTR(sourceUrl.m_sPath) + pos + 1);
        }

        break;
    }
    case ftpCWD:
    {
        strLine = "CWD ";
        int pos = sourceUrl.m_sPath.ReverseFind( _T('/') );
        if( pos == -1 ) {
            pos = sourceUrl.m_sPath.ReverseFind( _T('\\') );
        }

        if( pos == -1 ) {
            this->m_FtpState = ftpSIZE_TYPE;
            return SendCommand();
        } else {
            CString path( LPCTSTR(sourceUrl.m_sPath) , pos );
            strLine += path;
        }
    }
    break;
    case ftpSIZE_TYPE:
    case ftpRETR_TYPE:// Selecting BINARY type for transfer
    {
        strLine = "TYPE I";
        break;
    }
    case ftpRETR_PASVPORT:
    {
        // Selecting passive or active mode
        if ( m_bPassive )
        {
            strLine = "PASV";
        }
        break;
    }
    case ftpRETR_REST: /// 注意断点续传
    {
        uint64 uiStartPos;
        (DYNAMIC_DOWNCAST(CFtpClient,GetClient()))->GetUrlStartPosForReq( uiStartPos ); //< 通知Peer层获取下载任务,并计算请求起始点
        strLine.Format( "REST %I64u", uiStartPos );
        break;
    }
    case ftpRETR: // Retrieving file
    {
        strLine = _T("RETR ");
        int pos = sourceUrl.m_sPath.ReverseFind( _T('/') );
        if( pos == -1 ) {
            pos = sourceUrl.m_sPath.ReverseFind( _T('\\') );
        }

        if( pos == -1 ) {
            strLine += sourceUrl.m_sPath;
        } else {
            strLine += (LPCTSTR(sourceUrl.m_sPath) + pos + 1);
        }
        break;
    }
    case ftpABOR:// Transfer aborting
    {
        strLine = _T("ABOR");
        break;
    }
    default:
        return TRUE;
    }

    if( GetClient() )
        GetClient()->AddPeerLog(new CTraceSendMessage((CString)strLine));

    strLine  += "\r\n";

    TRACE( "<< %s",  (LPCSTR) strLine );

    /*
    	char buffer[1024];

    	// Convert Unicode String to MutiBytes String
    	int nMulti = WideCharToMultiByte( CP_ACP, 0, (LPCWSTR)strLine.GetBuffer(), strLine.GetLength(), NULL, 0 , NULL, NULL);
    	WideCharToMultiByte(CP_ACP, 0, strLine.GetBuffer(), strLine.GetLength(), buffer, nMulti, NULL, NULL);
    	strLine.ReleaseBuffer();
    */

    CRawPacket* pFtpCMDPacket = new CRawPacket(strLine);
    theStats.AddUpDataOverheadFileRequest(pFtpCMDPacket->size);
    SendPacket(pFtpCMDPacket);

    return TRUE;
}
Example #12
0
/*
 * Handle management socket events asynchronously
 */
void
OnManagement(SOCKET sk, LPARAM lParam)
{
    int res;
    char *pos = NULL;
    char data[MAX_LOG_LENGTH];
    connection_t *c = GetConnByManagement(sk);
    if (c == NULL)
        return;

    switch (WSAGETSELECTEVENT(lParam))
    {
    case FD_CONNECT:
        if (WSAGETSELECTERROR(lParam))
            SendMessage(c->hwndStatus, WM_CLOSE, 0, 0);
        break;

    case FD_READ:
        /* Check if there's a complete line to read */
        res = recv(c->manage.sk, data, sizeof(data), MSG_PEEK);
        if (res < 1)
            return;

        pos = memchr(data, (*c->manage.password ? ':' : '\n'), res);
        if (!pos)
            return;

        /* There is data available: read it */
        res = recv(c->manage.sk, data, pos - data + 1, 0);
        if (res != pos - data + 1)
            return;

        /* Reply to a management password request */
        if (*c->manage.password)
        {
            ManagementCommand(c, c->manage.password, NULL, regular);
            *c->manage.password = '******';
            return;
        }

        /* Handle regular management interface output */
        data[pos - data - 1] = '\0';
        if (data[0] == '>')
        {
            /* Real time notifications */
            pos = data + 1;
            if (strncmp(pos, "LOG:", 4) == 0)
            {
                if (rtmsg_handler[log])
                    rtmsg_handler[log](c, pos + 4);
            }
            else if (strncmp(pos, "STATE:", 6) == 0)
            {
                if (rtmsg_handler[state])
                    rtmsg_handler[state](c, pos + 6);
            }
            else if (strncmp(pos, "HOLD:", 5) == 0)
            {
                if (rtmsg_handler[hold])
                    rtmsg_handler[hold](c, pos + 5);
            }
            else if (strncmp(pos, "PASSWORD:"******"INFO:", 5) == 0)
            {
                /* delay until management interface accepts input */
                Sleep(100);
                if (rtmsg_handler[ready])
                    rtmsg_handler[ready](c, pos + 5);
            }
        }
        else if (c->manage.cmd_queue)
        {
            /* Response to commands */
            mgmt_cmd_t *cmd = c->manage.cmd_queue;
            if (strncmp(data, "SUCCESS:", 8) == 0)
            {
                if (cmd->handler)
                    cmd->handler(c, data + 9);
                UnqueueCommand(c);
            }
            else if (strncmp(data, "ERROR:", 6) == 0)
            {
                if (cmd->handler)
                    cmd->handler(c, NULL);
                UnqueueCommand(c);
            }
            else if (strcmp(data, "END") == 0)
            {
                UnqueueCommand(c);
            }
            else if (cmd->handler)
            {
                cmd->handler(c, data);
            }
        }
        break;

    case FD_WRITE:
        SendCommand(c);
        break;

    case FD_CLOSE:
        closesocket(c->manage.sk);
        c->manage.sk = INVALID_SOCKET;
        while (UnqueueCommand(c))
            ;
        WSACleanup();
        if (rtmsg_handler[stop])
            rtmsg_handler[stop](c, "");
        break;
    }
}
Example #13
0
// perform the PACE protocol by replaying APDUs
int CmdHFEPAPACEReplay(const char *Cmd)
{
	// the 4 APDUs which are replayed + their lengths
	uint8_t msesa_apdu[41], gn_apdu[8], map_apdu[75];
	uint8_t pka_apdu[75], ma_apdu[18], apdu_lengths[5] = {0};
	// pointers to the arrays to be able to iterate
	uint8_t *apdus[] = {msesa_apdu, gn_apdu, map_apdu, pka_apdu, ma_apdu};

	// usage message
	static const char const *usage_msg =
		"Please specify 5 APDUs separated by spaces. "
		"Example:\n preplay 0022C1A4 1068000000 1086000002 1234ABCDEF 1A2B3C4D";

	// Proxmark response
	UsbCommand resp;

	int skip = 0, skip_add = 0, scan_return = 0;
	// for each APDU
	for (int i = 0; i < sizeof(apdu_lengths); i++) {
		// scan to next space or end of string
		while (Cmd[skip] != ' ' && Cmd[skip] != '\0') {
			// convert
			scan_return = sscanf(Cmd + skip, "%2X%n",
			                     (unsigned int *) (apdus[i] + apdu_lengths[i]),
			                     &skip_add);
			if (scan_return < 1) {
				PrintAndLog((char *)usage_msg);
				PrintAndLog("Not enough APDUs! Try again!");
				return 0;
			}
			skip += skip_add;
            apdu_lengths[i]++;
		}

		// break on EOF
		if (Cmd[skip] == '\0') {
			if (i < sizeof(apdu_lengths) - 1) {

				PrintAndLog((char *)usage_msg);
				return 0;
			}
			break;
		}
		// skip the space
		skip++;
	}

	// transfer the APDUs to the Proxmark
	UsbCommand usb_cmd;
	usb_cmd.cmd = CMD_EPA_PACE_REPLAY;
	for (int i = 0; i < sizeof(apdu_lengths); i++) {
		// APDU number
		usb_cmd.arg[0] = i + 1;
		// transfer the APDU in several parts if necessary
		for (int j = 0; j * sizeof(usb_cmd.d.asBytes) < apdu_lengths[i]; j++) {
			// offset into the APDU
			usb_cmd.arg[1] = j * sizeof(usb_cmd.d.asBytes);
			// amount of data in this packet
			int packet_length = apdu_lengths[i] - (j * sizeof(usb_cmd.d.asBytes));
			if (packet_length > sizeof(usb_cmd.d.asBytes)) {
				packet_length = sizeof(usb_cmd.d.asBytes);
			}
			usb_cmd.arg[2] = packet_length;

			memcpy(usb_cmd.d.asBytes, // + (j * sizeof(usb_cmd.d.asBytes)),
			       apdus[i] + (j * sizeof(usb_cmd.d.asBytes)),
			       packet_length);
			SendCommand(&usb_cmd);
			WaitForResponse(CMD_ACK, &resp);
			if (resp.arg[0] != 0) {
				PrintAndLog("Transfer of APDU #%d Part %d failed!", i, j);
				return 0;
			}
		}
	}

	// now perform the replay
	usb_cmd.arg[0] = 0;
	SendCommand(&usb_cmd);
	WaitForResponse(CMD_ACK, &resp);
	if (resp.arg[0] != 0) {
		PrintAndLog("\nPACE replay failed in step %u!", (uint32_t)resp.arg[0]);
		PrintAndLog("Measured times:");
		PrintAndLog("MSE Set AT: %u us", resp.d.asDwords[0]);
		PrintAndLog("GA Get Nonce: %u us", resp.d.asDwords[1]);
		PrintAndLog("GA Map Nonce: %u us", resp.d.asDwords[2]);
		PrintAndLog("GA Perform Key Agreement: %u us", resp.d.asDwords[3]);
		PrintAndLog("GA Mutual Authenticate: %u us", resp.d.asDwords[4]);
	} else {
		PrintAndLog("PACE replay successfull!");
		PrintAndLog("MSE Set AT: %u us", resp.d.asDwords[0]);
		PrintAndLog("GA Get Nonce: %u us", resp.d.asDwords[1]);
		PrintAndLog("GA Map Nonce: %u us", resp.d.asDwords[2]);
		PrintAndLog("GA Perform Key Agreement: %u us", resp.d.asDwords[3]);
		PrintAndLog("GA Mutual Authenticate: %u us", resp.d.asDwords[4]);
	}


	return 1;
}
int ModemGSM::Dispatch()
{
	int res = 0;
	int level;
	int ind;
	static int state=0;

	EvalNetworkLedStatus();

#ifdef REGISTRATION_DELAYED
	if(FNetworkRegDelayActive && FNetworkRegDelayTS.IsExpired())
	{
		DEBUG_P(PSTR("Network Registration Delay Expired --> Now Registered To Network"LB));                    

		FNetworkRegDelayActive = false;
		FRegisteredToNetwork = true;
	}
#endif
	if(FLastKeepAliveTS.IsExpired())
	{
#if SIMULATION
		if(FPBReady)
		{
			int idx;
			char temp[30];

//			switch(state % 3) //repeat commands
			switch(state)
			{
				case 0:
				{
					DEBUG_P(PSTR("---- Posting Fake SMS"LB));
					WriteSMS("+390000000000", "ON 0000,22", &idx);
					sprintf_P(temp, PSTR("+CMTI: \"SM\",%d"), idx);
					break;
				}
				case 1:
				{
					DEBUG_P(PSTR("---- Posting Fake SMS"LB));
					WriteSMS("+390000000000", "ON 0000,22", &idx);
					sprintf_P(temp, PSTR("+CMTI: \"SM\",%d"), idx);
					break;
				}

				default:
				{
					temp[0] = 0;

					if(!SendKeepAlive())
					{
						FKeepAliveFailedCount++;
						//if the modem is not answering try the hard way ...
						if(FKeepAliveFailedCount > 5)
						{
							//Try to power off the modem
							SendCommand("AT+CPWROFF");
							delay(1000);

							//Signal Error condition
							FError = true;
							return res;
						}
					}
					else
					{
						FError = false;
						FKeepAliveFailedCount = 0;
					}				
				}
			}

			state++;
			if(temp[0])
			{
				FURCQueue.Enqueue(temp);			
				DEBUG_P(PSTR("---- Posted Fake SMS"LB));
			}
		}
		else
#endif
			if(!SendKeepAlive())
			{
				FKeepAliveFailedCount++;
				//if the modem is not answering try the hard way ...
				if(FKeepAliveFailedCount > 5)
				{
					//Try to power off the modem
					SendCommand("AT+CPWROFF");
					delay(1000);

					//Signal Error condition
					FError = true;
					return res;
				}
			}
			else
			{
				FError = false;
				FKeepAliveFailedCount = 0;
			}

		FLastKeepAliveTS.Reset();
	};
	
	int idx;
	//Check for Queued URC or Data from Modem SerialLine
	if((FURCQueue.Count() ? FURCQueue.Dequeue(FRXBuff, sizeof(FRXBuff)) : false) || (Readln(100, false) != TIMEOUT))
	{
		if(sscanf_P(FRXBuff, PSTR("+CMTI: \"%*[^\"]\",%d"), &idx) == 1)
		{                
			DEBUG_P(PSTR("SMS Received at -> %d"LB), idx);

			//Save SMS position in SM Memory, the SMS is stored by the Modem
			FSMSInQueue.Enqueue(idx);
		}
		else if((sscanf_P(FRXBuff,PSTR("+CMGS: %d"), &level) == 1) || (sscanf_P(FRXBuff,PSTR("+CMSS: %d"), &level) == 1))
		{
			DEBUG_P(PSTR("Last Message Sent Successfully"LB));
		}
		else if(sscanf_P(FRXBuff,PSTR("+CIEV: %d,%d"), &ind, &level) == 2)
		{
			if(ind == 2)
			{
				if((level >= 1) && (level <= 5))
				{
					FSignalLevel = level;
					DEBUG_P(PSTR("Signal Strength --> %d"LB), level);                    
				}
				else
				{
					FSignalLevel = UNKNOWN_LEVEL;
					DEBUG_P(PSTR("**BAD Signal Strength --> %d"LB), level);                    
				}
			}
		}
		else if(sscanf_P(FRXBuff,PSTR("+CREG: %d"), &level) == 1)
		{
			if((level == 1) || (level == 5))
			{
#ifdef REGISTRATION_DELAYED
				DEBUG_P(PSTR("Registered to Network Indication --> Starting Delay"LB));                    
				FNetworkRegDelayActive = true;
				//Wait for a while to be sure that SMS will work
				FNetworkRegDelayTS.Reset(); 
#else
				FRegisteredToNetwork = true;
				DEBUGLN_P(PSTR("Registered to Network"LB)); 
#endif
			}
			else
			{
				DEBUG_P(PSTR("NOT Registered to Network"LB));
				FRegisteredToNetwork = false;
#ifdef REGISTRATION_DELAYED
				FNetworkRegDelayActive = false;
#endif
			}
			FLastBlinkTS.Reset();
			EvalNetworkLedStatus();
		}
		else if(strncmp(FRXBuff,"+XDRVI: ", 8) == 0)
		{        
			resetCount++;
			DEBUG_P(PSTR("Module RESET"LB));
			DiscardSerialInput(5000);
			InnerSetup();
		}
		else if(strcmp_P(FRXBuff,PSTR("+PBREADY")) == 0)
		{        
			FPBReady = true;
			for(int i = 0; i < 10; i++)
				if(ClearSMSMemory())
					break;
				else
				{
					delay(1000);
					DEBUG_P(PSTR("Retrying .... "LB));
				}
				
			FLastKeepAliveTS.Reset();
		}
		else
		{
			DEBUG_P(PSTR("** Unhandled -> "));
			DEBUGLN(FRXBuff);
		}    
	}

	//Do not fire SMS retries if the network is not available
	if((FSMSOutQueue.Count() && FRegisteredToNetwork) && !(FSMSResendPending && !FSMSResendTS.IsExpired()))    
	{
		int idx;

		FSMSOutQueue.Peek(&idx);
		
		if(SendSMSAtIndex(idx))
		{
			SMSDequeue(qOut, NULL);
			FSMSResendPending = false;
		}
		else
		{
			//A retry failed ?
			if(FSMSResendPending)
			{
				//some other retry available ?
				if(FSMSRetry)
				{
					FSMSRetry--;
					FSMSResendTS.Reset();
					DEBUG_P(PSTR("Retrying SMS Send. Retry Count --> %d"LB), (int)FSMSRetry);
				}
				else
				{
					//discard SMS
					FSMSResendPending = false;
					FSMSOutQueue.Dequeue(NULL);
					DEBUG_P(PSTR("** Too Many Retries SMS Send Aborted"LB));
				}
			}
			else
			{
				//Start a delay and retry sequence
				FSMSRetry = SMS_RETRY_COUNT;
				FSMSResendPending = true;
				FSMSResendTS.Reset();
				DEBUG_P(PSTR("Retrying SMS Send. Retry Count --> %d"LB), (int)FSMSRetry);
			}		
		}
	}

	return res;
}
Example #15
0
gxSocketError gxsSMTPClient::SMTPRSet()
// Function used to send the SMTP "Reset" command. Returns zero if
// no errors occur.
{
  return SendCommand("RSET", "250");
}
Example #16
0
/* ---------------------------------------------------------------------------
-- Main routine.  Calls SendCommand for single page.
---------------------------------------------------------------------------- */
int main(int argc, char *argv[]) {

	SendCommand("Hi there, I'm a print output\n\r\f");
	return(0);
}
Example #17
0
gxSocketError gxsSMTPClient::SMTPMailFrom(const char *from_email_address)
// Function used to send the SMTP "MAIL FROM" command. Returns zero if 
// no errors occur.
{
  return SendCommand("MAIL FROM:", "250", from_email_address);
}
Example #18
0
int mfEmlSetMem(uint8_t *data, int blockNum, int blocksCount) {
	UsbCommand c = {CMD_MIFARE_EML_MEMSET, {blockNum, blocksCount, 0}};
	memcpy(c.d.asBytes, data, blocksCount * 16); 
	SendCommand(&c);
	return 0;
}
Example #19
0
gxSocketError gxsSMTPClient::SMTPSendMessage(const char *to, 
					     const char *from, 
					     const char *subject, 
					     const char *body)
// Function used to send a formatted message. Returns zero if no errors
// occur.
{
  if(SMTPRSet() != gxSOCKET_NO_ERROR) return socket_error;
  if(SMTPMailFrom(from) != gxSOCKET_NO_ERROR)
    return socket_error;
  if(SMTPRcptTo(to) != gxSOCKET_NO_ERROR)
    return socket_error;
  if(SendCommand("DATA", "354") != gxSOCKET_NO_ERROR) return socket_error;

  // Construct a message header
  char systime[gxsBUF_SIZE];
  GetSMTPTimeStamp(systime);
  unsigned header_len = strlen(from) + strlen(to) + strlen(subject) + \
    strlen(systime);

  header_len += 50; // Allocate space for additional formatting
  char *message_header = new char[header_len+1];
  if(!message_header) return socket_error = gxSOCKET_BUFOVER_ERROR;
  
  // Format the message header
  // 11/17/2007: Fix for LF problem
  // SMTP protocol reported an error condition
  // 451 See http://pobox.com/~djb/docs/smtplf.html
  // http://cr.yp.to/docs/smtplf.html
  sprintf(message_header, "Date: %s\r\nFrom: %s\r\nTo: %s\r\nSubject: %s\r\n",
	  systime, from, to, subject);

  // Send the message header
  if(Send(message_header, (int)strlen(message_header)) < 0) {
    // PC-lint 04/26/2005: Avoid inappropriate de-allocation error,
    // but message_header is not a user defined type so there is no destructor
    // to call for the array members.
    delete[] message_header;
    return socket_error;
  }

  // Send the body of the message
  if(Send(body, (int)strlen(body)) < 0) {
    // PC-lint 04/26/2005: Avoid inappropriate de-allocation error,
    // but message_header is not a user defined type so there is no destructor
    // to call for the array members.
    delete[] message_header;
    return socket_error;
  }
  
  // Send the end of message sequence
  // PC-lint 04/26/2005: Avoid inappropriate de-allocation error,
  // but message_header is not a user defined type so there is no destructor
  // to call for the array members.
  delete[] message_header;

  strcpy(command_buf, "\r\n.\r\n");
  int len = strlen(command_buf);
  if(Send(command_buf, len) < 0) return socket_error;
  
  // Read the server's response
  if(!RecvResponse(reply_buf, gxsBUF_SIZE, "250")) return socket_error;
  return socket_error = gxSOCKET_NO_ERROR;
}
Example #20
0
int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t * resultKey, bool calibrate) 
{
	uint16_t i;
	uint32_t uid;
	UsbCommand resp;

	StateList_t statelists[2];
	struct Crypto1State *p1, *p2, *p3, *p4;
	
	// flush queue
	WaitForResponseTimeout(CMD_ACK,NULL,100);
	
	UsbCommand c = {CMD_MIFARE_NESTED, {blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, calibrate}};
	memcpy(c.d.asBytes, key, 6);
	SendCommand(&c);

	if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) {
		return -1;
	}

	if (resp.arg[0]) {
		return resp.arg[0];  // error during nested
	}
		
			memcpy(&uid, resp.d.asBytes, 4);
	PrintAndLog("uid:%08x trgbl=%d trgkey=%x", uid, (uint16_t)resp.arg[2] & 0xff, (uint16_t)resp.arg[2] >> 8);
			
			for (i = 0; i < 2; i++) {
				statelists[i].blockNo = resp.arg[2] & 0xff;
				statelists[i].keyType = (resp.arg[2] >> 8) & 0xff;
				statelists[i].uid = uid;
				memcpy(&statelists[i].nt,  (void *)(resp.d.asBytes + 4 + i * 8 + 0), 4);
				memcpy(&statelists[i].ks1, (void *)(resp.d.asBytes + 4 + i * 8 + 4), 4);
			}
	
	// calc keys
	
	pthread_t thread_id[2];
		
	// create and run worker threads
	for (i = 0; i < 2; i++) {
		pthread_create(thread_id + i, NULL, nested_worker_thread, &statelists[i]);
	}
	
	// wait for threads to terminate:
	for (i = 0; i < 2; i++) {
		pthread_join(thread_id[i], (void*)&statelists[i].head.slhead);
	}


	// the first 16 Bits of the cryptostate already contain part of our key.
	// Create the intersection of the two lists based on these 16 Bits and
	// roll back the cryptostate
	p1 = p3 = statelists[0].head.slhead; 
	p2 = p4 = statelists[1].head.slhead;
	while (p1 <= statelists[0].tail.sltail && p2 <= statelists[1].tail.sltail) {
		if (Compare16Bits(p1, p2) == 0) {
			struct Crypto1State savestate, *savep = &savestate;
			savestate = *p1;
			while(Compare16Bits(p1, savep) == 0 && p1 <= statelists[0].tail.sltail) {
				*p3 = *p1;
				lfsr_rollback_word(p3, statelists[0].nt ^ statelists[0].uid, 0);
				p3++;
				p1++;
			}
			savestate = *p2;
			while(Compare16Bits(p2, savep) == 0 && p2 <= statelists[1].tail.sltail) {
				*p4 = *p2;
				lfsr_rollback_word(p4, statelists[1].nt ^ statelists[1].uid, 0);
				p4++;
				p2++;
			}
		}
		else {
			while (Compare16Bits(p1, p2) == -1) p1++;
			while (Compare16Bits(p1, p2) == 1) p2++;
		}
	}
	p3->even = 0; p3->odd = 0;
	p4->even = 0; p4->odd = 0;
	statelists[0].len = p3 - statelists[0].head.slhead;
	statelists[1].len = p4 - statelists[1].head.slhead;
	statelists[0].tail.sltail=--p3;
	statelists[1].tail.sltail=--p4;

	// the statelists now contain possible keys. The key we are searching for must be in the
	// intersection of both lists. Create the intersection:
	qsort(statelists[0].head.keyhead, statelists[0].len, sizeof(uint64_t), compar_int);
	qsort(statelists[1].head.keyhead, statelists[1].len, sizeof(uint64_t), compar_int);

	uint64_t *p5, *p6, *p7;
	p5 = p7 = statelists[0].head.keyhead; 
	p6 = statelists[1].head.keyhead;
	while (p5 <= statelists[0].tail.keytail && p6 <= statelists[1].tail.keytail) {
		if (compar_int(p5, p6) == 0) {
			*p7++ = *p5++;
			p6++;
		}
		else {
			while (compar_int(p5, p6) == -1) p5++;
			while (compar_int(p5, p6) == 1) p6++;
		}
	}
	statelists[0].len = p7 - statelists[0].head.keyhead;
	statelists[0].tail.keytail=--p7;

	memset(resultKey, 0, 6);
	// The list may still contain several key candidates. Test each of them with mfCheckKeys
	for (i = 0; i < statelists[0].len; i++) {
		uint8_t keyBlock[6];
		uint64_t key64;
		crypto1_get_lfsr(statelists[0].head.slhead + i, &key64);
		num_to_bytes(key64, 6, keyBlock);
		key64 = 0;
		if (!mfCheckKeys(statelists[0].blockNo, statelists[0].keyType, false, 1, keyBlock, &key64)) {
			num_to_bytes(key64, 6, resultKey);
			break;
		}
	}
	
	free(statelists[0].head.slhead);
	free(statelists[1].head.slhead);
	
	return 0;
}
Example #21
0
//----------------------------------------------------------------------------
// Execute a script file
int
CSTATEngine::RunScript(ScriptProgressMonitor *const monitor)
{
	int ret = ITS_OK;
	iCurrentCommand = 0;
	eStopProcessing = STAT_RUN;
	iDeviceCode = 0;

	// anything smaller can cause problems and doesn't make sense anyway!
	if (iMaxTimeLimit < 1000)
		iMaxTimeLimit = 1000;

	// pointers to our command structures
	CSTATScriptCommand *pSendCommand;
	CSTATScriptCommand *pRecvCommand;

	char lastCommand = NULL;

	receivedData.Empty( );
	
	

	// get a command from the script
	while (pDecoder->GetNextCommand(&pSendCommand) && ret == ITS_OK)
	{
		iCurrentCommand++;

		if (StopProcessing())
		{
			pComms->Send(STAT_RESYNCID);
			ret = E_USERCANCEL;
			break;
		}

		if (lastCommand == STAT_REBOOT)
		{
			ret = ITS_OK;
			break;
		}

		switch(pSendCommand->cCommandID)
		{
			case 'P':
				Message(pSendCommand->Command());
				Sleep(atol(pSendCommand->Command()));
				break;
			case '/':
				Message(pSendCommand->Command());
				break;
			case '#':
				{
					Message(pSendCommand->Command());
					cScreenshotDirectory = pSendCommand->Command();
					if(cScreenshotDirectory.Right(1) != _T("\\"))
						cScreenshotDirectory += _T("\\");
					CreateAllDirectories(cScreenshotDirectory);
				}
				break;
			
			default:
				{

					// send the command and retrieve a response
					int iResyncErrors = 0;
					while ((ret = SendCommand(pSendCommand, &pRecvCommand)) == E_RESYNCCOMMAND)
					{
						Sleep(STAT_RETRYDELAY);
						iResyncErrors++;
						if (iResyncErrors > STAT_MAXERRORS)
						{
							Message("Too many resync errors - stopping");
							ret = E_COMMANDFAILED;
							break;
						}
						
					}

					if (ret == ITS_OK)
					{
						// perform special operations for these commands
						switch(pSendCommand->cCommandID)
						{
							case 'D':
								StoreData(pRecvCommand->Command(), pRecvCommand->Length(), pDeviceInfo);
								AppendCommandToSTATLog("*** DEVICE INFORMATION ***", pRecvCommand->Command(), pRecvCommand->Length());
								break;
							case 'S':
							{
								// convert and save the data returned in the response
								CString image = pSendCommand->Command();
								ret = ConvertAndSaveScreeenshot(image, pRecvCommand->Command(), pRecvCommand->Length());

								// imave verification
								if (ret == ITS_OK)
								{
									if (pImageVerify->IsActive() && pConverter->bWriteToFile)
									{
										ret = pImageVerify->VerifyImage(image);
										if (ret == VERIFICATION_PASS)
											ret = ITS_OK;
									}
								}
								break;
							}
						
							case 'T':
							{
								
								if(dataSocket==NULL)
								{

									// filename has been sent, now send the file itself
									CSTATScriptCommand oSendCommand;
									oSendCommand.cCommandID = pRecvCommand->cCommandID;
									
										// read and send the file contents
									if ((ret = ReadTransferFile(pSendCommand->Command(), &oSendCommand)) == ITS_OK)
									{
										int iResyncErrors = 0;
										while ((ret = SendCommand(&oSendCommand, &pRecvCommand)) == E_RESYNCCOMMAND)
										{
											Sleep(STAT_RETRYDELAY);
											iResyncErrors++;
											if (iResyncErrors > STAT_MAXERRORS)
											{
												Message("Too many resync errors - stopping");
												ret = E_COMMANDFAILED;
												break;
											}
										}
									}
									
								}
								else
								{
									//release the socket
									ret = ReleaseSocket();
									
								}
								

								break;
							}
							case 'R':
							case 'X':
							{	
								if(dataSocket==NULL)
								{
									// save the file contents
									ret = SaveTransferFile(pSendCommand->Command(), pRecvCommand->Command(), pRecvCommand->Length());
								}
								else
								{
									//release the socket
									ret = ReleaseSocket();
								}
								break;
							}
							case 'G':
							{
								// upload the device log file and write to STAT log file
								AppendCommandToSTATLog("*** DEVICE LOG ***", pRecvCommand->Command(), pRecvCommand->Length());
								break;
							}
							case STAT_REFRESH:
							case STAT_END:
							{
								ret = END_SCRIPT;
								break;
							}
							case 'N':
							{
								// Retrieve the TEF shared data
								StoreData(pRecvCommand->Command(), pRecvCommand->Length(), iTEFSharedData);
								AppendCommandToSTATLog("*** RETRIEVE TEF SHARED DATA ***", pRecvCommand->Command(), pRecvCommand->Length());
							}
							break;
							default:
							{
								Sleep(iDelay);
								break;
							}
						}
					}

					if (ret == ITS_OK)
					{
						// Data received from certain of the commands is stored
						// for retreival later.
						switch(pSendCommand->cCommandID)
						{
							case 'W':
							case 'V':
							//execute returns pid
							case 'J':
							//poll returns 0 1
							case '3':
								receivedData += oRecvCommand.Command();
								break;
							default:
								break;
						}
					}
				}
				break;
		}

		lastCommand = pSendCommand->cCommandID;

		if(monitor)
		{
			monitor->OnCompleteCommand( iCurrentCommand );
		}
	}

	pDecoder->Release();

	return ret;
}
Example #22
0
void CSelectedUnits::GiveCommand(Command c, bool fromUser)
{
	GML_RECMUTEX_LOCK(grpsel); // GiveCommand

//	LOG_L(L_DEBUG, "Command given %i", c.id);
	if ((gu->spectating && !gs->godMode) || selectedUnits.empty()) {
		return;
	}

	const int& cmd_id = c.GetID();

	if (fromUser) { // add some statistics
		playerHandler->Player(gu->myPlayerNum)->currentStats.numCommands++;
		if (selectedGroup != -1) {
			playerHandler->Player(gu->myPlayerNum)->currentStats.unitCommands += grouphandlers[gu->myTeam]->groups[selectedGroup]->units.size();
		} else {
			playerHandler->Player(gu->myPlayerNum)->currentStats.unitCommands += selectedUnits.size();
		}
	}

	if (cmd_id == CMD_GROUPCLEAR) {
		for (CUnitSet::iterator ui = selectedUnits.begin(); ui != selectedUnits.end(); ++ui) {
			if ((*ui)->group) {
				(*ui)->SetGroup(0);
				possibleCommandsChanged = true;
			}
		}
		return;
	}
	else if (cmd_id == CMD_GROUPSELECT) {
		SelectGroup((*selectedUnits.begin())->group->id);
		return;
	}
	else if (cmd_id == CMD_GROUPADD) {
		CGroup* group = NULL;
		for (CUnitSet::iterator ui = selectedUnits.begin(); ui != selectedUnits.end(); ++ui) {
			if ((*ui)->group) {
				group = (*ui)->group;
				possibleCommandsChanged = true;
				break;
			}
		}
		if (group) {
			for (CUnitSet::iterator ui = selectedUnits.begin(); ui != selectedUnits.end(); ++ui) {
				if (!(*ui)->group) {
					(*ui)->SetGroup(group);
				}
			}
			SelectGroup(group->id);
		}
		return;
	}
	else if (cmd_id == CMD_TIMEWAIT) {
		waitCommandsAI.AddTimeWait(c);
		return;
	}
	else if (cmd_id == CMD_DEATHWAIT) {
		waitCommandsAI.AddDeathWait(c);
		return;
	}
	else if (cmd_id == CMD_SQUADWAIT) {
		waitCommandsAI.AddSquadWait(c);
		return;
	}
	else if (cmd_id == CMD_GATHERWAIT) {
		waitCommandsAI.AddGatherWait(c);
		return;
	}

	SendCommand(c);

	#if (PLAY_SOUNDS == 1)
	if (!selectedUnits.empty()) {
		CUnitSet::const_iterator ui = selectedUnits.begin();

		const int soundIdx = (*ui)->unitDef->sounds.ok.getRandomIdx();
		if (soundIdx >= 0) {
			Channels::UnitReply.PlaySample(
				(*ui)->unitDef->sounds.ok.getID(soundIdx), (*ui),
				(*ui)->unitDef->sounds.ok.getVolume(soundIdx));
		}
	}
	#endif
}
int HostProcess(pid_t listenerID, FILE* fout, FILE* fin)
{
  CommandFeedBackThreadInfo cfbInfo;
  cfbInfo.m_fin=fin;
  pthread_t CommandFeedBackThread;
  int threadError = pthread_create(&CommandFeedBackThread,NULL,HostProcess_CommandFeedBackThread,&cfbInfo);

  pthread_t KeyBoardInputThread;
  pthread_mutex_t cmd_lock;
  pthread_mutex_init(&cmd_lock,NULL);  

  sem_init(&cfbInfo.m_CDStatusSocket.m_finish_sem,0,1);  
  sem_init(&cfbInfo.m_CDStatusSocket.m_start_sem,0,0);  

  sem_init(&cfbInfo.m_CDListSocket.m_finish_sem,0,0);  
  sem_init(&cfbInfo.m_CDListSocket.m_start_sem,0,0);  

  sem_init(&cfbInfo.m_ListStatusSocket.m_finish_sem,0,1);  
  sem_init(&cfbInfo.m_ListStatusSocket.m_start_sem,0,0); 

  sem_init(&cfbInfo.m_ListListsSocket.m_finish_sem,0,0);  
  sem_init(&cfbInfo.m_ListListsSocket.m_start_sem,0,0);  

  sem_init(&cfbInfo.m_ListSongsSocket.m_finish_sem,0,0);  
  sem_init(&cfbInfo.m_ListSongsSocket.m_start_sem,0,0);  
  
  FeiSocketSever server(PORT);
  if (!server.IsValid())
  {
    SendCommand("Quit",fout, cmd_lock);
    return -1;
  }

  while (1)
  {
    FeiSocketSession se=server.GetSession();
    if (se.IsValid())
    {
      char buffer[4096];
      char command[256];
      int len;
      len=se.Recieve(buffer,4096);
      if (len<=0) 
      {
        se.Close();
        break;
      }
      buffer[len]=0;
      char *pos;
      if ((pos=strchr(buffer, '\n')) != NULL)
        *pos = '\0';
      if (-1==sscanf(buffer,"%s",command)) continue;
      string s_command=command;
      
      if (s_command=="Shutdown" || s_command=="Reboot")
      {
        SendCommand("Quit",fout, cmd_lock);
        if (s_command=="Shutdown")
        {
          PlaySound("shutdown.mp3");
          system("sudo halt -p");
          return 0;
        }
        else if (s_command=="Reboot")
        {
          PlaySound("reboot.mp3");
          system("sudo reboot");
          return 0;
        }
      }
      else if (s_command=="ResetCDWatch")
      {
        if (cfbInfo.m_CDStatusSocket.m_se.IsValid())
        {
          se.Send("playing\n",8);
          cfbInfo.m_CDStatusSocket.m_resetSocket=true;
		  		SendCommand("CurTrack",fout, cmd_lock);
          sem_wait(&cfbInfo.m_CDStatusSocket.m_finish_sem);
          cfbInfo.m_CDStatusSocket.m_se=se;
          sem_post(&cfbInfo.m_CDStatusSocket.m_start_sem);
        }
        else
        {
          se.Send("notplaying\n",11);
        }
      }      
	  	else if (s_command=="ResetListWatch")
      {
        if (cfbInfo.m_ListStatusSocket.m_se.IsValid())
        {
          se.Send("playing\n",8);
          cfbInfo.m_ListStatusSocket.m_resetSocket=true;
		  		SendCommand("CurSong",fout, cmd_lock);
          sem_wait(&cfbInfo.m_ListStatusSocket.m_finish_sem);
          cfbInfo.m_ListStatusSocket.m_se=se;
          sem_post(&cfbInfo.m_ListStatusSocket.m_start_sem);
        }
        else
        {
          se.Send("notplaying\n",11);
        }
      }      
      else 
      {
        SendCommand(buffer,fout, cmd_lock);
        if (s_command=="PlayCD")
        {
          sem_wait(&cfbInfo.m_CDStatusSocket.m_finish_sem);
          cfbInfo.m_CDStatusSocket.m_resetSocket=false;
          cfbInfo.m_CDStatusSocket.m_se=se;
          sem_post(&cfbInfo.m_CDStatusSocket.m_start_sem);
        }
        else if (s_command=="ListCD")
        {
          cfbInfo.m_CDListSocket.m_se=se;
          sem_post(&cfbInfo.m_CDListSocket.m_start_sem);
          sem_wait(&cfbInfo.m_CDListSocket.m_finish_sem);
        } 
				else if (s_command=="PlayList")
        {
          sem_wait(&cfbInfo.m_ListStatusSocket.m_finish_sem);
          cfbInfo.m_ListStatusSocket.m_resetSocket=false;
          cfbInfo.m_ListStatusSocket.m_se=se;
          sem_post(&cfbInfo.m_ListStatusSocket.m_start_sem);
        }
				else if (s_command=="ListLists")
        {
          cfbInfo.m_ListListsSocket.m_se=se;
          sem_post(&cfbInfo.m_ListListsSocket.m_start_sem);
          sem_wait(&cfbInfo.m_ListListsSocket.m_finish_sem);
        } 
				else if (s_command=="ListSongs")
        {
          cfbInfo.m_ListSongsSocket.m_se=se;
          sem_post(&cfbInfo.m_ListSongsSocket.m_start_sem);
          sem_wait(&cfbInfo.m_ListSongsSocket.m_finish_sem);
        } 
       
      }
    }
  }
  pthread_mutex_destroy(&cmd_lock);  

  sem_destroy(&cfbInfo.m_CDStatusSocket.m_finish_sem);
  sem_destroy(&cfbInfo.m_CDStatusSocket.m_start_sem);

  sem_destroy(&cfbInfo.m_CDListSocket.m_finish_sem);
  sem_destroy(&cfbInfo.m_CDListSocket.m_start_sem);

  sem_destroy(&cfbInfo.m_ListStatusSocket.m_finish_sem);
  sem_destroy(&cfbInfo.m_ListStatusSocket.m_start_sem);

  sem_destroy(&cfbInfo.m_ListListsSocket.m_finish_sem);
  sem_destroy(&cfbInfo.m_ListListsSocket.m_start_sem);

  sem_destroy(&cfbInfo.m_ListSongsSocket.m_finish_sem);
  sem_destroy(&cfbInfo.m_ListSongsSocket.m_start_sem);
  
  return 0;
}
Example #24
0
int main(void) 
{
	// ipmask -- mask of CB/RB instruction pointer
	// regmask -- mask of CB/RB register (specified by third argument)
	// 0 - eax, 1 - ecx, 2 - edx, 3 - ebx, 4 - esp, 5 - ebp, 6 - esi, 7 - edi
   	
	// Negotiate type2 -- populate t2vals
	unsigned char *read_data = NULL;
	unsigned int read_len = 0;
	int read_res;	
	int i;

	unsigned char same_line_delimiter[] = ": ";
	unsigned char new_line_delimiter[] = "\n";

	unsigned int type2_addr;
	unsigned int type2_size;
	unsigned int type2_length;

	NegotiateType2Pov( &type2_addr, &type2_size, &type2_length );

	// Read command count
	read_res = delimited_read( 0, &read_data, &read_len, same_line_delimiter, 2 );
	SendCommand( "3\n" );

	// Read source ID
	read_res = delimited_read( 0, &read_data, &read_len, same_line_delimiter, 2 );
	SendCommand( "0\n" );

	// Read Dest ID
	read_res = delimited_read( 0, &read_data, &read_len, same_line_delimiter, 2 );
	SendCommand( "19\n" );

	// Read 13 lines
	for ( i = 0; i < 13; i++ )
		read_res = delimited_read( 0, &read_data, &read_len, new_line_delimiter, 1 );

	SendCommand( "7\n" );

	// Read 2 lines
	for ( i = 0; i < 2; i++ )
		read_res = delimited_read( 0, &read_data, &read_len, new_line_delimiter, 1 );

	SendCommand( "25\n" );
	// Now send TCM enable command
	
	// Get source ID	
	read_res = delimited_read( 0, &read_data, &read_len, same_line_delimiter, 2 );
	SendCommand( "0\n" );

	// Get Dest ID
	read_res = delimited_read( 0, &read_data, &read_len, same_line_delimiter, 2 );
	SendCommand( "20\n" );

	// Read 13 lines
	for ( i = 0; i < 13; i++ )
		read_res = delimited_read( 0, &read_data, &read_len, new_line_delimiter, 1 );
	
	SendCommand( "11\n" );

	// Read 2 lines
	for ( i = 0; i < 2; i++ )
		read_res = delimited_read( 0, &read_data, &read_len, new_line_delimiter, 1 );

	// 125 milliseconds
	SendCommand( "125\n" );	
	
	// Read send binary message
	read_res = delimited_read( 0, &read_data, &read_len, same_line_delimiter, 2 );

	// Send TCM start command	
	SendCommand( "03010001\n" );
	
	// Read Enter Source ID
	read_res = delimited_read( 0, &read_data, &read_len, same_line_delimiter, 2 );
	SendCommand( "0\n" );

	// Read Dest ID
	read_res = delimited_read( 0, &read_data, &read_len, same_line_delimiter, 2 );
	SendCommand( "20\n" );

	// Read 13 lines
	for ( i = 0; i < 13; i++ )
		read_res = delimited_read( 0, &read_data, &read_len, new_line_delimiter, 1 );
	
	SendCommand( "11\n" );

	// Read 2 lines
	for ( i = 0; i < 2; i++ )
		read_res = delimited_read( 0, &read_data, &read_len, new_line_delimiter, 1 );

	SendCommand( "225\n" );

	// Read enter binary message
	read_res = delimited_read( 0, &read_data, &read_len, same_line_delimiter, 2 );

	// Send cgc_read wheel speed command -- exceed the length and cgc_read the equipment ID -- it should leak 64-bits or 8-bytes of data
	SendCommand( "010600010406070809\n" );

	// Consume 13 lines...	
	for ( i = 0; i < 13; i++ )
		read_res = delimited_read( 0, &read_data, &read_len, new_line_delimiter, 1 );

	read_res = delimited_read( 0, &read_data, &read_len, new_line_delimiter, 1 );

	const char *szExpectLine = "[MESSAGE][SRC=20][DEST=0][LENGTH=13]\n";

	if ( read_len != cgc_strlen(szExpectLine) )
	{
		char *szBlah = "0000";
		SendBytes( 3, (char *)szBlah, 4 );
		_terminate(-1);
	}

	if ( memcmp( read_data, szExpectLine, read_len ) != 0 )
		_terminate(-1);

	// Next line has equipment ID -- which is type 2 memory leak
	read_res = delimited_read( 0, &read_data, &read_len, new_line_delimiter, 1 );

	if ( read_len < 26 )
		_terminate(-1);
	else
	{
		// Convert
		uint8_t pov2_data[8];

		size_t pos_source = 10;
		size_t count = 0;
		size_t out_pos = 0;

		for ( count = 0; count < 8; count++ )
		{
			pov2_data[out_pos] = 0;

			if ( !IsHexChar( read_data[pos_source] ) )
				_terminate(-1);

			pov2_data[out_pos] = (HexCharToInt( read_data[pos_source] ) << 4);

			pos_source++;

			if ( !IsHexChar( read_data[pos_source] ) )
				_terminate(-1);

			pov2_data[out_pos] |= (HexCharToInt( read_data[pos_source] ));

			out_pos++;
			pos_source++;
		}

		SendBytes( 3, (char *)pov2_data, 4 );
	}
}
Example #25
0
//--------------------------------------------------------
// タイマー処理
void CCradio::Timer(int tx, int interval)
{
	if( m_CreateON == TRUE ){
		if( m_PSKGNRId ) return;
		if( m_pRadio != NULL ){
			if( m_pRadio->GetStatus() & mmrpstatusDEFCMD ){
				LPCSTR p;
				switch(m_pRadio->GetDefCommand()){
                    case 1:
						p = RADIO.CmdTx.c_str();
                        break;
                    case 2:
						p = RADIO.CmdRx.c_str();
                        break;
					default:
						p = RADIO.CmdInit.c_str();
                        break;
                }
				SendCommand(p);
				m_PollCnt = (5 + RADIO.PollInterval);
            }
        }
		if( (!tx) && RADIO.PollType ){
			if( !m_PollCnt ){
				if( m_pRadio != NULL ) m_pRadio->Polling();
				if( m_ScanAddr ){		// アドレススキャン
					m_PollCnt = 4;
					if( m_ScanAddr <= 3 ){
						m_ScanAddr++;
					}
					else {
						RADIO.Cmdxx++;
						if( RADIO.Cmdxx >= 0x80 ){
							RADIO.Cmdxx = 0;
						}
					}
				}
				else {
					m_PollCnt = (5 + RADIO.PollInterval);
				}
				if( interval ){
					m_PollCnt = m_PollCnt * 100 / interval;
				}
				switch(RADIO.PollType){
					case RADIO_POLLYAESUHF:
					case RADIO_POLLFT1000D:
					case RADIO_POLLFT920:
						m_rxcnt = 0;
						SendCommand("\\$0000000210");
						break;
					case RADIO_POLLYAESUVU:
						m_rxcnt = 0;
						SendCommand("\\$0000000003");
						break;

                    //1.66B AA6YQ
                    case RADIO_POLLFT9000:
                    case RADIO_POLLFT2000:
                    case RADIO_POLLFT950:
 					case RADIO_POLLFT450:
						m_rxcnt = 0;
						SendCommand("IF;");
						break;

					case RADIO_POLLICOM:
					case RADIO_POLLOMNIVI:
						m_rxcnt = 0;
						SendCommand("\\$FEFExxE003FD");
						break;
					case RADIO_POLLICOMN:
					case RADIO_POLLOMNIVIN:
						if( !m_Freq[0] || m_ScanAddr ){
							m_rxcnt = 0;
							SendCommand("\\$FEFExxE003FD");
						}
						break;
					case RADIO_POLLKENWOOD:
						m_rxcnt = 0;
						SendCommand("IF;");
						break;
					case RADIO_POLLKENWOODN:
						if( !m_Freq[0] ){
							m_rxcnt = 0;
							SendCommand("AI1;");
						}
						break;
					case RADIO_POLLJST245:
						m_rxcnt = 0;
						SendCommand("I\r\n");
						break;
					case RADIO_POLLJST245N:
						if( !m_Freq[0] ){
							m_rxcnt = 0;
							SendCommand("I1\r\nL\r\n");
						}
						break;
					default:
						break;
				}
			}
			m_PollCnt--;
		}
	}
}
Example #26
0
gxSocketError gxsSMTPClient::ESMTPLogin(const char *client_name) 
// Login for ESMTP mail servers if roaming. Returns zero if 
// no errors occur.
{
  return SendCommand("EHLO", "250", client_name);
}
Example #27
0
uint32 CScreenProfile::OnCommand(uint32 dwCommand, uint32 dwParam1, uint32 dwParam2)
{
	switch (dwCommand)
	{
	case CMD_OK:
		{
			m_pDlg->Show(LTFALSE);
			SetCapture(LTNULL);
			HandleDlgCommand(nCommand,(uint16)dwParam1);
			SetSelection(1);
		}
		break;
	case CMD_CANCEL:
		{
			m_pDlg->Show(LTFALSE);
			SetCapture(LTNULL);
			SetSelection(1);
		}
		break;

	case CMD_LOAD:
		{
			m_pDlg->Show(LTTRUE);
			SetCapture(m_pDlg);
			nCommand = dwCommand;
		}
		break;
	case CMD_CONFIRM:
		{
			uint16 nIndex = (uint16)dwParam1;
			if (dwParam2 == CMD_DELETE)
			{
				if (nIndex < m_pListCtrl->GetNumControls()) 
				{
					StringSet::iterator iter = m_ProfileList.begin();
					for (int i = 0; i < nIndex && iter != m_ProfileList.end(); ++i, ++iter);

					if (iter != m_ProfileList.end())
					{
						std::string profile = *iter;
						g_pProfileMgr->DeleteProfile(profile);

					}
					m_pProfile = g_pProfileMgr->GetCurrentProfile();
					SAFE_STRCPY(m_szProfile, m_pProfile->m_sName.c_str());
					UpdateProfileName();

				}
			}
			else if (dwParam2 == CMD_LOAD)
			{
				if (nIndex < m_pListCtrl->GetNumControls()) 
				{
					StringSet::iterator iter = m_ProfileList.begin();
					for (int i = 0; i < nIndex && iter != m_ProfileList.end(); ++i, ++iter);

					if (iter != m_ProfileList.end())
					{
						std::string profile = *iter;
						g_pProfileMgr->NewProfile(profile);
						m_pProfile = g_pProfileMgr->GetCurrentProfile();

						SAFE_STRCPY(m_szProfile, profile.c_str());
						UpdateProfileName();
					}
				}
			}
			else if (dwParam2 == CMD_CREATE)
			{
				SAFE_STRCPY(m_szOldProfile,m_szProfile);
				bCreate = LTTRUE;

				//show edit box here	
				MBCreate mb;
				mb.eType = LTMB_EDIT;
				mb.pFn = EditCallBack;
				mb.pString = m_szProfile;
				mb.nMaxChars = MAX_PROFILE_NAME;
				mb.eInput = CLTGUIEditCtrl::kInputFileFriendly;
				g_pInterfaceMgr->ShowMessageBox(IDS_ENTER_PROFILE_NAME,&mb);
			}
		}
		break;
	case CMD_DELETE:
		{
			m_pDlg->Show(LTTRUE);
			SetCapture(m_pDlg);
			nCommand = dwCommand;
		}
		break;
	case CMD_CREATE:
		{
			if (g_pLTClient->IsConnected())
			{
				MBCreate mb;
				mb.eType = LTMB_YESNO;
				mb.pFn = CreateCallBack,
				g_pInterfaceMgr->ShowMessageBox(IDS_CONFIRM_NEWPROFILE,&mb);
			}
			else
				SendCommand(CMD_CONFIRM,0,CMD_CREATE);
		}
		break;
	case CMD_RENAME:
		{
			m_pDlg->Show(LTTRUE);
			SetCapture(m_pDlg);
			nCommand = dwCommand;
		}
		break;
	case CMD_EDIT:
		{
			SAFE_STRCPY(m_szProfile,(char *)dwParam1);
			std::string profileName = m_szProfile;
			StringSet::iterator iter = m_ProfileList.find(profileName);

			if (iter != m_ProfileList.end())
			{
				//don't proceed renaming or creating a new one if we already have a profile of that
				//name
				MBCreate mb;
				mb.eType = LTMB_OK;
				mb.pFn = NULL,
				g_pInterfaceMgr->ShowMessageBox(IDS_PROFILE_ALREADY_EXISTS,&mb);
			}
			else
			{
				if (bCreate)
				{
					g_pProfileMgr->NewProfile(profileName);
				}
				else
				{
					g_pProfileMgr->RenameProfile(szOldFN,profileName);
				}
				m_pProfile = g_pProfileMgr->GetCurrentProfile();
				SAFE_STRCPY(m_szProfile,m_pProfile->m_sName.c_str());
				UpdateProfileName();
			}
		}
		break;
	default:
		return CBaseScreen::OnCommand(dwCommand,dwParam1,dwParam2);
	}

	return 1;
};
Example #28
0
gxSocketError gxsSMTPClient::SMTPLogout()
// Function used to send the SMTP "QUIT" command. Returns zero if
// no errors occur.
{
  return SendCommand("QUIT", "221");
}
void HMC6352Class::Wake()
{
  SendCommand(HMC6352WakeAddress);
}
Example #30
0
BOOL Skype::SetMoodText(const wstring& mood) {
  current_mood = mood;
  wstring command = L"SET PROFILE RICH_MOOD_TEXT " + mood;
  return SendCommand(command);
}