void RunScript()
{
    char pstrCommand[MAX_COMMAD_SIZE];
    char pstrStringParam[MAX_PARAM_SIZE];

    for (g_iCurrScriptLine=0; g_iCurrScriptLine < g_iScriptSize; g_iCurrScriptLine++)
    {
        g_iCurrentLineChar = 0;

        GetCommand(pstrCommand);

        if (strcmp(pstrCommand, COMMAND_PRINTSTRING) == 0)
        {
            GetStringParam(pstrStringParam);
            printf("\t%s\n", pstrStringParam);
        }

        else if (strcmp(pstrCommand, COMMAND_PRINTSTRINGLOOP) == 0)
        {
            GetStringParam(pstrStringParam);
            int iLoopCount = GetIntParam();

            for (int i=0; i < iLoopCount; i++)
                printf("\t%d: %s\n", i, pstrStringParam);
        }

        else if (strcmp(pstrCommand, COMMAND_NEWLINE) == 0)
        {
            printf("\n");
        }

        else 
        {
            printf("\tError: Invalid Command.\n");
            break;
        }
    }
}
Exemplo n.º 2
0
bool CRegisteredCommands::AddCommand(CLuaMain* pLuaMain, const char* szKey, const CLuaFunctionRef& iLuaFunction, bool bRestricted, bool bCaseSensitive)
{
    assert(pLuaMain);
    assert(szKey);

    // Check if we already have this key and handler
    SCommand* pCommand = GetCommand(szKey, pLuaMain);

    if (pCommand && iLuaFunction == pCommand->iLuaFunction)
        return false;

    // Create the entry
    pCommand = new SCommand;
    pCommand->pLuaMain = pLuaMain;
    pCommand->strKey.AssignLeft(szKey, MAX_REGISTERED_COMMAND_LENGTH);
    pCommand->iLuaFunction = iLuaFunction;
    pCommand->bRestricted = bRestricted;
    pCommand->bCaseSensitive = bCaseSensitive;

    // Add it to our list
    m_Commands.push_back(pCommand);

    return true;
}
Exemplo n.º 3
0
BOOL Cx179App::InitInstance()
{
	CWinApp::InitInstance();
	
	CString cmd = GetCommand();

	OutputDebugStringA(cmd);

	//cmd = L"xxx caihong 123456 room 100001";

	if(cmd.Find("caihong") >= 0)
	{
		ProcessCaihongCmd(cmd);
		return TRUE;
	}

	if(cmd.Find("://") > 0)
	{
		ProcessWebCmd(cmd);
		return TRUE;
	}
		
	return TRUE;
}
Exemplo n.º 4
0
int
GetMailcapEntry(FILE *fp)
/* Parse a mailcap entry
 *   On entry-
 *     fp=mailcap file being read
 *   If a valid mailcap entry is found then on exit-
 *     GetMailcapEntry=1
 *     mc holds the decoded entry
 *   Else on exit-
 *     GetMailcapEntry=0
 *     The content of mc is undefined
 ***/
{ int rawentryalloc = 2000, len;
  char *rawentry, *s, *t, *LineBuf;

  LineBuf = malloc(LINE_BUF_SIZE);
  if (!LineBuf) ExitWithError(nomem);
  rawentry = malloc(1 + rawentryalloc);
  if (!rawentry) ExitWithError(nomem);
  *rawentry = 0;
  while (fgets(LineBuf, LINE_BUF_SIZE, fp)) {
    if (LineBuf[0] == '#') continue;
    len = strlen(LineBuf);
    if (len == 0) continue;
    if (LineBuf[len-1] == '\n') LineBuf[--len] = 0;
    if ((len + strlen(rawentry)) > rawentryalloc) {
      rawentryalloc += 2000;
      rawentry = realloc(rawentry, rawentryalloc+1);
      if (!rawentry) ExitWithError(nomem);
    }
    if (LineBuf[len-1] == '\\') {
      LineBuf[len-1] = 0;
      strcat(rawentry, LineBuf);
    } else {
      strcat(rawentry, LineBuf);
      break;
    }
  }
  free(LineBuf);
  for (s=rawentry; *s && isspace((unsigned char) *s); ++s) ;
  if (!*s) { /* totally blank entry -- quietly ignore */
    free(rawentry);
    return(0);
  }
  s = index(rawentry, ';');
  if (!s) { /* ignore invalid entries unless debugging */
    if (DoDebug)
      fprintf(stderr, "Invalid mailcap entry: %s\n", rawentry);
    free(rawentry);
    return(0);
  }
  *s++ = 0;	/* Terminate the content type and point to the remainder */

  mc.needsterminal = 0;
  mc.copiousoutput = 0;
  mc.testcommand = NULL;
  mc.label = NULL;
  mc.printcommand = NULL;

  StripTrailingSpace(rawentry);
  mc.contenttype = malloc(1+strlen(rawentry));
  if (!mc.contenttype) ExitWithError(nomem);
  strcpy(mc.contenttype, rawentry);

  t = GetCommand(s, &mc.command);
  if (!t) { /* There are no parameters */
    free(rawentry);
    return(1);
  }
  s = t;
  while (s) {
    char *arg, *eq;

    t = GetCommand(s, &arg);
    eq = index(arg, '=');
    if (eq) *eq++ = 0;
    if (*arg) {
      arg = Cleanse(arg);
      if (!strcmp(arg, "needsterminal")) {
	mc.needsterminal = 1;
      } else if (!strcmp(arg, "copiousoutput")) {
	mc.copiousoutput = 1;
      } else if (eq && !strcmp(arg, "test")) {
	mc.testcommand = eq;
      } else if (eq && !strcmp(arg, "description")) {
	mc.label = eq;
      } else if (eq && !strcmp(arg, "label")) { 
	mc.label = eq; /* bogus old name for description */
      } else if (eq && !strcmp(arg, "print")) {
	mc.printcommand = eq;
      } else if (eq && !strcmp(arg, "textualnewlines")) {
	/* ExceptionalNewline(mc.contenttype, atoi(eq)); */
      } else if (strcmp(arg, "notes")) { /* IGNORE notes field */
      } else if (*arg && DoDebug) {
        fprintf(stderr, "ignoring mailcap flag: %s\n", arg);
      }
    }
    s = t;
  }
  free(rawentry);
  return(1);
}
Exemplo n.º 5
0
void c_main()
{
	int		i;
	bool	autoboot=true;
	char	cmd[128];
	long	timeout;
	int		argc=0;
	char	*argv[MAX_ARGS];
	CMD_TBL	*cptr;
	 
	// initiate status.
	status.terminalSpeed = SERIAL_SPEED;
	status.downloadSpeed = SERIAL_DOWNLOAD_SPEED;

	/* initiate serial and timer */
	// serial and timer init.
	SerialInit(status.terminalSpeed);
         printf("\n\nFFUART has been initiated");

	TimerInit();

	//// printf the required GPL string. //////////////////////////////////////
	printf("\n\n");
	//printf(" "PACKAGE "-" VERSION "\n Copyright 2005 Embedded Group at 211.1010@UESTC\n");
	//printf(" Support:211.1010@UESTC\n");
	printf("\n");

	//MemCpy((char *)KERNEL_DRAM_BASE, (char *)KERNEL_SRAM_BASE, KERNEL_MAX_SIZE);	// kernel image reload

	EthInit();
        //sendtest();

	///// wait 10 seconds before starting autoboot. ///////////////////////////
	printf("Autoboot in progress, press any key to stop ");

	for (i=0; i<3; i++){
		timeout = GetTime()+1;	// 1ÃÊ°£ Delay

		printf(".");
		while (GetTime()<timeout){
			if ((FFLSR & 0x00000001)){	// Serial
				FFRBR;
				autoboot = false;
				break;
			}
		}
		if (autoboot==false) break;
	}


	/* No key was pressed, so proceed booting the kernel. */
	if (autoboot)
	{
		printf("Autoboot started.\n");
		for (cptr=cmdTbl; cptr->cmd; cptr++){
			if (!StrCmp(cptr->cmd, "boot")) break;
		}
		DoBootKernel(cptr, 1, 0);
	}


	/* Key was pressed, so proceed command mode. */
	printf("\nAutoboot aborted\n");
	printf("Type \"help\" to get a list of commands\n");

	// the command loop. endless, of course.
	for(;;) {
		DisplayPrompt("bootloader>");

		// wait an hour to get a command.
		GetCommand(cmd, 128, 3600);
		if (!cmd || !cmd[0]) continue;
		
		argc = GetArgs(cmd, argv);
		for (cptr=cmdTbl; cptr->cmd; cptr++){
			if (!StrCmp(argv[0], cptr->cmd)){
				(cptr->run)(cptr, argc, argv);
				break;
			}
		}
		if (!StrCmp(argv[0], "help") || !StrCmp(argv[0], "?")){
			DoPrintfHelp(argc, argv);
		} else if (!(cptr->cmd)){
			printf("\tUnknown command : %s\n", argv[0]);
		}
	}
} // CMain.
Exemplo n.º 6
0
bool CConsole::HandleInput ( const char* szCommand, CClient* pClient, CClient* pEchoClient )
{
    // Copy it
    char szCommandBuffer [256];
    szCommandBuffer [255] = 0;
    strncpy ( szCommandBuffer, szCommand, 255 );
    stripControlCodes ( szCommandBuffer );

    // Split it into two parts: Key and argument
    char* szKey = strtok ( szCommandBuffer, " " );
    char* szArguments = strtok ( NULL, "\0" );

    // Does the key exist?
    if ( szKey && szKey [0] != 0 )
    {
        CConsoleCommand* pCommand = GetCommand ( szKey );
        if ( pCommand )
        {
            // Can this user use this command?
            if ( m_pACLManager->CanObjectUseRight ( pClient->GetAccount ()->GetName ().c_str (),
                                                    CAccessControlListGroupObject::OBJECT_TYPE_USER,
                                                    szKey,
                                                    CAccessControlListRight::RIGHT_TYPE_COMMAND,
                                                    !pCommand->IsRestricted () ) )
            {
                return (*pCommand)( this, szArguments, pClient, pEchoClient );
            }

            // Not enough access, tell the console
            CLogger::LogPrintf ( "DENIED: Denied '%s' access to command '%s'\n", pClient->GetNick (), szKey );

            // Tell the client
            char szBuffer [128];
            _snprintf ( szBuffer, sizeof(szBuffer), "ACL: Access denied for '%s'", szKey );
            szBuffer[sizeof(szBuffer)-1] = '\0';

            pClient->SendEcho ( szBuffer );
            return false;
        }

        // Let the script handle it
        int iClientType = pClient->GetClientType ();

        switch ( iClientType )
        {
            case CClient::CLIENT_PLAYER:
            {
                // See if any registered command can process it
                CPlayer* pPlayer = static_cast < CPlayer* > ( pClient );
                m_pRegisteredCommands->ProcessCommand ( szKey, szArguments, pClient );

                // HACK: if the client gets destroyed before here, dont continue
                if ( m_pPlayerManager->Exists ( pPlayer ) )
                {
                    // Call the console event
                    CLuaArguments Arguments;
                    Arguments.PushString ( szCommand );
                    pPlayer->CallEvent ( "onConsole", Arguments );
                }
                break;
            }
            case CClient::CLIENT_CONSOLE:
            {
                // See if any registered command can process it
                CConsoleClient* pConsole = static_cast < CConsoleClient* > ( pClient );
                m_pRegisteredCommands->ProcessCommand ( szKey, szArguments, pClient );

                // Call the console event
                CLuaArguments Arguments;
                Arguments.PushString ( szCommand );
                pConsole->CallEvent ( "onConsole", Arguments );
                break;
            }
            default: break;
        }
    }

    // Doesn't exist
    return false;
}
Exemplo n.º 7
0
QString CommandService::GetHelpContextId(const QString& commandId) const
{
  Command::Pointer command = GetCommand(commandId);
  return commandManager->GetHelpContextId(command);
}
Exemplo n.º 8
0
void CGuiHandler::MouseRelease(int x,int y,int button)
{
	if(activeMousePress)
		activeMousePress=false;
	else 
		return;

	if(needShift && !keys[SDLK_LSHIFT]){
		if(showingMetal){
			showingMetal=false;
			groundDrawer->SetExtraTexture(0,0,false);
		}
		inCommand=-1;
		needShift=false;
	}

	int icon=IconAtPos(x,y);

//	(*info) << x << " " << y << " " << mouse->lastx << " " << mouse->lasty << "\n";

	if (button == SDL_BUTTON_RIGHT && icon==-1) { // right click -> default cmd
		inCommand=defaultCmdMemory;//GetDefaultCommand(x,y);
		defaultCmdMemory=0;
	} 

	if(icon>=0 && icon<commands.size()){
		if(showingMetal){
			showingMetal=false;
			groundDrawer->SetExtraTexture(0,0,false);
		}
		switch(commands[icon].type){
			case CMDTYPE_ICON:{
				Command c;
				c.id=commands[icon].id;
				CreateOptions(c,(button==SDL_BUTTON_LEFT?0:1));
				selectedUnits.GiveCommand(c);
				inCommand=-1;
				break;}
			case CMDTYPE_ICON_MODE:{
				int newMode=atoi(commands[icon].params[0].c_str())+1;
				if(newMode>commands[icon].params.size()-2)
					newMode=0;

				char t[10];
				SNPRINTF(t, 10, "%d", newMode);
				commands[icon].params[0]=t;

				Command c;
				c.id=commands[icon].id;
				c.params.push_back(newMode);
				CreateOptions(c,(button==SDL_BUTTON_LEFT?0:1));
				selectedUnits.GiveCommand(c);
				inCommand=-1;
				break;}
			case CMDTYPE_ICON_MAP:
			case CMDTYPE_ICON_AREA:
			case CMDTYPE_ICON_UNIT:
			case CMDTYPE_ICON_UNIT_OR_MAP:
			case CMDTYPE_ICON_FRONT:
			case CMDTYPE_ICON_UNIT_OR_AREA:
			case CMDTYPE_ICON_UNIT_FEATURE_OR_AREA:
				inCommand=icon;
				break;

			case CMDTYPE_ICON_BUILDING:{
				UnitDef* ud=unitDefHandler->GetUnitByID(-commands[icon].id);
				if(ud->extractsMetal>0 && !groundDrawer->drawMetalMap && autoShowMetal){
					groundDrawer->SetMetalTexture(readmap->metalMap->metalMap,readmap->metalMap->extractionMap,readmap->metalMap->metalPal,false);
					showingMetal=true;
				}
				inCommand=icon;
				break;}

			case CMDTYPE_COMBO_BOX:
				{
					inCommand=icon;
					CommandDescription& cd=commands[icon];
					list=new CglList(cd.name.c_str(),MenuSelection);
					for(vector<string>::iterator pi=++cd.params.begin();pi!=cd.params.end();++pi)
						list->AddItem(pi->c_str(),"");
					list->place=atoi(cd.params[0].c_str());
					game->showList=list;
					return;
				}
				inCommand=-1;
				break;
			case CMDTYPE_NEXT:
				{
					++activePage;
					if(activePage>maxPages)
						activePage=0;
				}
				selectedUnits.SetCommandPage(activePage);
				inCommand=-1;
				break;

			case CMDTYPE_PREV:
				{
					--activePage;
					if(activePage<0)
						activePage=maxPages;
				}
				selectedUnits.SetCommandPage(activePage);
				inCommand=-1;
				break;
		}
		return;
	}

	Command c=GetCommand(x,y,button,false);

	if(c.id!=CMD_STOP)	//if cmd_stop is returned it indicates that no good command could be found
	selectedUnits.GiveCommand(c);
	FinishCommand(button);
}
Exemplo n.º 9
0
void MythSystemWindows::Fork(time_t timeout)
{
    QString LOC_ERR = QString("myth_system('%1'): Error: ").arg(GetLogCmd());

    // For use in the child
    char locerr[MAX_BUFLEN];
    strncpy(locerr, (const char *)LOC_ERR.toUtf8().constData(), MAX_BUFLEN);
    locerr[MAX_BUFLEN-1] = '\0';

    VERBOSE(VB_SYSTEM|VB_EXTRA, QString("Launching: %1").arg(GetLogCmd()));

    GetBuffer(0)->setBuffer(0);
    GetBuffer(1)->setBuffer(0);
    GetBuffer(2)->setBuffer(0);

    HANDLE p_stdin[2] = { NULL, NULL };
    HANDLE p_stdout[2] = { NULL, NULL };
    HANDLE p_stderr[2] = { NULL, NULL };

    SECURITY_ATTRIBUTES saAttr; 
    STARTUPINFO si;

    ZeroMemory(&si, sizeof(STARTUPINFO));
    si.cb = sizeof(STARTUPINFO);
        
    // Set the bInheritHandle flag so pipe handles are inherited. 
    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 
    saAttr.bInheritHandle = TRUE; 
    saAttr.lpSecurityDescriptor = NULL; 

    /* set up pipes */
    if( GetSetting("UseStdin") )
    {
        if (!CreatePipe(&p_stdin[0], &p_stdin[1], &saAttr, 0)) 
        {
            VERBOSE(VB_IMPORTANT|VB_SYSTEM,
                            (LOC_ERR + "stdin pipe() failed"));
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
        {
            // Ensure the write handle to the pipe for STDIN is not inherited. 
            if (!SetHandleInformation(p_stdin[1], HANDLE_FLAG_INHERIT, 0))
            {
                VERBOSE(VB_SYSTEM|VB_IMPORTANT,
                            (LOC_ERR + "stdin inheritance error"));
                SetStatus( GENERIC_EXIT_NOT_OK );
            }
            else
            {
                si.hStdInput = p_stdin[0];
                si.dwFlags |= STARTF_USESTDHANDLES;
            }
        }
    }


    if( GetSetting("UseStdout") )
    {
        if (!CreatePipe(&p_stdout[0], &p_stdout[1], &saAttr, 0)) 
        {
            VERBOSE(VB_IMPORTANT|VB_SYSTEM,
                            (LOC_ERR + "stdout pipe() failed"));
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
        {
            // Ensure the read handle to the pipe for STDOUT is not inherited.
            if (!SetHandleInformation(p_stdout[0], HANDLE_FLAG_INHERIT, 0))
            {
                VERBOSE(VB_IMPORTANT|VB_SYSTEM,
                            (LOC_ERR + "stdout inheritance error"));
                SetStatus( GENERIC_EXIT_NOT_OK );
            }
            else
            {
                si.hStdOutput = p_stdout[1];
                si.dwFlags |= STARTF_USESTDHANDLES;
            }
        }
    }

    if( GetSetting("UseStderr") )
    {
        if (!CreatePipe(&p_stderr[0], &p_stderr[1], &saAttr, 0)) 
        {
            VERBOSE(VB_IMPORTANT|VB_SYSTEM,
                            (LOC_ERR + "stderr pipe() failed"));
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
        {
            // Ensure the read handle to the pipe for STDERR is not inherited.
            if (!SetHandleInformation(p_stderr[0], HANDLE_FLAG_INHERIT, 0))
            {
                VERBOSE(VB_IMPORTANT|VB_SYSTEM,
                            (LOC_ERR + "stderr inheritance error"));
                SetStatus( GENERIC_EXIT_NOT_OK );
            }
            else
            {
                si.hStdError = p_stderr[2];
                si.dwFlags |= STARTF_USESTDHANDLES;
            }
        }
    }

    // set up command args
    QString cmd = GetCommand() + " " + GetArgs().join(" ");
    if (GetSetting("UseShell"))
        cmd.prepend("cmd.exe /c ");

    SetCommand( cmd );

    QByteArray cmdUTF8 = GetCommand().toUtf8();
    TCHAR *command = TEXT((char *)cmdUTF8.constData());

    const char *directory = NULL;
    QString dir = GetDirectory();
    if (GetSetting("SetDirectory") && !dir.isEmpty())
        directory = strdup(dir.toUtf8().constData());

    PROCESS_INFORMATION pi;
    ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));

    m_timeout = timeout;
    if( timeout )
        m_timeout += time(NULL);

    bool success = CreateProcess(NULL, 
                    command,       // command line 
                    NULL,          // process security attributes 
                    NULL,          // primary thread security attributes 
                    TRUE,          // handles are inherited 
                    0,             // creation flags 
                    NULL,          // use parent's environment 
                    directory,     // use parent's current directory 
                   &si,            // STARTUPINFO pointer 
                   &pi);           // receives PROCESS_INFORMATION 

    if (!success)
    {
        VERBOSE(VB_IMPORTANT|VB_SYSTEM, (LOC_ERR + "CreateProcess() failed"));
        SetStatus( GENERIC_EXIT_NOT_OK );
    }
    else
    {
        /* parent */
        m_child = pi.hProcess;
        SetStatus( GENERIC_EXIT_RUNNING );

        VERBOSE(VB_SYSTEM|VB_EXTRA,
                QString("Managed child (Handle: %1) has started! "
                        "%2%3 command=%4, timeout=%5")
                    .arg((long long)m_child) 
                    .arg(GetSetting("UseShell") ? "*" : "")
                    .arg(GetSetting("RunInBackground") ? "&" : "")
                    .arg(GetLogCmd()) .arg(timeout));

        /* close unused pipe ends */
        CLOSE(p_stdin[0]);
        CLOSE(p_stdout[1]);
        CLOSE(p_stderr[1]);

        // store the rest
        m_stdpipe[0] = p_stdin[1];
        m_stdpipe[1] = p_stdout[0];
        m_stdpipe[2] = p_stderr[0];

        // clean up the memory use
        if( directory )
            free((void *)directory);
    }

    /* Parent */
    if( GetStatus() != GENERIC_EXIT_RUNNING )
    {
        CLOSE(p_stdin[0]);
        CLOSE(p_stdin[1]);
        CLOSE(p_stdout[0]);
        CLOSE(p_stdout[1]);
        CLOSE(p_stderr[0]);
        CLOSE(p_stderr[1]);
    }
}
Exemplo n.º 10
0
void LanTask (void)
{
   uint16_t plen, dat_p = 0;
   bool send;
   
   while (1)
   {
      plen = Enc28j60PacketReceive(BUFFER_SIZE, buf);
         /*plen will unequal to zero if there is a valid packet (without crc error) */
      if (plen == 0) return;

      // arp is broadcast if unknown but a host may also verify the mac address by sending it to a unicast address.
      if (Eth_type_is_arp_and_my_ip(buf, plen))
      {
         Make_arp_answer_from_request(buf);
         continue;
      }
      // check if the ip packet is for us:
      if (Eth_type_is_ip_and_my_ip(buf, plen) == 0)
      {
         continue;
      }
      // ping
      if((buf[IP_PROTO_P] == IP_PROTO_ICMP_V) && (buf[ICMP_TYPE_P] == ICMP_TYPE_ECHOREQUEST_V))
      {
         Make_echo_reply_from_request(buf, plen);
         continue;
      }

      // tcp port www start, compare only the lower byte
      if ((buf[IP_PROTO_P] == IP_PROTO_TCP_V) && (buf[TCP_DST_PORT_H_P] == 0) && (buf[TCP_DST_PORT_L_P] == mywwwport))
      {
         if (buf[TCP_FLAGS_P] & TCP_FLAGS_SYN_V)
         {
            Make_tcp_synack_from_syn(buf); // make_tcp_synack_from_syn does already send the syn,ack
            continue;
         }
         if (buf[TCP_FLAGS_P] & TCP_FLAGS_ACK_V)
         {
            Init_len_info(buf); // init some data structures
            dat_p = Get_tcp_data_pointer();
            if (dat_p == 0)
            { 
               // we can possibly have no data, just ack:
               if (buf[TCP_FLAGS_P] & TCP_FLAGS_FIN_V)
               {
                  Make_tcp_ack_from_any(buf);
               }
               continue;
            }
         }
         send = false;
         if (strncmp("GET ",(char *) & (buf[dat_p]), 4) != 0)
         {
          	// head, post and other methods for possible status codes see:
            // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
            plen = Fill_tcp_data_p(buf, 0, PSTR("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n<h1>200 OK</h1>"));
            send = true;
         }

	      if (!send)
         {
            char *p;
            p = (char*) &(buf[dat_p+4]);  // start of incomming payload
            switch (GetCommand(p))
            {
               case 0:
                  break;
               case 1:
                  countUp0 = false;
                  break;
			   case 2:
                  countUp0 = true;
                  break;
            }
			
            plen = PrintWebpage(buf);
            send = true;
         }

         Make_tcp_ack_from_any(buf); // send ack for http get
         Make_tcp_ack_with_data(buf, plen); // send data
		 continue;       
      }


		// udp interface:
        if (buf[IP_PROTO_P]==IP_PROTO_UDP_V)
		{
        	uint8_t payloadlen=buf[UDP_LEN_L_P]-UDP_HEADER_LEN;
            // the received command has to start with t and be 4 char long
            // e.g "test\0"
            if(payloadlen)
			{
				char msg1[]="Hello";
				Make_udp_reply_from_request(buf,msg1,sizeof(msg1),MYUDPPORT);
			}
         }// End udp interface.

   }// End while(1)

}// End LanTask
Exemplo n.º 11
0
bool CRegisteredCommands::CommandExists(const char* szKey, CLuaMain* pLuaMain)
{
    assert(szKey);

    return GetCommand(szKey, pLuaMain) != NULL;
}
Exemplo n.º 12
0
bool wxExVCSCommand::IsDiff() const
{
  return 
    GetCommand(false).find("diff") != std::string::npos;
}
Exemplo n.º 13
0
/*--------------------------------------------------------------------------*/
int TCL_EvalScilabCmd(ClientData clientData,Tcl_Interp * theinterp,int objc,CONST char ** argv)
{
  int ierr = 0,seq = 0;
  char *command;

  char *comm[arbitrary_max_queued_callbacks];
  int   seqf[arbitrary_max_queued_callbacks];
  int nc,ncomm=-1;

  if (C2F(iop).ddt==-1)
    {
      /* trace for debugging */
      int argc=1;
      char *msg=_("TCL_EvalScilabCmd %s");

      sciprint_full(msg,argv[1]);

      while (argv[++argc]) sciprint(" %s",argv[argc]);
      sciprint("\n");

     }

  if (argv[1] != (char *)0)
    {
       command = strdup(argv[1]);
      if (command == (char *) 0)
	{
	  sciprint(_("%s: No more memory.\n"),"TCL_EvalScilabCmd");
	  return TCL_ERROR;
	}


      if ( (argv[2] != (char *)0) && (strncmp(argv[2],"sync",4)==0) )
	{
	  /* sync or sync seq
	   * TODO : Scilab is supposed to be busy there. Add mutex lock...
	   * C2F(tksynchro)(&c_n1);
	   * set sciprompt to -1 (scilab busy)
	   */
	  seq= ( (argv[3] != (char *)0) && (strncmp(argv[3],"seq",3)==0) );

	  if (C2F(iop).ddt==-1)
	    {
	      char *msg=_("Execution starts for %s");
	      sciprint_full(msg,command);
	      sciprint("\n");
	    }

	  /*
      int ns=(int)strlen(command);
	  Was : syncexec(command,&ns,&ierr,&seq,ns);
	  So far as Tcl has it's own thread now mixing global values
	  and threads within parse makes Scilab crash often.
	  */
	  StorePrioritaryCommandWithFlag(command, seq);
	  ierr = 0;

	  if (C2F(iop).ddt==-1)
	    {
	      char *msg=_("Execution ends for %s");
	      sciprint_full(msg,command);
	      sciprint("\n");
	    }
	  // TODO : Scilab is supposed to be busy there. Add mutex lock...
	  // C2F(tksynchro)(&C2F(recu).paus);
	  if (ierr != 0) return TCL_ERROR;
	}
      else if (strncmp(command,"flush",5)==0)
	{
	  /* flush */
	  if (C2F(iop).ddt==-1) sciprint(_(" Flushing starts for queued commands.\n"));
	  while (ismenu() && ncomm<arbitrary_max_queued_callbacks-1)
	    {
	      ncomm++;
	      comm[ncomm] = (char *) MALLOC (bsiz+1);
	      if (comm[ncomm] == (char *) 0)
		{
		  sciprint(_("%s: No more memory.\n"),"TCL_EvalScilabCmd");
		  return TCL_ERROR;
		}
	      seqf[ncomm]=GetCommand (comm[ncomm]);
	    }
	  if (ismenu()) sciprint(_("Warning: Too many callbacks in queue!\n"));
	  for (nc = 0 ; nc <= ncomm ; nc++ )
	    {
	      // TODO : Scilab is supposed to be busy there. Add mutex lock...
	      // C2F(tksynchro)(&c_n1);  // set sciprompt to -1 (scilab busy)
	      if (C2F(iop).ddt==-1)
		{
		  if (seqf[nc]==0)
		    {
		      char *msg=_("Flushed execution starts for %s - No option");
		      sciprint_full(msg,comm[nc]);
		      sciprint("\n");
		    }
		  else
		    {
		      char *msg=_("Flushed execution starts for %s - seq");
		      sciprint_full(msg,comm[nc]);
		      sciprint("\n");
		    }
		}
	  /*
	  Was : syncexec(comm[nc],&ns,&ierr,&(seqf[nc]),ns);
	  So far as Tcl has it's own thread now mixing global values
	  and threads within parse makes Scilab crash often.
	  */
	  StorePrioritaryCommandWithFlag(comm[nc], seqf[nc]);
	     if (C2F(iop).ddt==-1)
		{
		  char *msg=_("Flushed execution ends for %s");
		  sciprint_full(msg,comm[nc]);
		  sciprint("\n");
		}
	      FREE(comm[nc]);
	      // TODO : Scilab is supposed to be busy there. Add mutex lock...
	      // C2F(tksynchro)(&C2F(recu).paus);
	      if (ierr != 0) return TCL_ERROR;
	    }
	  if (C2F(iop).ddt==-1) sciprint(_("Flushing ends\n"));
	}
      else
	{
	  if ( (argv[2] != (char *)0) && (strncmp(argv[2],"seq",3)==0) )
	    {
	      /* seq */
	      StoreCommandWithFlag(command, 1);
	    }
	  else
	    {
	      /* no option or unknown option (TODO: no error for this latter case?) */
	      StoreCommand(command);
	      Tcl_SetResult(theinterp,NULL,NULL);
	    }
	}
      FREE(command);

    }
  else
    {
      /* ScilabEval called without argument */
      Scierror(999,_("%s: Wrong number of input argument(s): at least one expected.\n"),"TCL_EvalScilabCmd");
    }

  return TCL_OK;
}
Exemplo n.º 14
0
#include "OperationPathList.h"
#include "InputOutput.h"
#include "Functions.h"

#include <fstream>
#include <iostream>
#include <locale>
#include <codecvt>

ClassFactory<OperationPathList> * OperationPathList::RegisteredFactory =
new ClassFactory<OperationPathList>(GetCommand());

OperationPathList::OperationPathList(std::queue<std::wstring> & oArgList) : Operation(oArgList)
{
	// exit if there are not enough arguments to parse
	std::vector<std::wstring> sSubArgs = ProcessAndCheckArgs(1, oArgList, L"\\0");

	// open the file
	std::wifstream fFile(sSubArgs[0].c_str());

	// adapt the stream to read windows unicode files
	(void) fFile.imbue(std::locale(fFile.getloc(), new std::codecvt_utf8<wchar_t,
		0x10ffff, std::consume_header>));

	// read the file line-by-line
	std::wstring sLine;
	while (std::getline(fFile, sLine))
	{
		// sometimes a carriage return appears in the input stream so adding 
		// it here ensures it is stripped from the very end
		std::vector<std::wstring> oLineItems = SplitArgs(sLine, L"\r");
Exemplo n.º 15
0
void Invoke179App(HANDLE hMutex)
{
	//客户端已经打开
	if(WAIT_OBJECT_0 == ::WaitForSingleObject(hMutex, INFINITE))
	{
		HANDLE hMapFile = ::OpenFileMapping(FILE_MAP_READ, FALSE, _T("Local\\51KTVMainFileMap"));
		if(hMapFile == NULL)
		{
			ReleaseMutex(hMutex);
			CloseHandle(hMutex);
			return;
		}

		ShareMemInfo* pMemInfo = (ShareMemInfo*)MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, sizeof(ShareMemInfo));
		if(pMemInfo == NULL)
		{
			CloseHandle(hMapFile);
			ReleaseMutex(hMutex);
			CloseHandle(hMutex);
			return;
		}

		if(pMemInfo->unVersion == SHARE_MEMORY_INFO_VERSION)
		{
			if(::IsWindowEnabled(pMemInfo->hwndHall))
			{
				if(::IsIconic(pMemInfo->hwndHall))
				{
					::SendMessage(pMemInfo->hwndHall,WM_SYSCOMMAND, SC_RESTORE, 0);
				}
				else
				{
					::SetForegroundWindow(pMemInfo->hwndHall);	
				}
			}
			else if(::IsIconic(pMemInfo->hwndHall))
			{
				::EnableWindow(pMemInfo->hwndHall, TRUE);						
				::SendMessage(pMemInfo->hwndHall, WM_SYSCOMMAND, SC_RESTORE, 0);
				::SendMessage(pMemInfo->hwndLogin, WM_SYSCOMMAND, SC_RESTORE, 0);
				::EnableWindow(pMemInfo->hwndHall, FALSE);
			}

			CString strCommand = GetCommand();			
			if(!strCommand.IsEmpty())
			{
				HGLOBAL hGlobal = ::GlobalAlloc(GMEM_FIXED | GMEM_ZEROINIT, strCommand.GetLength()+1);
				char* pDst = (char*)::GlobalLock(hGlobal);
				strcpy(pDst, strCommand.GetBuffer());
				::GlobalUnlock(hGlobal);
				::OpenClipboard(::GetDesktopWindow());
				::SetClipboardData(RegisterClipboardFormat(WEBPLUGIN_DATA_FORMAT), hGlobal);
				::CloseClipboard();
				::SendMessage(pMemInfo->hwndLogin, WM_WEBPLUGIN_MESSAGE, 0, 0);
				::GlobalFree(hGlobal);
			}
		}

		UnmapViewOfFile(pMemInfo);
		CloseHandle(hMapFile);
		ReleaseMutex(hMutex);
		CloseHandle(hMutex);
	}
}
Exemplo n.º 16
0
#include "OperationWhatIf.h"
#include "InputOutput.h"

ClassFactory<OperationWhatIf> * OperationWhatIf::RegisteredFactory =
new ClassFactory<OperationWhatIf>(GetCommand());

OperationWhatIf::OperationWhatIf(std::queue<std::wstring> & oArgList) : Operation(oArgList)
{
	InputOutput::InWhatIfMode() = true;
}
Exemplo n.º 17
0
/********************************************************************
* Function: 	int main()
*
* Precondition: None.
*
* Input: 		None.
*
* Output:		None.
*
* Side Effects:	Enables 32-bit Timer2/3.  Enables UART.
*
* Overview: 	Initialization of program and main loop.
*			
* Note:		 	None.
********************************************************************/
int main()
{
	DWORD_VAL delay;

	//Setup bootloader entry delay
	sourceAddr.Val = DELAY_TIME_ADDR;	//bootloader timer address
	delay.Val = ReadLatch(sourceAddr.word.HW, sourceAddr.word.LW); //read BL timeout
	
	//Setup user reset vector
	sourceAddr.Val = USER_PROG_RESET;
	userReset.Val = ReadLatch(sourceAddr.word.HW, sourceAddr.word.LW);

	//Prevent bootloader lockout - if no user reset vector, reset to BL start
	if(userReset.Val == 0xFFFFFF){
		userReset.Val = BOOT_ADDR_LOW;	
	}
	userResetRead = 0;


	//If timeout is zero, check reset state.
	if(delay.v[0] == 0){

		//If device is returning from reset, BL is disabled call user code
		//otherwise assume the BL was called from use code and enter BL
		if(RCON & 0xFED3){
			//If bootloader disabled, go to user code
			ResetDevice(userReset.Val); 
		}else{
			delay.Val = 0xFF;
		}
	}


	T2CONbits.TON = 0;
	T2CONbits.T32 = 1; // Setup Timer 2/3 as 32 bit timer incrementing every clock
	IFS0bits.T3IF = 0; // Clear the Timer3 Interrupt Flag 
	IEC0bits.T3IE = 0; // Disable Timer3 Interrupt Service Routine 

	//Enable timer if not in always-BL mode
	if((delay.Val & 0x000000FF) != 0xFF){
		//Convert seconds into timer count value 
		delay.Val = ((DWORD)(FCY)) * ((DWORD)(delay.v[0])); 

		PR3 = delay.word.HW; //setup timer timeout value
		PR2 = delay.word.LW;

		TMR2 = 0;
		TMR3 = 0;
		T2CONbits.TON=1;  //enable timer
	}


	//If using a part with PPS, map the UART I/O
	#ifdef DEV_HAS_PPS
		ioMap();
	#endif

	
	//Configure UART pins to be digital I/O.
	#ifdef UTX_ANA
		UTX_ANA = 1;
	#endif
	#ifdef URX_ANA
		URX_ANA = 1;
	#endif


	// SETUP UART COMMS: No parity, one stop bit, autobaud, polled
	UxMODEbits.UARTEN = 1;		//enable uart
    #ifdef USE_AUTOBAUD
	    UxMODEbits.ABAUD = 1;		//use autobaud
    #else
        UxBRG = BAUDRATEREG;
    #endif
	#ifdef USE_HI_SPEED_BRG
		UxMODEbits.BRGH = 1;	//use high speed mode
	#endif
	UxSTA = 0x0400;  //Enable TX

	while(1){

		#ifdef USE_RUNAWAY_PROTECT
			writeKey1 = 0xFFFF;	// Modify keys to ensure proper program flow
			writeKey2 = 0x5555;
		#endif

		GetCommand();		//Get full AN851 command from UART

		#ifdef USE_RUNAWAY_PROTECT
			writeKey1 += 10;	// Modify keys to ensure proper program flow
			writeKey2 += 42;
		#endif

		HandleCommand();	//Handle the command

		PutResponse(responseBytes);		//Respond to sent command

	}//end while(1)

}//end main(void)
Exemplo n.º 18
0
std::string CInv::ToString() const
{
    return strprintf("%s %s", GetCommand(), hash.ToString());
}
Exemplo n.º 19
0
bool wxExVCSCommand::IsDiff() const
{
  return 
    GetCommand(false).Contains("diff");
}
Exemplo n.º 20
0
Command CGuiHandler::GetOrderPreview(void)
{
	return GetCommand(mouse->lastx,mouse->lasty,-1,true);
}
Exemplo n.º 21
0
bool wxExVCSCommand::IsHelp() const
{
  return 
    GetCommand(false) == "help";
}
Exemplo n.º 22
0
void CModCommand::AddHelp(CTable& Table) const {
    Table.AddRow();
    Table.SetCell("Command", GetCommand());
    Table.SetCell("Arguments", GetArgs());
    Table.SetCell("Description", GetDescription());
}
Exemplo n.º 23
0
bool wxExVCSCommand::IsUpdate() const
{
  return 
    GetCommand(false) == "update" ||
    GetCommand(false) == "up";
}
Exemplo n.º 24
0
void CommandService::RefreshElements(const QString& commandId,
                     const QHash<QString, Object::Pointer>&  filter)
{
  Command::Pointer cmd = GetCommand(commandId);

  if (!cmd->IsDefined() || !(cmd->GetHandler().Cast<IElementUpdater>()))
  {
    return;
  }
  IElementUpdater::Pointer updater = cmd->GetHandler().Cast<IElementUpdater>();

  if (commandCallbacks.isEmpty())
  {
    return;
  }

  if(!commandCallbacks.contains(commandId))
  {
    return;
  }

  foreach (IElementReference::Pointer callbackRef, commandCallbacks[commandId])
  {
    struct _SafeRunnable : public ISafeRunnable
    {
      IElementUpdater* updater;
      IElementReference* callbackRef;

      _SafeRunnable(IElementUpdater* updater, IElementReference* callbackRef)
        : updater(updater), callbackRef(callbackRef)
      {}

      void HandleException(const std::exception& exc)
      {
        WorkbenchPlugin::Log(QString("Failed to update callback: ") +
                             callbackRef->GetCommandId() + exc.what());
      }

      void Run()
      {
        updater->UpdateElement(callbackRef->GetElement().GetPointer(), callbackRef->GetParameters());
      }
    };

    QHash<QString,Object::Pointer> parms = callbackRef->GetParameters();

    ISafeRunnable::Pointer run(new _SafeRunnable(updater.GetPointer(), callbackRef.GetPointer()));
    if (filter.isEmpty())
    {
      SafeRunner::Run(run);
    }
    else
    {
      bool match = true;
      QHashIterator<QString, Object::Pointer> i(filter);
      while (i.hasNext())
      {
        i.next();
        Object::Pointer value = parms[i.key()];
        if (i.value() != value)
        {
          match = false;
          break;
        }
      }
      if (match)
      {
        SafeRunner::Run(run);
      }
    }
  }
}
Exemplo n.º 25
0
bool wxExVCSCommand::IsAdd() const
{
  return 
    GetCommand(false) == "add";
}
Exemplo n.º 26
0
std::string CInv::ToString() const
{
    return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,20).c_str());
}
Exemplo n.º 27
0
bool wxExVCSCommand::IsBlame() const
{
  return 
    GetCommand(false) == "blame" ||
    GetCommand(false) == "print";
}
Exemplo n.º 28
0
bool CMessageHeader::IsValid() const
{
    // Check start string
    if (memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0)
        return false;

    // Check the command string for errors
    for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
    {
        if (*p1 == 0)
        {
            // Must be all zeros after the first zero
            for (; p1 < pchCommand + COMMAND_SIZE; p1++)
                if (*p1 != 0)
                    return false;
        }
        else if (*p1 < ' ' || *p1 > 0x7E)
            return false;
    }

    // Message size
    if (nMessageSize > MAX_SIZE)
    {
        printf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand().c_str(), nMessageSize);
        return false;
    }

    return true;
}
Exemplo n.º 29
0
bool wxExVCSCommand::IsCheckout() const
{
  return 
    GetCommand(false) == "checkout" ||
    GetCommand(false) == "co";
}