Example #1
0
int DdmTestConsole::SetHandle(int _ConnectionID, char *pCommandLine) {

	char *pHandleNum = NULL;
	char *pOption = NULL;	
	int handle;
	int option;

	SplitCommand(pCommandLine, pHandleNum, pOption);
	
	if ((pOption[0] == 0) || (pOption[0] == ' '))
	{
		WriteString(_ConnectionID, "\n\rIncorrect syntax - please see help\n\r\0");				
		return -1;
	}
	
	handle = atoi(pHandleNum);
	option = atoi(pOption);
	
	// Set the output for this terminal
	if (handle < HandleMan->numHandles) {
		HandleMan->pHandle[handle]->SetOutput(_ConnectionID, option);
	}
	else {
		WriteString(_ConnectionID, "\n\rInvalid process number\n\r\0");				
		return -1;
	}

	return 0;

}
Example #2
0
BOOL CRenoCommandFrame::ExecuteCommand(const CString& command)
{
	CStringPtrArray commandElements;

	// Split the command into arguments
	SplitCommand(command,commandElements);

	// Check if null command passed in
	if(!commandElements.GetCount())
		return FALSE;

	// Get our command map
	const RENO_COMMAND* commandMap = GetCommandMap();
	ASSERT(commandMap);

	// Find the command that was called
	for(ULONG i = 0; commandMap[i].name && commandMap[i].function; ++i)
		if(!lstrcmpi(commandMap[i].name,commandElements[0]))
			return (this->*commandMap[i].function)(commandElements);	// TODO Maybe just always return TRUE since the passed in command name was valid

	// Unknown command
	PrintFormat(TEXT("* Unknown command: %s\r\n"),commandElements[0]);

	return FALSE;
}
Example #3
0
bool ExecuteShellAndWait(HINSTANCE Handle, const UnicodeString & Command,
  TProcessMessagesEvent ProcessMessages)
{
  UnicodeString Program, Params, Dir;
  SplitCommand(Command, Program, Params, Dir);
  return ExecuteShellAndWait(Handle, Program, Params, ProcessMessages);
}
Example #4
0
void __fastcall BrowseForExecutableT(T * Control, UnicodeString Title,
  UnicodeString Filter, bool FileNameCommand, bool Escape)
{
  UnicodeString Executable, Program, Params, Dir;
  Executable = Control->Text;
  if (FileNameCommand)
  {
    ReformatFileNameCommand(Executable);
  }
  SplitCommand(Executable, Program, Params, Dir);

  TOpenDialog * FileDialog = new TOpenDialog(Application);
  try
  {
    if (Escape)
    {
      Program = ReplaceStr(Program, L"\\\\", L"\\");
    }
    UnicodeString ExpandedProgram = ExpandEnvironmentVariables(Program);
    FileDialog->FileName = ExpandedProgram;
    UnicodeString InitialDir = ExtractFilePath(ExpandedProgram);
    if (!InitialDir.IsEmpty())
    {
      FileDialog->InitialDir = InitialDir;
    }
    FileDialog->Filter = Filter;
    FileDialog->Title = Title;

    if (FileDialog->Execute())
    {
      TNotifyEvent PrevOnChange = Control->OnChange;
      Control->OnChange = NULL;
      try
      {
        // preserve unexpanded file, if the destination has not changed actually
        if (!CompareFileName(ExpandedProgram, FileDialog->FileName))
        {
          Program = FileDialog->FileName;
          if (Escape)
          {
            Program = ReplaceStr(Program, L"\\", L"\\\\");
          }
        }
        Control->Text = FormatCommand(Program, Params);
      }
      __finally
      {
        Control->OnChange = PrevOnChange;
      }

      if (Control->OnExit != NULL)
      {
        Control->OnExit(Control);
      }
    }
  }
Example #5
0
int DdmTestConsole::RunTest(int _ConnectionID, char *pCommandLine) {

	char *pCommand = NULL;
	char *pArgs = NULL;	
	int handle;

	SplitCommand(pCommandLine, pCommand, pArgs);
	
	// Generate the handle
	handle = HandleMan->AddHandle(pCommandLine, OutputOn);
	// Set the status to output on by default
	HandleMan->pHandle[handle]->SetOutput(_ConnectionID, OutputOn);

	// Run the command!
	TestMsgRun* pTestMsg = new TestMsgRun(pCommand, pArgs, handle);
	Send(pTestMsg, NULL, REPLYCALLBACK(DdmTestConsole, InputStream));
	
	return 0;

}
Example #6
0
//---------------------------------------------------------------------------
void __fastcall OpenSessionInPutty(const UnicodeString PuttyPath,
  TSessionData * SessionData)
{
  UnicodeString Program, AParams, Dir;
  SplitCommand(PuttyPath, Program, AParams, Dir);
  Program = ExpandEnvironmentVariables(Program);
  if (FindFile(Program))
  {

    AParams = ExpandEnvironmentVariables(AParams);
    UnicodeString Password = GUIConfiguration->PuttyPassword ? SessionData->Password : UnicodeString();
    TCustomCommandData Data(SessionData, SessionData->UserName, Password);
    TRemoteCustomCommand RemoteCustomCommand(Data, SessionData->RemoteDirectory);
    TWinInteractiveCustomCommand InteractiveCustomCommand(
      &RemoteCustomCommand, L"PuTTY");

    UnicodeString Params =
      RemoteCustomCommand.Complete(InteractiveCustomCommand.Complete(AParams, false), true);

    if (!RemoteCustomCommand.IsSiteCommand(AParams))
    {
      UnicodeString SessionName;
      TRegistryStorage * Storage = NULL;
      TSessionData * ExportData = NULL;
      TRegistryStorage * SourceStorage = NULL;
      try
      {
        Storage = new TRegistryStorage(Configuration->PuttySessionsKey);
        Storage->AccessMode = smReadWrite;
        // make it compatible with putty
        Storage->MungeStringValues = false;
        Storage->ForceAnsi = true;
        if (Storage->OpenRootKey(true))
        {
          if (Storage->KeyExists(SessionData->StorageKey))
          {
            SessionName = SessionData->SessionName;
          }
          else
          {
            SourceStorage = new TRegistryStorage(Configuration->PuttySessionsKey);
            SourceStorage->MungeStringValues = false;
            SourceStorage->ForceAnsi = true;
            if (SourceStorage->OpenSubKey(StoredSessions->DefaultSettings->Name, false) &&
                Storage->OpenSubKey(GUIConfiguration->PuttySession, true))
            {
              Storage->Copy(SourceStorage);
              Storage->CloseSubKey();
            }

            ExportData = new TSessionData(L"");
            ExportData->Assign(SessionData);
            ExportData->Modified = true;
            ExportData->Name = GUIConfiguration->PuttySession;
            ExportData->Password = L"";

            if (SessionData->FSProtocol == fsFTP)
            {
              if (GUIConfiguration->TelnetForFtpInPutty)
              {
                ExportData->PuttyProtocol = PuttyTelnetProtocol;
                ExportData->PortNumber = TelnetPortNumber;
                // PuTTY  does not allow -pw for telnet
                Password = L"";
              }
              else
              {
                ExportData->PuttyProtocol = PuttySshProtocol;
                ExportData->PortNumber = SshPortNumber;
              }
            }

            ExportData->Save(Storage, true);
            SessionName = GUIConfiguration->PuttySession;
          }
        }
      }
      __finally
      {
        delete Storage;
        delete ExportData;
        delete SourceStorage;
      }

      AddToList(Params, FORMAT(L"-load %s", (EscapePuttyCommandParam(SessionName))), L" ");
    }

    if (!Password.IsEmpty() && !RemoteCustomCommand.IsPasswordCommand(AParams))
    {
      AddToList(Params, FORMAT(L"-pw %s", (EscapePuttyCommandParam(Password))), L" ");
    }

    if (!ExecuteShell(Program, Params))
    {
      throw Exception(FMTLOAD(EXECUTE_APP_ERROR, (Program)));
    }
  }
Example #7
0
int ShellCommandReturnsZero(char *comm,int useshell)

{ int status, i, argc = 0;
  pid_t pid;
  char arg[CF_MAXSHELLARGS][CF_BUFSIZE];
  char **argv;

if (!useshell)
   {
   /* Build argument array */

   for (i = 0; i < CF_MAXSHELLARGS; i++)
      {
      memset (arg[i],0,CF_BUFSIZE);
      }

   argc = SplitCommand(comm,arg);

   if (argc == -1)
      {
      snprintf(OUTPUT,CF_BUFSIZE,"Too many arguments in %s\n",comm);
      CfLog(cferror,OUTPUT,"");
      return false;
      }
   }
    
if ((pid = fork()) < 0)
   {
   FatalError("Failed to fork new process");
   }
else if (pid == 0)                     /* child */
   {
   ALARM_PID = -1;
   if (useshell)
      {
      if (execl("/bin/sh","sh","-c",comm,NULL) == -1)
         {
         yyerror("script failed");
         perror("execl");
         exit(1);
         }
      }
   else
      {
      argv = (char **) malloc((argc+1)*sizeof(char *));

      if (argv == NULL)
         {
         FatalError("Out of memory");
         }

      for (i = 0; i < argc; i++)
         {
         argv[i] = arg[i];
         }

      argv[i] = (char *) NULL;

      if (execv(arg[0],argv) == -1)
         {
         yyerror("script failed");
         perror("execvp");
         exit(1);
         }

      free((char *)argv);
      }
   }
else                                    /* parent */
   {
   pid_t wait_result;
   
   while ((wait_result = wait(&status)) != pid)
      {
      if (wait_result <= 0)
         {
         snprintf(OUTPUT,CF_BUFSIZE,"Wait for child failed\n");
         CfLog(cfinform,OUTPUT,"wait");
         return false;
         }
      }

   if (WIFSIGNALED(status))
      {
      Debug("Script %s returned: %d\n",comm,WTERMSIG(status));
      return false;
      }
   
   if (! WIFEXITED(status))
      {
      return false;
      }
   
   if (WEXITSTATUS(status) == 0)
      {
      Debug("Shell command returned 0\n");
      return true;
      }
   else
      {
      Debug("Shell command was non-zero: %d\n",WEXITSTATUS(status));
      return false;
      }
   }

return false;
}
Example #8
0
int DdmTestConsole::DisplayHandles(int _ConnectionID, char *pCommandLine) {

	int displayMask = 0x0;
	char *pCurrent = pCommandLine;
	int iCurrent;
	char *pArg;
	char *pRest;
	int rulenum, tempi, pos;

	// trim whitespace off front
	for (pos=0; pos < (int)strlen(pCommandLine); pos++) {
		if (pCommandLine[pos] == ' ')
			pCurrent++;
		else
			break;
	}
	
	// and back
	for (iCurrent = strlen(pCurrent); iCurrent > 0; iCurrent--) {
		if (pCurrent[iCurrent-1] != ' ')
			break;
	}
	
	// If we didn't get any arguments, display all the handles
	if (iCurrent == 0)	{
		displayMask = 0xFFFFFFFF;
	}
	// If we got a digit, we must be requesting individual handles
	else if (isdigit(pCurrent[0])) {
		SplitCommand(pCurrent, pArg, pRest);
		while (pArg[0] != 0) {
			int handlenum = atoi(pArg);
			if (handlenum < HandleMan->numHandles) {
				WriteString(_ConnectionID, "\n\rHandle Information:\n\r\0");
				DisplayHandle(_ConnectionID, handlenum);		
			}
			else {
				WriteString(_ConnectionID, "\n\rInvalid handle specified\n\r\0");				
			}
			pCurrent = pRest;
			SplitCommand(pCurrent, pArg, pRest);
		}
		return 0;
	}
	// else I guess we must want to mask the entire list
	else {
	
		SplitCommand(pCurrent, pArg, pRest);
		while (pArg[0] != 0) {
			if (!strcmp(pArg, "running"))
				displayMask = displayMask |= Running;
			else if (!strcmp(pArg, "finished"))
				displayMask = displayMask |= Finished;
			else if (!strcmp(pArg, "error"))
				displayMask = displayMask |= Error;	
			pCurrent = pRest;
			SplitCommand(pCurrent, pArg, pRest);
		}
		
		// if we didn't recognize any masks, it must have been a typo - display them all
		if (displayMask ==  0x0)
			displayMask = 0xFFFFFFFF;
	}

	WriteString(_ConnectionID, "\n\rHandle List:\n\r\0");

	for(int i=0; i < HandleMan->numHandles; i++) {
		DisplayHandle(_ConnectionID, i, displayMask);
	}

	return 0;
	
}
Example #9
0
STATUS DdmTestConsole::ReadReplyHandler(Message * pMsgReq) {

	NetMsgRead* pReadMsg = (NetMsgRead*) pMsgReq;
	
	// a happy read buffer was received
	if(pReadMsg->DetailedStatusCode == OK) {
	
		char *pBuf;
		char *pTemp;
		char *pCommandLine;
		char *pCommand = NULL;
		char *pArgs = NULL;
		int clSize;
		int iBufSize;
		int currSession;
		int oldSize;
		int tempi;
		
		pReadMsg->GetBuffer(pBuf,iBufSize);		
		
		currSession = SessionMan->GetSessionIndex(pReadMsg->m_iConnectionID);
		
		// Get the old size of the buffer
		oldSize = SessionMan->pSession[currSession]->BufferPosition();
												
		// Scan input stream
		for (int i=0; i < iBufSize; i++) {
		
			switch (pBuf[i]) {

				// [ESC]: Clear Buffer / line on the screen
				case 0x1B:
					SessionMan->pSession[currSession]->ClearBuffer();
					WriteString(pReadMsg->m_iConnectionID, "\r\0");
					WriteString(pReadMsg->m_iConnectionID, "                                                                  \r\0");
					DisplayCommandLine(pReadMsg->m_iConnectionID);
					break;
					
				// Backspace
				case 0x08:
					if (SessionMan->pSession[currSession]->BufferPosition() > 0) {
						SessionMan->pSession[currSession]->bufPos--;
						WriteString(pReadMsg->m_iConnectionID, "\b\0");
						WriteString(pReadMsg->m_iConnectionID, " \0");
						WriteString(pReadMsg->m_iConnectionID, "\b\0");
					}
					break;

				// Disregard newline
				case 0x0A:
					break;
									
				// Enter (command in buffer)
				case 0x0D:
					SessionMan->pSession[currSession]->GetBuffer(pTemp, clSize);
					if (clSize > 0) {
						STATUS status;
						pCommandLine = new char[clSize+1];
						memcpy(pCommandLine, pTemp, clSize);
						pCommandLine[clSize] = 0;
						
						SessionMan->pSession[currSession]->ClearBuffer();
						
						// trim whitespace off front (move the data, not the pointer)
						while (pCommandLine[0] == ' ') {
							memcpy(pCommandLine, &pCommandLine[1], strlen(pCommandLine));				
						}

						// and back
						for (int iCurrent = strlen(pCommandLine); iCurrent > 0; iCurrent--) {
							if (pCommandLine[iCurrent-1] != ' ')
								break;
							else
								pCommandLine[iCurrent-1] = 0;
						}
						
						// if there actually is a command here, process the command
						if (strlen(pCommandLine) > 0) {
						
							// process the command - it must be done here since there could be
							// multiple commands per incoming buffer
							SplitCommand(pCommandLine, pCommand, pArgs);
//							Tracef("Command : [%s]\nArgs : [%s]\n", pCommand, pArgs);
						
							// Determine what the command is and execute it
							status = CommandMan->RunCommand(pReadMsg->m_iConnectionID, pCommand, pArgs);
							// icky - this really needs some spit shining
							// we didn't find a command
							if (status == -2)
							{
								WriteString(pReadMsg->m_iConnectionID, "\n\rInvalid command\n\r\0");											
							}
				
							delete[] pCommandLine;
						}
						
					}
				
					// Display the command line prompt
					WriteString(pReadMsg->m_iConnectionID, "\n\r\0");					
					DisplayCommandLine(pReadMsg->m_iConnectionID);
					break;

				// Dump test tables out serial port (Ctrl-T)
				case 0x14:
					TestTable::Dump();
					break;
					
				// Report delta memory (Ctrl-D)
				case 0x04:
					OsHeap::heapSmall.ReportDeltaMemoryUsage("Mem Report");
					break;			

				// Regular character, copy into buffer and echo to client
				default:
					SessionMan->pSession[currSession]->AddToBuffer(&pBuf[i], 1);
					WriteChar(pReadMsg->m_iConnectionID, pBuf[i]);					
					break;
					
			} // end switch
		} // end for iBufSize
	} // end if DetailedStatus OK
	else {
		// We have lost the connection with that socket
		// DdmNet should handle cleanup of outstanding messages, but we need to do some internal
		// cleanup.  Remove the session it was under.  We should also cleanup all the outputs
		// involving that ConnectionID, but that will have to wait
//		Tracef("DdmTestConsole: Connection %d has been terminated\n",pReadMsg->m_iConnectionID);
		SessionMan->RemoveSession(pReadMsg->m_iConnectionID);				
	}
	delete pReadMsg;
	
	return OK;
}
Example #10
0
bool Tex2RTFConnection::OnExecute(const wxString& WXUNUSED(topic), wxChar *data, int WXUNUSED(size), wxIPCFormat WXUNUSED(format))
{
  wxStrcpy(Tex2RTFLastStatus, _T("OK"));

  wxChar firstArg[50];
  wxChar secondArg[300];
  if (SplitCommand(data, firstArg, secondArg))
  {
    bool hasArg = (wxStrlen(secondArg) > 0);
    if (wxStrcmp(firstArg, _T("INPUT")) == 0 && hasArg)
    {
        InputFile = secondArg;
        if (frame)
        {
            wxChar buf[100];
            wxString str = wxFileNameFromPath(InputFile);
            wxSnprintf(buf, sizeof(buf), _T("Tex2RTF [%s]"), (const wxChar*) str);
            frame->SetTitle(buf);
        }
    }
    else if (wxStrcmp(firstArg, _T("OUTPUT")) == 0 && hasArg)
    {
        OutputFile = secondArg;
    }
    else if (wxStrcmp(firstArg, _T("GO")) == 0)
    {
      wxStrcpy(Tex2RTFLastStatus, _T("WORKING"));
      if (!Go())
        wxStrcpy(Tex2RTFLastStatus, _T("CONVERSION ERROR"));
      else
        wxStrcpy(Tex2RTFLastStatus, _T("OK"));
    }
    else if (wxStrcmp(firstArg, _T("EXIT")) == 0)
    {
      if (frame) frame->Close();
    }
    else if (wxStrcmp(firstArg, _T("MINIMIZE")) == 0 || wxStrcmp(firstArg, _T("ICONIZE")) == 0)
    {
      if (frame)
        frame->Iconize(true);
    }
    else if (wxStrcmp(firstArg, _T("SHOW")) == 0 || wxStrcmp(firstArg, _T("RESTORE")) == 0)
    {
      if (frame)
      {
        frame->Iconize(false);
        frame->Show(true);
      }
    }
    else
    {
      // Try for a setting
      wxStrcpy(Tex2RTFLastStatus, RegisterSetting(firstArg, secondArg, false));
#if !defined(NO_GUI) && wxUSE_STATUSBAR
      if (frame && wxStrcmp(firstArg, _T("conversionMode")) == 0)
      {
        wxChar buf[100];
        wxStrcpy(buf, _T("In "));

        if (winHelp && (convertMode == TEX_RTF))
          wxStrcat(buf, _T("WinHelp RTF"));
        else if (!winHelp && (convertMode == TEX_RTF))
          wxStrcat(buf, _T("linear RTF"));
        else if (convertMode == TEX_HTML) wxStrcat(buf, _T("HTML"));
        else if (convertMode == TEX_XLP) wxStrcat(buf, _T("XLP"));
          wxStrcat(buf, _T(" mode."));
        frame->SetStatusText(buf, 1);
      }
#endif
    }
  }
  return true;
}
Example #11
0
void OpenSessionInPutty(const UnicodeString & PuttyPath,
  TSessionData * SessionData)
{
  UnicodeString Program, Params, Dir;
  SplitCommand(PuttyPath, Program, Params, Dir);
  Program = ExpandEnvironmentVariables(Program);
  if (FindFile(Program))
  {
    Params = ExpandEnvironmentVariables(Params);
    UnicodeString Password = GetGUIConfiguration()->GetPuttyPassword() ? SessionData->GetPassword() : UnicodeString();
    UnicodeString Psw = Password;
    UnicodeString SessionName;
    std::unique_ptr<TRegistryStorage> Storage(new TRegistryStorage(GetConfiguration()->GetPuttySessionsKey()));
    Storage->SetAccessMode(smReadWrite);
    // make it compatible with putty
    Storage->SetMungeStringValues(false);
    Storage->SetForceAnsi(true);
    if (Storage->OpenRootKey(true))
    {
      if (Storage->KeyExists(SessionData->GetStorageKey()))
      {
        SessionName = SessionData->GetSessionName();
      }
      else
      {
        std::unique_ptr<TRegistryStorage> SourceStorage(new TRegistryStorage(GetConfiguration()->GetPuttySessionsKey()));
        SourceStorage->SetMungeStringValues(false);
        SourceStorage->SetForceAnsi(true);
        if (SourceStorage->OpenSubKey(StoredSessions->GetDefaultSettings()->GetName(), false) &&
            Storage->OpenSubKey(GetGUIConfiguration()->GetPuttySession(), true))
        {
          Storage->Copy(SourceStorage.get());
          Storage->CloseSubKey();
        }

        std::unique_ptr<TSessionData> ExportData(new TSessionData(L""));
        ExportData->Assign(SessionData);
        ExportData->SetModified(true);
        ExportData->SetName(GetGUIConfiguration()->GetPuttySession());
        ExportData->SetPassword(L"");

        if (SessionData->GetFSProtocol() == fsFTP)
        {
          if (GetGUIConfiguration()->GetTelnetForFtpInPutty())
          {
            ExportData->SetPuttyProtocol(PuttyTelnetProtocol);
            ExportData->SetPortNumber(TelnetPortNumber);
            // PuTTY  does not allow -pw for telnet
            Psw.Clear();
          }
          else
          {
            ExportData->SetPuttyProtocol(PuttySshProtocol);
            ExportData->SetPortNumber(SshPortNumber);
          }
        }

        ExportData->Save(Storage.get(), true);
        SessionName = GetGUIConfiguration()->GetPuttySession();
      }
    }

    if (!Params.IsEmpty())
    {
      Params += L" ";
    }
    if (!Psw.IsEmpty())
    {
      Params += FORMAT(L"-pw %s ", EscapePuttyCommandParam(Psw).c_str());
    }
    //Params += FORMAT(L"-load %s", EscapePuttyCommandParam(SessionName).c_str());
    Params += FORMAT(L"-l %s ", EscapePuttyCommandParam(SessionData->GetUserNameExpanded()).c_str());
    Params += FORMAT(L"-P %d ", SessionData->GetPortNumber());
    Params += FORMAT(L"%s ", EscapePuttyCommandParam(SessionData->GetHostNameExpanded()).c_str());

    if (!ExecuteShell(Program, Params))
    {
      throw Exception(FMTLOAD(EXECUTE_APP_ERROR, Program.c_str()));
    }
  }
  else
  {
    throw Exception(FMTLOAD(FILE_NOT_FOUND, Program.c_str()));
  }
}