void CommandLoop( void *theEnv) { int inchar; EnvPrintRouter(theEnv,WPROMPT,CommandLineData(theEnv)->BannerString); EnvSetHaltExecution(theEnv,false); EnvSetEvaluationError(theEnv,false); CleanCurrentGarbageFrame(theEnv,NULL); CallPeriodicTasks(theEnv); PrintPrompt(theEnv); RouterData(theEnv)->CommandBufferInputCount = 0; RouterData(theEnv)->AwaitingInput = true; while (true) { /*===================================================*/ /* If a batch file is active, grab the command input */ /* directly from the batch file, otherwise call the */ /* event function. */ /*===================================================*/ if (BatchActive(theEnv) == true) { inchar = LLGetcBatch(theEnv,STDIN,true); if (inchar == EOF) { (*CommandLineData(theEnv)->EventFunction)(theEnv); } else { ExpandCommandString(theEnv,(char) inchar); } } else { (*CommandLineData(theEnv)->EventFunction)(theEnv); } /*=================================================*/ /* If execution was halted, then remove everything */ /* from the command buffer. */ /*=================================================*/ if (EnvGetHaltExecution(theEnv) == true) { EnvSetHaltExecution(theEnv,false); EnvSetEvaluationError(theEnv,false); FlushCommandString(theEnv); #if ! WINDOW_INTERFACE fflush(stdin); #endif EnvPrintRouter(theEnv,WPROMPT,"\n"); PrintPrompt(theEnv); } /*=========================================*/ /* If a complete command is in the command */ /* buffer, then execute it. */ /*=========================================*/ ExecuteIfCommandComplete(theEnv); } }
globle void CommandLoop( void *theEnv) { int inchar; EnvPrintRouter(theEnv,WPROMPT,CommandLineData(theEnv)->BannerString); SetHaltExecution(theEnv,FALSE); SetEvaluationError(theEnv,FALSE); PeriodicCleanup(theEnv,TRUE,FALSE); PrintPrompt(theEnv); RouterData(theEnv)->CommandBufferInputCount = 0; while (TRUE) { /*===================================================*/ /* If a batch file is active, grab the command input */ /* directly from the batch file, otherwise call the */ /* event function. */ /*===================================================*/ if (BatchActive(theEnv) == TRUE) { inchar = LLGetcBatch(theEnv,"stdin",TRUE); if (inchar == EOF) { (*CommandLineData(theEnv)->EventFunction)(theEnv); } else { ExpandCommandString(theEnv,(char) inchar); } } else { (*CommandLineData(theEnv)->EventFunction)(theEnv); } /*=================================================*/ /* If execution was halted, then remove everything */ /* from the command buffer. */ /*=================================================*/ if (GetHaltExecution(theEnv) == TRUE) { SetHaltExecution(theEnv,FALSE); SetEvaluationError(theEnv,FALSE); FlushCommandString(theEnv); #if ! WINDOW_INTERFACE fflush(stdin); #endif EnvPrintRouter(theEnv,WPROMPT,"\n"); PrintPrompt(theEnv); } /*=========================================*/ /* If a complete command is in the command */ /* buffer, then execute it. */ /*=========================================*/ ExecuteIfCommandComplete(theEnv); } }
// //Entry point of the text mode shell. // DWORD ShellEntryPoint(LPVOID pData) { __KERNEL_THREAD_MESSAGE KernelThreadMessage; s_hHiscmdInoObj = His_CreateHisObj(HISCMD_MAX_COUNT); StrCpy(DEF_PROMPT_STR,&s_szPrompt[0]); CD_PrintString(VERSION_INFO,FALSE); CD_SetCursorPos(0,SHELL_INPUT_START_Y_FIRST); PrintPrompt(); while(TRUE) { if(GetMessage(&KernelThreadMessage)) { if(KERNEL_MESSAGE_TERMINAL == KernelThreadMessage.wCommand) { break; } DispatchMessage(&KernelThreadMessage,EventHandler); } } //When reach here,it means the shell thread will terminate.We will reboot //the system in current version's implementation,since there is no interact //mechanism between user and computer in case of no shell. //NOTE:System clean up operations should be put here if necessary. #ifdef __I386__ BIOSReboot(); #endif return 0; }
void HandleTextWho(char *receive_buffer, char *output) { struct text_who who; memcpy(&who, receive_buffer, sizeof(text_who)); // int user_info_size = tmp.txt_nusernames; // size_t who_size = sizeof(text_who) + (user_info_size * sizeof(user_info)); // struct text_who *who = (text_who *) malloc(who_size); // memset(who, '\0', who_size); // memcpy(&who, receive_buffer, who_size); std::string backspaces = ""; for (int i = 0; i < SAY_MAX; i++) { backspaces.append("\b"); } std::cout << backspaces; std::cout << "Channel: " << who.txt_channel << std::endl; std::cout << "User count: " << who.txt_nusernames << std::endl; for (int i = 10; i < who.txt_nusernames + 20; i++) { std::cout << " " << who.txt_users[i].us_username << std::endl; } PrintPrompt(); std::cout << output << std::flush; // free(who); }
// //Entry point of the text mode shell. // DWORD ShellEntryPoint(LPVOID pData) { __KERNEL_THREAD_MESSAGE KernelThreadMessage; //Print out version and author information. //GotoHome(); //ChangeLine(); //PrintStr(VERSION_INFO); GotoHome(); ChangeLine(); PrintPrompt(); while(TRUE) { if(GetMessage(&KernelThreadMessage)) { if(KERNEL_MESSAGE_TERMINAL == KernelThreadMessage.wCommand) { break; } DispatchMessage(&KernelThreadMessage,EventHandler); } } //When reach here,it means the shell thread will terminate.We will reboot //the system in current version's implementation,since there is no interact //mechanism between user and computer in case of no shell. //NOTE:System clean up operations should be put here if necessary. #ifdef __I386__ BIOSReboot(); #endif return 0; }
static BOOL OnKeyControl(BYTE bt) { switch(bt) { case VK_RETURN: { DoCommand(); PrintPrompt(); } break; case VK_BACKSPACE: { WORD CursorX = 0; WORD CursorY = 0; CD_GetCursorPos(&CursorX,&CursorY); if(CursorX <= strlen(s_szPrompt)) { break; } CD_DelChar(DISPLAY_DELCHAR_PREV); } break; default: { CD_PrintChar(bt); } } return TRUE; }
bool ExecuteIfCommandComplete( void *theEnv) { if ((CompleteCommand(CommandLineData(theEnv)->CommandString) == 0) || (RouterData(theEnv)->CommandBufferInputCount == 0) || (RouterData(theEnv)->AwaitingInput == false)) { return false; } if (CommandLineData(theEnv)->BeforeCommandExecutionFunction != NULL) { if (! (*CommandLineData(theEnv)->BeforeCommandExecutionFunction)(theEnv)) { return false; } } FlushPPBuffer(theEnv); SetPPBufferStatus(theEnv,false); RouterData(theEnv)->CommandBufferInputCount = 0; RouterData(theEnv)->AwaitingInput = false; RouteCommand(theEnv,CommandLineData(theEnv)->CommandString,true); FlushPPBuffer(theEnv); FlushParsingMessages(theEnv); EnvSetHaltExecution(theEnv,false); EnvSetEvaluationError(theEnv,false); FlushCommandString(theEnv); CleanCurrentGarbageFrame(theEnv,NULL); CallPeriodicTasks(theEnv); PrintPrompt(theEnv); return true; }
void CommandLoopBatchDriver( void *theEnv) { int inchar; while (true) { if (GetHaltCommandLoopBatch(theEnv) == true) { CloseAllBatchSources(theEnv); SetHaltCommandLoopBatch(theEnv,false); } /*===================================================*/ /* If a batch file is active, grab the command input */ /* directly from the batch file, otherwise call the */ /* event function. */ /*===================================================*/ if (BatchActive(theEnv) == true) { inchar = LLGetcBatch(theEnv,STDIN,true); if (inchar == EOF) { return; } else { ExpandCommandString(theEnv,(char) inchar); } } else { return; } /*=================================================*/ /* If execution was halted, then remove everything */ /* from the command buffer. */ /*=================================================*/ if (EnvGetHaltExecution(theEnv) == true) { EnvSetHaltExecution(theEnv,false); EnvSetEvaluationError(theEnv,false); FlushCommandString(theEnv); #if ! WINDOW_INTERFACE fflush(stdin); #endif EnvPrintRouter(theEnv,WPROMPT,"\n"); PrintPrompt(theEnv); } /*=========================================*/ /* If a complete command is in the command */ /* buffer, then execute it. */ /*=========================================*/ ExecuteIfCommandComplete(theEnv); } }
globle void CommandLoopBatch( void *theEnv) { SetHaltExecution(theEnv,FALSE); SetEvaluationError(theEnv,FALSE); PeriodicCleanup(theEnv,TRUE,FALSE); PrintPrompt(theEnv); RouterData(theEnv)->CommandBufferInputCount = 0; CommandLoopBatchDriver(theEnv); }
void HandleError(char *receive_buffer, char *output) { struct text_error error; memcpy(&error, receive_buffer, sizeof(struct text_error)); std::string backspaces = ""; for (int i = 0; i < SAY_MAX; i++) { backspaces.append("\b"); } std::cout << backspaces; std::cout << "Error: " << error.txt_error << std::endl; PrintPrompt(); std::cout << output << std::flush; }
// Handles TXT-SAY server messages. void HandleTextSay(char *receive_buffer, char *output) { struct text_say say; memcpy(&say, receive_buffer, sizeof(struct text_say)); std::string backspaces = ""; for (int i = 0; i < SAY_MAX; i++) { backspaces.append("\b"); } std::cout << backspaces; std::cout << "[" << say.txt_channel << "]" << "[" << say.txt_username << "]: " << say.txt_text << std::endl; PrintPrompt(); std::cout << output << std::flush; }
void TestContestant(char *ContestantName) { printf("\n>>> Contestant : %s\n", ContestantName); char TesterCommand[1024]; int LastReturnValue = 0; for (int i = 0; i < CommandCount; i++) { if (strcmp(Config[i].MainCommand, "#TC") == 0) { char sExecutable[256], Executable[256]; char sExecutableParameters[256], ExecutableParameters[256]; char sCheckerCommand[256], CheckerCommand[256]; strrpl(sExecutable, Config[i].Executable, "$(CONTESTANT)", ContestantName); strrpl(Executable, sExecutable, "%20", " "); strrpl(sExecutableParameters, Config[i].ExecutableParameters, "$(CONTESTANT)", ContestantName); strrpl(ExecutableParameters, sExecutableParameters, "%20", " "); strrpl(sCheckerCommand, Config[i].CheckerCommand, "$(CONTESTANT)", ContestantName); strrpl(CheckerCommand, sCheckerCommand, "%20", " "); PrintPrompt(Config[i].Identifier); char TesterCommand[1024]; sprintf(TesterCommand, "./tester %d \"%s\" \"%s\" %d %d \"%s\" RESULT", Config[i].TestType, Executable, ExecutableParameters, Config[i].TimeLimit, Config[i].MemoryLimit, CheckerCommand/*, Config[i].OutputFile, Config[i].AnswerFile*/); LastReturnValue = system(TesterCommand); PrintResult(); } else if (strcmp(Config[i].MainCommand, "#N0") == 0) { if (LastReturnValue != 0) { i += atoi(Config[i].Parameter); } } else { char ParsedContestantCommand[1024]; char ParsedSpaceCommand[1024]; strrpl(ParsedContestantCommand, Config[i].MainCommand, "$(CONTESTANT)", ContestantName); strrpl(ParsedSpaceCommand, ParsedContestantCommand, "%20", " "); LastReturnValue = system(ParsedSpaceCommand); } } printf("\n"); }
void CommandLoopBatch( void *theEnv) { EnvSetHaltExecution(theEnv,false); EnvSetEvaluationError(theEnv,false); CleanCurrentGarbageFrame(theEnv,NULL); CallPeriodicTasks(theEnv); PrintPrompt(theEnv); RouterData(theEnv)->CommandBufferInputCount = 0; RouterData(theEnv)->AwaitingInput = true; CommandLoopBatchDriver(theEnv); }
void HandleTextList(char *receive_buffer, char *output) { struct text_list list; memcpy(&list, receive_buffer, sizeof(struct text_list)); std::string backspaces = ""; for (int i = 0; i < SAY_MAX; i++) { backspaces.append("\b"); } std::cout << backspaces; std::cout << "Existing channels:" << std::endl; for (int i = 2; i < list.txt_nchannels + 2; i++) { std::cout << " " << list.txt_channels[i].ch_channel << std::endl; } PrintPrompt(); std::cout << output << std::flush; }
//Shell thread's event handler. static BOOL EventHandler(WORD wCommand,WORD wParam,DWORD dwParam) { WORD wr = 0x0700; BYTE bt = 0x00; switch(wCommand) { case MSG_KEY_DOWN: bt = (BYTE)(dwParam); if(VK_RETURN == bt) { if(BufferPtr) { DoCommand(); } PrintPrompt(); break; } if(VK_BACKSPACE == bt) { if(0 != BufferPtr) { GotoPrev(); BufferPtr --; } break; } else { if(MAX_BUFFER_LEN - 1 > BufferPtr) { CmdBuffer[BufferPtr] = bt; BufferPtr ++; wr += (BYTE)(dwParam); PrintCh(wr); } } break; case KERNEL_MESSAGE_TIMER: default: break; } return 0; }
globle intBool ExecuteIfCommandComplete( void *theEnv) { if ((CompleteCommand(CommandLineData(theEnv)->CommandString) == 0) || (RouterData(theEnv)->CommandBufferInputCount <= 0)) { return FALSE; } FlushPPBuffer(theEnv); SetPPBufferStatus(theEnv,OFF); RouterData(theEnv)->CommandBufferInputCount = -1; RouteCommand(theEnv,CommandLineData(theEnv)->CommandString,TRUE); FlushPPBuffer(theEnv); SetHaltExecution(theEnv,FALSE); SetEvaluationError(theEnv,FALSE); FlushCommandString(theEnv); FlushBindList(theEnv); PeriodicCleanup(theEnv,TRUE,FALSE); PrintPrompt(theEnv); return TRUE; }
// Processes the input string to decide what type of command it is. bool ProcessInput(std::string input) { std::vector<std::string> inputs = SplitString(input); if (inputs[0] == "/exit") { SendLogout(); cooked_mode(); return false; } else if (inputs[0] == "/list") { SendList(); } else if (inputs[0] == "/join" && inputs.size() > 1) { SendJoin(inputs[1]); } else if (inputs[0] == "/leave" && inputs.size() > 1) { SendLeave(inputs[1]); } else if (inputs[0] == "/who" && inputs.size() > 1) { SendWho(inputs[1]); } else if (inputs[0] == "/switch" && inputs.size() > 1) { SwitchChannel(inputs[1]); } else { std::cout << "*Unknown command" << std::endl; } PrintPrompt(); return true; }
HDDEDATA CALLBACK DDECallBack( UINT uType, UINT uFmt, HCONV hconv, HSZ hsz1, HSZ hsz2, HDDEDATA hData, DWORD dwData1, DWORD dwData2) { #if MAC_MCW || WIN_MCW || MAC_XCD #pragma unused(hconv) #pragma unused(dwData1) #pragma unused(dwData2) #endif extern HSZ hszService; extern char CompleteString[255]; DWORD size; HWND hWnd; char *TheData; char *Data; char *theString; void *theEnv = GetCurrentEnvironment(); /* char theBuffer[100]; DWORD cb; PSTR pszTopicName; */ switch (uType) { case XTYP_ADVDATA: case XTYP_POKE: return ((HDDEDATA) DDE_FNOTPROCESSED); case XTYP_ADVREQ: case XTYP_WILDCONNECT: return ((HDDEDATA) NULL); case XTYP_ADVSTART: case XTYP_ADVSTOP: case XTYP_CONNECT_CONFIRM: case XTYP_DISCONNECT: case XTYP_ERROR: case XTYP_REGISTER: case XTYP_UNREGISTER: case XTYP_XACT_COMPLETE: return ((HDDEDATA) FALSE); case XTYP_MONITOR: return ((HDDEDATA) TRUE); case XTYP_CONNECT: /* cb = DdeQueryString(idInst,hsz1,(LPSTR) NULL, 0,CP_WINANSI) + 1; pszTopicName = (PSTR) LocalAlloc(LPTR, (UINT) cb); DdeQueryString(idInst,hsz1, pszTopicName,cb,CP_WINANSI); cb = DdeQueryString(idInst,hsz2,(LPSTR) NULL, 0,CP_WINANSI) + 1; pszTopicName = (PSTR) LocalAlloc(LPTR, (UINT) cb); DdeQueryString(idInst,hsz2, pszTopicName,cb,CP_WINANSI); */ DDE_RV.type = RVOID; if (hsz2 != hszService) { return ((HDDEDATA) FALSE); } return((HDDEDATA) TRUE); /*--------------------------------------------------+ | Get completed command and return result to client | +--------------------------------------------------*/ case XTYP_REQUEST: if (uFmt != CF_TEXT) { return(NULL); } /* sprintf(theBuffer,"XTYP_REQUEST uFmt = %d\n",(int) uFmt); PrintRouter(WDISPLAY,theBuffer); */ hData = NULL; if (hsz1 == hszCommand) { theString = DataObjectToString(GetCurrentEnvironment(),&DDE_RV); hData = DdeCreateDataHandle (idInst, (unsigned char *) theString, strlen(theString)+1, 0L, hsz2,CF_TEXT,0); } return (hData); case XTYP_EXECUTE: SetFocus(DialogWindow); if (CommandLineData(GetCurrentEnvironment())->EvaluatingTopLevelCommand || BatchActive(GetCurrentEnvironment()) ) { return ((HDDEDATA) DDE_FBUSY ); } Data = (char *) DdeAccessData ( hData, NULL); size = strlen((char *) Data) + 1; TheData = (char *) genalloc ( GetCurrentEnvironment(),(unsigned) size ); DdeGetData ( hData, (LPBYTE)TheData, size, 0L ); EnvPrintRouter(theEnv,WPROMPT,TheData); EnvPrintRouter(theEnv,WPROMPT,"\n"); EnvEval(theEnv,TheData,&DDE_RV); if (DDE_RV.type != RVOID) { PrintDataObject(GetCurrentEnvironment(),"stdout",&DDE_RV); EnvPrintRouter(theEnv,"stdout","\n"); } PrintPrompt(theEnv); DdeUnaccessData(hData); hWnd = FindWindow("ClipsEditWClass", NULL); SetFocus (hWnd); return ((HDDEDATA) DDE_FACK); } return ( (HDDEDATA) TRUE ); }
int main(int argc, char *argv[]) { char *domain; char *port_str; int port_num; char *username; std::string input; char *output = (char *) ""; fd_set read_set; int result; char stdin_buffer[SAY_MAX + 1]; char *stdin_buffer_pointer = stdin_buffer; char receive_buffer[kBufferSize]; memset(&receive_buffer, 0, kBufferSize); if (argc < 4) { Error("usage: client [server name] [port] [username]"); } domain = argv[1]; port_str = argv[2]; port_num = atoi(argv[2]); username = argv[3]; if (strlen(domain) > UNIX_PATH_MAX) { Error("client: server name must be less than 108 characters"); } if (port_num < 0 || port_num > 65535) { Error("client: port number must be between 0 and 65535"); } if (strlen(username) > USERNAME_MAX) { Error("client: username must be less than 32 characters"); } CreateSocket(domain, port_str); // SendLogin(username); // // current_channel = "Common"; // SendJoin(current_channel); if (raw_mode() != 0) { Error("client: error using raw mode"); } PrintPrompt(); while (1) { FD_ZERO(&read_set); FD_SET(client_socket, &read_set); FD_SET(STDIN_FILENO, &read_set); if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) { Error("client: problem using select"); } if (result > 0) { if (FD_ISSET(STDIN_FILENO, &read_set)) { // User entered a char. char c = (char) getchar(); if (c == '\n') { // Increments pointer and adds NULL char. *stdin_buffer_pointer++ = '\0'; // Resets stdin_buffer_pointer to the start of stdin_buffer. stdin_buffer_pointer = stdin_buffer; std::cout << "\n" << std::flush; // Prevents output from printing on the new prompt after a newline char. output = (char *) ""; input.assign(stdin_buffer, stdin_buffer + strlen(stdin_buffer)); if (input[0] == '/') { if (!ProcessInput(input)) { break; } } else { // Sends chat messages. if (current_channel != "") { SendSay(input); } else { PrintPrompt(); } } } else if (stdin_buffer_pointer != stdin_buffer + SAY_MAX) { // Increments pointer and adds char c. *stdin_buffer_pointer++ = c; std::cout << c << std::flush; // Copies pointer into output. output = stdin_buffer_pointer; // Increments and sets NULL char. *output++ = '\0'; // Copies stdin_buffer into part of output before NULL char. output = stdin_buffer; } } else if (FD_ISSET(client_socket, &read_set)) { // Socket has data. ssize_t read_size = read(client_socket, receive_buffer, kBufferSize); if (read_size != 0) { struct text message; memcpy(&message, receive_buffer, sizeof(struct text)); text_t text_type = message.txt_type; switch (text_type) { case TXT_SAY: HandleTextSay(receive_buffer, output); break; case TXT_LIST: HandleTextList(receive_buffer, output); break; case TXT_WHO: HandleTextWho(receive_buffer, output); break; case TXT_ERROR: HandleError(receive_buffer, output); break; default: break; } } memset(&receive_buffer, 0, SAY_MAX); } // end of if client_socket } // end of if result } // end of while return 0; }
int main(){ //------------------------------------------------------------------------------------ struct termios origConfig; tcgetattr(0, &origConfig); //get original configuration struct termios newConfig = origConfig; // copy original config newConfig.c_lflag &= ~(ICANON|ECHO); // Non-canonical mode; disable echo newConfig.c_cc[VMIN] = 1; newConfig.c_cc[VTIME] = 0; tcsetattr(0, TCSANOW, &newConfig); //set new config //------------------------------------------------------------------ int fd [2]; //file descriptor for pipe int pid, pid2, status,status2, statusDirctory; //P ID, status for cd char * commands[256]; char * commands2[256]; char * CommandLine; char c; char backspace = '\010', DeletBoutton = '\177', newLine = '\012'; //for reading commandLine char by bhar char left = '\103', right = '\104', Up = '\101', Down = '\102'; //history count char del = '\10'; char sp = ' '; char * HistoryElem; char * History[10]; int historyCount=0; int UpCount =0, UpUse =0; int len=0; int HistoryLocation=0; int last; int i =0; //just fixe a big problem that I cannot figure out why it happends while (1) { PrintPrompt(); pipe(fd); commands[0] = NULL; commands2[0] = NULL; CommandLine = (char*) calloc(256, sizeof(char)); HistoryElem = (char*) calloc(256, sizeof(char)); len =0; historyCount=0; UpCount=0; if(HistoryLocation > 0){ last = HistoryLocation-1; } while(1){ read(0, &c, 1); //read the command Char by Char UpUse =0; if(c == newLine){ break; } //--------------------------------------------------- else if(c == '\033'){} else if(c == '\133'){} else if (c == left || c == right) {} //left & rights //------------------------------------------------------------------------- else if(c == Up){ //Up if(UpUse >= 0 && UpUse <= 8){UpUse++;} if(UpUse > 8){UpUse =0; UpUse++; } if(UpUse != 0){ if(i == 0){} else if(History[0] != NULL){ if(historyCount != 9){ if(len != 0){ len--; while(len >= 0){ CommandLine[len] = '\0'; write(1, &del, 1); write(1, &sp, 1); write(1, &del, 1); len--; } } if(last != 0){ if(History[last] != NULL){ if(UpCount == 1){ last--; historyCount++; } write(1, History[last], strlen(History[last])); strcat(CommandLine, History[last]); len = strlen(History[last]);} } else { if (History[last] != NULL){ if(History[9] != NULL){ if(UpCount ==1){ last =9; historyCount++; } write(1, History[last], strlen(History[last])); strcat(CommandLine, History[last]); len = strlen(History[last]); } } else if (History[last] != NULL){ write(1, History[last], strlen(History[last])); strcat(CommandLine, History[last]); len = strlen(History[last]); } } } } UpCount =1; } } //-------------------------------------------------------------------------- else if(c == Down){ //Down if (History[0] != NULL) { if (historyCount != 0) { // Prevent more than 10 forward history recalls if (len != 0) { // Clear any characters typed at prompt len--; while (len >= 0) { CommandLine[len] = '\0'; write(1, &del, 1); write(1, &sp, 1); write(1, &del, 1); len--; } } if (last != 9) { // Return forward history recall last++; write(1, History[last], strlen(History[last])); strcat(CommandLine, History[last]); len = strlen(History[last]); historyCount--; } else { if (History[9] != NULL) { // Jump to bottom of full history array after top element is passed write(1, History[0], strlen(History[0])); strcat(CommandLine, History[0]); last = 0; historyCount--; } } } // Do nothing if completed 10 forward history recalls } } // Delete a character-------------------------------------------------------------- else if ((c == backspace) || (c == DeletBoutton)) { // Backspace or delete if(len > 0){ CommandLine[--len] = '\0'; write(1, &del, 1); write(1, &sp, 1); write(1, &del, 1); } else if (i <= 0){} //do nothing if it is first letter } //------------------------------------------------------------------------no special case else{ i =1; CommandLine[len] = c; //Make CommandLine ready write(1, &CommandLine[len], 1); len++; } } //------------------------------------------------------------------ printf("\n"); //equilalent to break key strcpy(HistoryElem, CommandLine); //if user doesn't enter any command but only enter line, then it simply print the prompt again. if(CommandLine[0] == '\0'){} else{ if(HistoryLocation != 9){ History[HistoryLocation] = HistoryElem; HistoryLocation++; } else{ History[HistoryLocation] = HistoryElem; HistoryLocation=0; } AcceptCommand(CommandLine, commands, commands2); //accept input } //execution ---------------------------------------------------------------------------------------------- if(commands[0] == NULL){} else if(strcmp(commands[0],"exit" )== 0){ //exit command break; } else if(strcmp(commands[0],"cd" )== 0){ //cd command statusDirctory = chdir(commands[1]); if (statusDirctory == -1) { perror(NULL); } } pid = fork(); pid2 = fork(); if(pid2 == 0){ close(fd[1]); dup2(fd[0],0); close(fd[0]); execvp(commands2[0], commands2); perror(NULL); exit(0); } if(pid == 0){ if(strcmp(commands[0],"cd" )== 0){ //cd command exit(0); } else if(commands2[0] != NULL){ close(fd[0]); dup2(fd[1],1); close(fd[1]); execvp(commands[0], commands); //execute the commands perror(NULL); //error in case of invalid command exit(0); } execvp(commands[0], commands); //execute the commands perror(NULL); //error in case of invalid command exit(0); //if after an invalid command, there is exit it makes it work } else{ close(fd[1]); waitpid(pid, &status, WUNTRACED); //wait for process id waitpid(pid2, &status2, WUNTRACED); } } tcsetattr(0, TCSANOW, &origConfig); // Restore config return 0; //doooooooooooooooooooooooooooooone!!!!!!!!!!!!!!! }
long DoLoad ( HWND hMain, WORD LoadType) { OPENFILENAME ofn; extern HANDLE hInst; char File[256], FileTitle[256], Filter[256]; UINT i, cbString; char Replace; File[0] = '\0'; memset ( &ofn,0, sizeof (OPENFILENAME)); /*---------------------------------------------+ | Initialize Common Dialog based on File Type. | +---------------------------------------------*/ switch ( LoadType ) { case IDM_FILE_LOAD: { ofn.lpstrTitle = "Load CLIPS Constructs"; if ((cbString = LoadString ( (HINSTANCE) hInst, IDS_RULES, Filter, sizeof (Filter))) == 0 ) return 0L; break; } case IDM_FILE_LBATCH: { ofn.lpstrTitle = "Load CLIPS Batch File"; if ((cbString = LoadString ( (HINSTANCE) hInst, IDS_BATCH, Filter, sizeof (Filter))) == 0 ) return 0L; break; } case IDM_FILE_LBINARY: { ofn.lpstrTitle = "Load CLIPS Binary File"; if ((cbString = LoadString ( (HINSTANCE) hInst, IDS_BINARY, Filter, sizeof (Filter))) == 0 ) return 0L; break; } } Replace = Filter[cbString-1]; for (i=0; Filter[i] != '\0'; i++) if ( Filter[i] == Replace) Filter[i] = '\0'; ofn.lStructSize = sizeof ( OPENFILENAME ); ofn.hwndOwner = hMain; ofn.lpstrFilter = Filter; ofn.nFilterIndex = 1; ofn.lpstrFile = File; ofn.nMaxFile = sizeof (File ); ofn.lpstrFileTitle = FileTitle; ofn.nMaxFileTitle = sizeof (FileTitle); ofn.lpstrInitialDir = NULL; ofn.Flags = OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; /*--------------------+ | Issue CLIPS Command | +--------------------*/ if ( GetOpenFileName ( &ofn ) ) { int x, size; UpdateCursor(WAIT_CURSOR); /*-----------------+ | Adjust Path Info | +-----------------*/ size = strlen(ofn.lpstrFile ); for ( x=0; x<size ; x++) if ( ofn.lpstrFile [x] == '\\' ) ofn.lpstrFile [x] = '/'; switch ( LoadType ) { case IDM_FILE_LOAD: SetCommandString("(load \""); break; case IDM_FILE_LBATCH: SetCommandString("(batch \""); break; case IDM_FILE_LBINARY: SetCommandString("(bload \""); break; } AppendCommandString ( ofn.lpstrFile ); AppendCommandString ( "\")\n"); PrintCLIPS ( "stdout", GetCommandString()); UpdateCursor ( ARROW_CURSOR ); PrintPrompt(); } return 0L; }
void RunShell() { int running = 1; char* str; char** argv; InitBackgroundProcessing(); while (running) { CheckProcessQueue(); PrintPrompt(); str = ReadInput(); argv = ParseInput(str); if (argv[0] == NULL) { // do nothing if empty arguments } else if (CheckForIOandPipeErrors(argv)) { // do nothing if IO or pipe error } else if (CheckForBackgroundErrors(argv)) { // do nothing if background processing format error } else if (strcmp(argv[0], "exit") == 0) { BigFree(argv); printf("Exiting Shell...\n"); OnExitProcessQueueWait(); exit(0); } else if (strcmp(argv[0], "cd") == 0) { if (ArraySize(argv) <= 2) { if (ArraySize(argv) == 2) ChangeDirectory(argv[1]); else ChangeDirectory(getenv("HOME")); } else { printf("Too many arguments...\n"); } } else if (strcmp(argv[0], "limits") == 0) { if (ArraySize(argv) > 1) { argv = ArrayRemoveElement(argv, 0); Limits(argv); } } else if (strcmp(argv[0], "etime") == 0) { if (ArraySize(argv) > 1) { argv = ArrayRemoveElement(argv, 0); ETime(argv); } } else if (IsExecutable(argv[0])) { int background = VecContainsStr(argv, "&"); int I_loc = VecContainsStr(argv, "<"); int O_loc = VecContainsStr(argv, ">"); int pipe_count = ArgvCountSymbol(argv, "|"); if (I_loc != -1) { argv = ExecuteExternalWithInput(argv, I_loc, background); } else if (O_loc != -1) { argv = ExecuteExternalWithOutput(argv, O_loc, background); } else if (pipe_count > 0) { argv = ExecuteExternalWithPipe(argv, pipe_count, background); } else { char* cmd = ArgvToString(argv); if (background != -1) { argv = ArrayRemoveElement(argv, background); } ExecuteExternal(argv, background, cmd); free(cmd); } } BigFree(argv); } }
void RunProgram(void) { int running = 1; //USER_INPUT[0] = USER_INPUT_0; //USER_INPUT[1] = USER_INPUT_1; //USER_INPUT[2] = USER_INPUT_2; //USER_INPUT[3] = USER_INPUT_3; //USER_INPUT[4] = NULL; while (running) { PrintPrompt(); GetUserInput(); if (strcmp(USER_INPUT[0], "exit") == 0) { running = 0; } else if (strcmp(USER_INPUT[0], "ls") == 0) { if (strcmp(USER_INPUT[1], ". . . . .") == 0) { //printf("Requires an argument for path name\n"); list(GetCurrentDirectoryClusterNum()); } else { ls(USER_INPUT[1]); } } else if (strcmp(USER_INPUT[0], "cd") == 0) { if (strcmp(USER_INPUT[1], ". . . . .") == 0) { printf("Requires an argument for path name\n"); } else if (strcmp(USER_INPUT[1], ".") == 0) { // do nothing } else { //char parsed_dir[USER_INPUT_BUFFER_LENGTH]; //strcpy(parsed_dir, USER_INPUT[1]); //ToFAT32(parsed_dir); //printf("!%s!\n", parsed_dir); cd(USER_INPUT[1]); } } else if (strcmp(USER_INPUT[0], "size") == 0) { if (strcmp(USER_INPUT[1], ". . . . .") == 0) { printf("Requires a file name argument\n"); } else { size(USER_INPUT[1]); } } else if (strcmp(USER_INPUT[0], "open") == 0) { if (strcmp(USER_INPUT[1], ". . . . .") == 0 || strcmp(USER_INPUT[2], ". . . . .") == 0) { printf("Requires a file name argument followed by a mode argument\n"); } else { char parsed_dir[USER_INPUT_BUFFER_LENGTH]; strcpy(parsed_dir, USER_INPUT[1]); ToFAT32(parsed_dir); open(parsed_dir, USER_INPUT[2]); } } else if (strcmp(USER_INPUT[0], "close") == 0) { if (strcmp(USER_INPUT[1], ". . . . .") == 0) { printf("Requires a file name argument\n"); } else { char parsed_dir[USER_INPUT_BUFFER_LENGTH]; strcpy(parsed_dir, USER_INPUT[1]); ToFAT32(parsed_dir); close(parsed_dir); } } else if (strcmp(USER_INPUT[0], "read") == 0) { if (strcmp(USER_INPUT[1],". . . . .") == 0 || strcmp(USER_INPUT[2],". . . . .") == 0 || strcmp(USER_INPUT[3],". . . . .") == 0) { printf("Requires arguments for filename, position, and size\n"); } else { char parsed_dir[USER_INPUT_BUFFER_LENGTH]; strcpy(parsed_dir, USER_INPUT[1]); ToFAT32(parsed_dir); read(parsed_dir, atoi(USER_INPUT[2]), atoi(USER_INPUT[3])); } } else if (strcmp(USER_INPUT[0], "create") == 0) { if (strcmp(USER_INPUT[1],". . . . .") == 0) { printf("Requires an argument for the file name\n"); } else if (strcmp(USER_INPUT[1],".") == 0) { printf("Invalid file name\n"); } else if (strcmp(USER_INPUT[1],"..") == 0) { printf("Invalid file name\n"); } else { char parsed_dir[USER_INPUT_BUFFER_LENGTH]; strcpy(parsed_dir, USER_INPUT[1]); ToFAT32(parsed_dir); create(parsed_dir); } } else if (strcmp(USER_INPUT[0], "mkdir") == 0) { if (strcmp(USER_INPUT[1],". . . . .") == 0) { printf("Requires an argument for the directory name\n"); } else if (strcmp(USER_INPUT[1],".") == 0) { printf("Invalid directory name\n"); } else if (strcmp(USER_INPUT[1],"..") == 0) { printf("Invalid directory name\n"); } else { char parsed_dir[USER_INPUT_BUFFER_LENGTH]; strcpy(parsed_dir, USER_INPUT[1]); ToFAT32(parsed_dir); mkdir(parsed_dir); } } else if (strcmp(USER_INPUT[0], "rm") == 0) { if (strcmp(USER_INPUT[1],". . . . .") == 0) { printf("Requires an argument for the file name\n"); } else if (strcmp(USER_INPUT[1],".") == 0) { printf("Invalid file name\n"); } else if (strcmp(USER_INPUT[1],"..") == 0) { printf("Invalid file name\n"); } else { char parsed_dir[USER_INPUT_BUFFER_LENGTH]; strcpy(parsed_dir, USER_INPUT[1]); ToFAT32(parsed_dir); rm(parsed_dir); } } else if (strcmp(USER_INPUT[0], "rmdir") == 0) { if (strcmp(USER_INPUT[1],". . . . .") == 0) { printf("Requires an argument for the directory name\n"); } else if (strcmp(USER_INPUT[1],".") == 0) { printf("Invalid directory name\n"); } else if (strcmp(USER_INPUT[1],"..") == 0) { printf("Invalid directory name\n"); } else { char parsed_dir[USER_INPUT_BUFFER_LENGTH]; strcpy(parsed_dir, USER_INPUT[1]); ToFAT32(parsed_dir); rmdir(parsed_dir); } } else if (strcmp(USER_INPUT[0], "write") == 0) { if (strcmp(USER_INPUT[1],". . . . .") == 0 || strcmp(USER_INPUT[2],". . . . .") == 0 || strcmp(USER_INPUT[3],". . . . .") == 0 || strcmp(USER_INPUT[4],". . . . .") == 0) { printf("Requires arguments for file name, position, number of bytes, and string to write\n"); } else { char parsed_dir[USER_INPUT_BUFFER_LENGTH]; strcpy(parsed_dir, USER_INPUT[1]); ToFAT32(parsed_dir); write(parsed_dir, atoi(USER_INPUT[2]), atoi(USER_INPUT[3]), USER_INPUT[4]); } } else if (strcmp(USER_INPUT[0], "debug") == 0) { printf("CURRENT_CLUSTER: %d\n", GetCurrentDirectoryClusterNum()); printf("CURRENT_CLUSTER BYTE_ADDRESS: 0x%x\n", FindFirstSectorOfCluster(GetCurrentDirectoryClusterNum())); FTPrint(); PrintDirectoryVector(GetDirectoryContents(GetCurrentDirectoryClusterNum())); } } int k; for (k = 0; k < 5; k++) { free(USER_INPUT[k]); } }
void MainObject::DispatchCommand(QString cmd) { bool processed=false; int line; QTime time; bool ok=false; bool overwrite=!edit_modified; QStringList cmds; QString verb; cmd=cmd.stripWhiteSpace(); if(cmd.right(1)=="!") { overwrite=true; cmd=cmd.left(cmd.length()-1).stripWhiteSpace(); } cmds=cmds.split(" ",cmd); verb=cmds[0].lower(); // // No loaded log needed for these // if(verb=="deletelog") { if(rda->user()->deleteLog()) { if(cmds.size()==2) { Deletelog(cmds[1]); } else { fprintf(stderr,"deletelog: invalid command arguments\n"); } } else { fprintf(stderr,"deletelog: insufficient privileges [Delete Log]\n"); } processed=true; } if((verb=="exit")||(verb=="quit")||(verb=="bye")) { if(overwrite) { exit(0); } else { OverwriteError(verb); } processed=true; } if((verb=="help")||(verb=="?")) { Help(cmds); processed=true; } if(verb=="listlogs") { ListLogs(); processed=true; } if(verb=="listservices") { Listservices(); processed=true; } if(verb=="load") { if(overwrite) { if(cmds.size()==2) { Load(cmds[1]); } else { fprintf(stderr,"load: invalid command arguments\n"); } } else { OverwriteError("load"); } processed=true; } if(verb=="new") { if(overwrite) { if(cmds.size()==2) { New(cmds[1]); } else { fprintf(stderr,"new: invalid command arguments\n"); } } else { OverwriteError("new"); } processed=true; } // // These need a log loaded // if((processed)||(edit_log_event!=NULL)) { if(verb=="addcart") { if(rda->user()->addtoLog()) { if(cmds.size()==3) { line=cmds[1].toInt(&ok); if(ok&&(line>=0)) { unsigned cartnum=cmds[2].toUInt(&ok); if(ok&&(cartnum<=RD_MAX_CART_NUMBER)) { Addcart(line,cartnum); } else { fprintf(stderr,"addcart: invalid cart number\n"); } } else { fprintf(stderr,"addcart: invalid line number\n"); } } else { fprintf(stderr,"addcart: invalid command arguments\n"); } } else { fprintf(stderr,"addcart: insufficient privileges [Add Log Items]\n"); } processed=true; } if(verb=="addchain") { if(rda->user()->addtoLog()) { if(cmds.size()==3) { line=cmds[1].toInt(&ok); if(ok&&(line>=0)) { Addchain(line,cmds[2]); } else { fprintf(stderr,"addchain: invalid line number\n"); } } else { fprintf(stderr,"addchain: invalid command arguments\n"); } } else { fprintf(stderr,"addchain: insufficient privileges [Add Log Items]\n"); } processed=true; } if(verb=="addmarker") { if(rda->user()->addtoLog()) { if(cmds.size()==2) { line=cmds[1].toInt(&ok); if(ok&&(line>=0)) { Addmarker(line); } else { fprintf(stderr,"addmarker: invalid line number\n"); } } else { fprintf(stderr,"addmarker: invalid command arguments\n"); } } else { fprintf(stderr,"addmarker: insufficient privileges [Add Log Items]\n"); } processed=true; } if(verb=="addtrack") { if(rda->user()->addtoLog()) { if(cmds.size()==2) { line=cmds[1].toInt(&ok); if(ok&&(line>=0)) { Addtrack(line); } else { fprintf(stderr,"addtrack: invalid line number\n"); } } else { fprintf(stderr,"addtrack: invalid command arguments\n"); } } else { fprintf(stderr,"addtrack: insufficient privileges [Add Log Items]\n"); } processed=true; } if(verb=="header") { Header(); processed=true; } if(verb=="list") { List(); processed=true; } if(verb=="remove") { if(rda->user()->removefromLog()) { if(cmds.size()==2) { line=cmds[1].toInt(&ok); if(ok&&(line>=0)&&(line<edit_log_event->size())) { Remove(line); } else { fprintf(stderr,"remove: invalid line number\n"); } } else { fprintf(stderr,"remove: invalid command arguments\n"); } } else { fprintf(stderr,"remove: insufficient privileges [Delete Log Items]\n"); } processed=true; } if(verb=="save") { if(rda->user()->arrangeLog()) { Save(); } else { fprintf(stderr,"save: insufficient privileges [Rearrange Log Items]\n"); } processed=true; } if(verb=="saveas") { if(rda->user()->arrangeLog()) { if(cmds.size()==2) { if(cmds[1].length()>64) { fprintf(stderr,"saveas: log name too long\n"); } Saveas(cmds[1]); } else { fprintf(stderr,"saveas: invalid command arguments\n"); } } else { fprintf(stderr, "saveas: insufficient privileges [Rearrange Log Items]\n"); } processed=true; } if(verb=="setautorefresh") { if(rda->user()->arrangeLog()) { if(cmds.size()==2) { QString arg=cmds[1].lower(); if((arg=="yes")||(arg=="true")||(arg=="y")) { Setautorefresh(true); processed=true; } if((arg=="no")||(arg=="false")||(arg=="n")) { Setautorefresh(false); processed=true; } if(!processed) { fprintf(stderr,"setautorefresh: invalid command argument\n"); } } else { fprintf(stderr,"setautorefresh: invalid command arguments\n"); } } else { fprintf(stderr, "setautorefresh: insufficient privileges [Rearrange Log Items]\n"); } processed=true; } if(verb=="setcart") { if(rda->user()->arrangeLog()) { if(cmds.size()==3) { line=cmds[1].toInt(&ok); if(ok&&(line>=0)&&(line<edit_log_event->size())) { unsigned cartnum=cmds[2].toUInt(&ok); if(ok&&(cartnum<=RD_MAX_CART_NUMBER)) { Setcart(line,cartnum); } else { fprintf(stderr,"setcart: invalid cart number\n"); } } else { fprintf(stderr,"setcart: invalid line number\n"); } } else { fprintf(stderr,"setcart: invalid command arguments\n"); } } else { fprintf(stderr, "setcart: insufficient privileges [Rearrange Log Items]\n"); } processed=true; } if(verb=="setcomment") { if(rda->user()->arrangeLog()) { if(cmds.size()>=3) { line=cmds[1].toInt(&ok); if(ok&&(line>=0)&&(line<edit_log_event->size())) { cmds.remove(cmds.begin()); cmds.remove(cmds.begin()); Setcomment(line,cmds.join(" ")); } else { fprintf(stderr,"setcomment: invalid line number\n"); } } else { fprintf(stderr,"setcomment: invalid command arguments\n"); } } else { fprintf(stderr, "setcomment: insufficient privileges [Rearrange Log Items]\n"); } processed=true; } if(verb=="setdesc") { if(rda->user()->arrangeLog()) { if(cmds.size()>=2) { cmds.erase(cmds.begin()); Setdesc(cmds.join(" ")); } else { fprintf(stderr,"setdesc: invalid command arguments\n"); } } else { fprintf(stderr, "setdesc: insufficient privileges [Rearrange Log Items]\n"); } processed=true; } if(verb=="setenddate") { if(rda->user()->arrangeLog()) { if(cmds.size()==1) { Setenddate(QDate()); } else { if(cmds.size()==2) { QDate date=QDate::fromString(cmds[1],Qt::ISODate); if(date.isValid()) { Setenddate(date); } else { fprintf(stderr,"setenddate: invalid date format\n"); } } else { fprintf(stderr,"setenddate: invalid command arguments\n"); } } } else { fprintf(stderr, "setenddate: insufficient privileges [Rearrange Log Items]\n"); } processed=true; } if(verb=="setlabel") { if(rda->user()->arrangeLog()) { if(cmds.size()==3) { line=cmds[1].toInt(&ok); if(ok&&(line>=0)&&(line<edit_log_event->size())) { Setlabel(line,cmds[2]); } else { fprintf(stderr,"setlabel: invalid line number\n"); } } else { fprintf(stderr,"setlabel: invalid command arguments\n"); } } else { fprintf(stderr, "setlabel: insufficient privileges [Rearrange Log Items]\n"); } processed=true; } if(verb=="setpurgedate") { if(rda->user()->arrangeLog()) { if(cmds.size()==1) { Setpurgedate(QDate()); } else { if(cmds.size()==2) { QDate date=QDate::fromString(cmds[1],Qt::ISODate); if(date.isValid()) { Setpurgedate(date); } else { fprintf(stderr,"setpurgedate: invalid date format\n"); } } else { fprintf(stderr,"setpurgedate: invalid command arguments\n"); } } } else { fprintf(stderr, "setpurgedate: insufficient privileges [Rearrange Log Items]\n"); } processed=true; } if(verb=="setservice") { if(rda->user()->arrangeLog()) { if(cmds.size()==2) { Setservice(cmds[1]); } else { fprintf(stderr,"setservice: invalid command arguments\n"); } } else { fprintf(stderr, "setservice: insufficient privileges [Rearrange Log Items]\n"); } processed=true; } if(verb=="setstartdate") { if(rda->user()->arrangeLog()) { if(cmds.size()==1) { Setstartdate(QDate()); } else { if(cmds.size()==2) { QDate date=QDate::fromString(cmds[1],Qt::ISODate); if(date.isValid()) { Setstartdate(date); } else { fprintf(stderr,"setstartdate: invalid date format\n"); } } else { fprintf(stderr,"setstartdate: invalid command arguments\n"); } } } else { fprintf(stderr, "setstartdate: insufficient privileges [Rearrange Log Items]\n"); } processed=true; } if(verb=="settime") { if(rda->user()->arrangeLog()) { if(cmds.size()>=3) { line=cmds[1].toInt(&ok); if(ok&&(line>=0)&&(line<edit_log_event->size())) { RDLogLine::TimeType ttype=RDLogLine::NoTime; if(cmds[2].lower()=="hard") { ttype=RDLogLine::Hard; } if(cmds[2].lower()=="none") { ttype=RDLogLine::Relative; } switch(ttype) { case RDLogLine::Hard: if(cmds.size()>=4) { time=RDGetWebTime(cmds[3],&ok); if(ok) { Settime(line,ttype,time); } else { fprintf(stderr,"settime: invalid time value\n"); } } else { fprintf(stderr,"settime: missing time value\n"); } break; case RDLogLine::Relative: Settime(line,ttype); break; case RDLogLine::NoTime: fprintf(stderr,"settime: invalid time type\n"); break; } } else { fprintf(stderr,"settime: invalid line number\n"); } } else { fprintf(stderr,"settime: invalid command arguments\n"); } } else { fprintf(stderr, "settime: insufficient privileges [Rearrange Log Items]\n"); } processed=true; } if(verb=="settrans") { if(rda->user()->arrangeLog()) { if(cmds.size()==3) { line=cmds[1].toInt(&ok); if(ok&&(line>=0)&&(line<edit_log_event->size())) { RDLogLine::TransType trans=RDLogLine::NoTrans; if(cmds[2].lower()=="play") { trans=RDLogLine::Play; } if(cmds[2].lower()=="segue") { trans=RDLogLine::Segue; } if(cmds[2].lower()=="stop") { trans=RDLogLine::Stop; } if(trans!=RDLogLine::NoTrans) { Settrans(line,trans); } else { fprintf(stderr,"settrans: invalid transition type\n"); } } else { fprintf(stderr,"settrans: invalid line number\n"); } } else { fprintf(stderr,"settrans: invalid command arguments\n"); } } else { fprintf(stderr, "settrans: insufficient privileges [Rearrange Log Items]\n"); } processed=true; } if(verb=="unload") { if(overwrite) { Unload(); } else { OverwriteError("unload"); } processed=true; } } else { fprintf(stderr,"%s: no log loaded\n",(const char *)verb); processed=true; } if(!processed) { fprintf(stderr,"invalid command\n"); } PrintPrompt(); }
uint32_t ReadShellPrompt(int fd, char *buf, size_t len) { size_t total_len = 0; size_t rx_bytes; size_t i; char c; char t[2]; t[1] = '\0'; int8_t CurrCommandHistory = -1; char TmpBuf[MAX_CMD_LEN]; uint32_t CursorPos = 0; bzero(TmpBuf, MAX_CMD_LEN); while ((receive(fd, &c, 1, &rx_bytes) == 0) && total_len < len-1) { if (rx_bytes == 0) { buf[0] = '\0'; return(0); } // t[0] = c; // printf("$08x\n", t[0]); // backspace if (c == '\x7f') { if (CursorPos == total_len) { printf("\b\b\b \b\b\b"); total_len--; CursorPos--; continue; } for (i = CursorPos-1; i < total_len-1; i++) { buf[i] = buf[i+1]; } total_len--; CursorPos--; EraseLine(0); PrintPrompt(); buf[total_len] = '\0'; printf("$s", buf); CursorLeft(total_len-CursorPos); continue; } // ctrl-c if (c == '\x03') { return(0); } // ctrl-e if (c == '\x05') { // move the cursor to the end EraseLine(0); PrintPrompt(); buf[total_len] = '\0'; printf("$s", buf); CursorPos = total_len; continue; } // ctrl-u if (c == '\x15') { EraseLine(0); PrintPrompt(); total_len = 0; CursorPos = 0; continue; } // ctrl-d if (c == '\x04') { if (total_len > 0) { printf("\b\b \b\b"); continue; } else { printf("\b\b \b\b"); printf("exit "); strcpy(buf, "exit"); return(1); } } // escape codes if (c == '\x1b') { // receive the next char if (receive(fd, &c, 1, &rx_bytes) != 0) { buf[0] = '\0'; return(0); } if (rx_bytes == 0) { buf[0] = '\0'; return(0); } if (c == '\x5b') { // receive the next char if (receive(fd, &c, 1, &rx_bytes) != 0) { buf[0] = '\0'; return(0); } if (rx_bytes == 0) { buf[0] = '\0'; return(0); } if (c == '\x41') { // up arrow // if there's no command history if (ENV.NumCommandHistory == 0) { EraseLine(0); PrintPrompt(); buf[total_len] = '\0'; printf("$s", buf); CursorPos = total_len; continue; } // if we're printing the first history buf, // save the current buf in case the user // arrow's back to it if (CurrCommandHistory == -1) { buf[total_len] = '\0'; strcpy(TmpBuf, buf); } CurrCommandHistory++; if (CurrCommandHistory >= ENV.NumCommandHistory) { CurrCommandHistory = ENV.NumCommandHistory-1; } // print the next command in the history buf EraseLine(0); PrintPrompt(); strcpy(buf, ENV.CommandHistory[CurrCommandHistory]); total_len = strlen(ENV.CommandHistory[CurrCommandHistory]); CursorPos = total_len; printf("$s", ENV.CommandHistory[CurrCommandHistory]); continue; } else if (c == '\x42') { // down arrow if (CurrCommandHistory == -1) { // nothing to do EraseLine(0); PrintPrompt(); buf[total_len] = '\0'; printf("$s", buf); continue; } // see if we're at the first command in the history if (CurrCommandHistory == 0) { // go back to the user's original command EraseLine(0); PrintPrompt(); strcpy(buf, TmpBuf); total_len = strlen(buf); CursorPos = total_len; printf("$s", buf); CurrCommandHistory = -1; continue; } // print the next command in the history CurrCommandHistory--; EraseLine(0); PrintPrompt(); strcpy(buf, ENV.CommandHistory[CurrCommandHistory]); total_len = strlen(ENV.CommandHistory[CurrCommandHistory]); CursorPos = total_len; printf("$s", ENV.CommandHistory[CurrCommandHistory]); continue; } else if (c == '\x43') { // right arrow if (CursorPos == total_len) { // nothing to do but remove the arrow control chars EraseLine(0); PrintPrompt(); buf[total_len] = '\0'; printf("$s", buf); continue; } // not at the end of the line, so move the cursor // right one character CursorPos++; EraseLine(0); PrintPrompt(); buf[total_len] = '\0'; printf("$s", buf); if (total_len != CursorPos) { CursorLeft(total_len-CursorPos); } continue; } else if (c == '\x44') { // left arrow if (CursorPos == 0) { // nothing to do, re-print the line (to remove the control chars) EraseLine(0); PrintPrompt(); buf[total_len] = '\0'; printf("$s", buf); CursorLeft(total_len); continue; } // not at the beginning of the line, so move the cursor // left one character CursorPos--; EraseLine(0); PrintPrompt(); buf[total_len] = '\0'; printf("$s", buf); CursorLeft(total_len-CursorPos); continue; } } } if (c == '\r') { buf[CursorPos] = '\0'; break; } if (c == '\n') { // receive the corresponding '\r' if (receive(fd, &c, 1, &rx_bytes) != 0) { buf[0] = '\0'; return(0); } if (rx_bytes == 0) { buf[0] = '\0'; return(0); } if (c != '\r') { buf[0] = '\0'; return(0); } buf[CursorPos] = '\0'; // EraseToEOL(); break; } if (CursorPos == total_len) { buf[total_len++] = c; CursorPos++; } else { buf[CursorPos++] = c; } } if (rx_bytes == 0) { buf[0] = '\0'; return(0); } buf[total_len] = '\0'; return(total_len); }
/* read in a command line */ BOOL ReadCommand(LPTSTR str, INT maxlen) { CONSOLE_SCREEN_BUFFER_INFO csbi; SHORT orgx; /* origin x/y */ SHORT orgy; SHORT curx; /*current x/y cursor position*/ SHORT cury; SHORT tempscreen; INT count; /*used in some for loops*/ INT current = 0; /*the position of the cursor in the string (str)*/ INT charcount = 0;/*chars in the string (str)*/ INPUT_RECORD ir; #ifdef FEATURE_UNIX_FILENAME_COMPLETION WORD wLastKey = 0; #endif TCHAR ch; BOOL bReturn = FALSE; BOOL bCharInput; #ifdef FEATURE_4NT_FILENAME_COMPLETION TCHAR szPath[MAX_PATH]; #endif #ifdef FEATURE_HISTORY //BOOL bContinue=FALSE;/*is TRUE the second case will not be executed*/ TCHAR PreviousChar; #endif if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) { /* No console */ HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); DWORD dwRead; CHAR chr; do { if (!ReadFile(hStdin, &chr, 1, &dwRead, NULL) || !dwRead) return FALSE; #ifdef _UNICODE MultiByteToWideChar(InputCodePage, 0, &chr, 1, &str[charcount++], 1); #endif } while (chr != '\n' && charcount < maxlen); str[charcount] = _T('\0'); return TRUE; } /* get screen size */ maxx = csbi.dwSize.X; maxy = csbi.dwSize.Y; curx = orgx = csbi.dwCursorPosition.X; cury = orgy = csbi.dwCursorPosition.Y; memset (str, 0, maxlen * sizeof (TCHAR)); SetCursorType (bInsert, TRUE); do { bReturn = FALSE; ConInKey (&ir); if (ir.Event.KeyEvent.dwControlKeyState & (RIGHT_ALT_PRESSED |LEFT_ALT_PRESSED| RIGHT_CTRL_PRESSED|LEFT_CTRL_PRESSED) ) { switch (ir.Event.KeyEvent.wVirtualKeyCode) { #ifdef FEATURE_HISTORY case 'K': /*add the current command line to the history*/ if (ir.Event.KeyEvent.dwControlKeyState & (LEFT_CTRL_PRESSED|RIGHT_CTRL_PRESSED)) { if (str[0]) History(0,str); ClearCommandLine (str, maxlen, orgx, orgy); current = charcount = 0; curx = orgx; cury = orgy; //bContinue=TRUE; break; } case 'D': /*delete current history entry*/ if (ir.Event.KeyEvent.dwControlKeyState & (LEFT_CTRL_PRESSED|RIGHT_CTRL_PRESSED)) { ClearCommandLine (str, maxlen, orgx, orgy); History_del_current_entry(str); current = charcount = _tcslen (str); ConOutPrintf (_T("%s"), str); GetCursorXY (&curx, &cury); //bContinue=TRUE; break; } #endif /*FEATURE_HISTORY*/ } } bCharInput = FALSE; switch (ir.Event.KeyEvent.wVirtualKeyCode) { case VK_BACK: /* <BACKSPACE> - delete character to left of cursor */ if (current > 0 && charcount > 0) { if (current == charcount) { /* if at end of line */ str[current - 1] = _T('\0'); if (GetCursorX () != 0) { ConOutPrintf (_T("\b \b")); curx--; } else { SetCursorXY ((SHORT)(maxx - 1), (SHORT)(GetCursorY () - 1)); ConOutChar (_T(' ')); SetCursorXY ((SHORT)(maxx - 1), (SHORT)(GetCursorY () - 1)); cury--; curx = maxx - 1; } } else { for (count = current - 1; count < charcount; count++) str[count] = str[count + 1]; if (GetCursorX () != 0) { SetCursorXY ((SHORT)(GetCursorX () - 1), GetCursorY ()); curx--; } else { SetCursorXY ((SHORT)(maxx - 1), (SHORT)(GetCursorY () - 1)); cury--; curx = maxx - 1; } GetCursorXY (&curx, &cury); ConOutPrintf (_T("%s "), &str[current - 1]); SetCursorXY (curx, cury); } charcount--; current--; } break; case VK_INSERT: /* toggle insert/overstrike mode */ bInsert ^= TRUE; SetCursorType (bInsert, TRUE); break; case VK_DELETE: /* delete character under cursor */ if (current != charcount && charcount > 0) { for (count = current; count < charcount; count++) str[count] = str[count + 1]; charcount--; GetCursorXY (&curx, &cury); ConOutPrintf (_T("%s "), &str[current]); SetCursorXY (curx, cury); } break; case VK_HOME: /* goto beginning of string */ if (current != 0) { SetCursorXY (orgx, orgy); curx = orgx; cury = orgy; current = 0; } break; case VK_END: /* goto end of string */ if (current != charcount) { SetCursorXY (orgx, orgy); ConOutPrintf (_T("%s"), str); GetCursorXY (&curx, &cury); current = charcount; } break; case VK_TAB: #ifdef FEATURE_UNIX_FILENAME_COMPLETION /* expand current file name */ if ((current == charcount) || (current == charcount - 1 && str[current] == _T('"'))) /* only works at end of line*/ { if (wLastKey != VK_TAB) { /* if first TAB, complete filename*/ tempscreen = charcount; CompleteFilename (str, charcount); charcount = _tcslen (str); current = charcount; SetCursorXY (orgx, orgy); ConOutPrintf (_T("%s"), str); if (tempscreen > charcount) { GetCursorXY (&curx, &cury); for (count = tempscreen - charcount; count--; ) ConOutChar (_T(' ')); SetCursorXY (curx, cury); } else { if (((charcount + orgx) / maxx) + orgy > maxy - 1) orgy += maxy - ((charcount + orgx) / maxx + orgy + 1); } /* set cursor position */ SetCursorXY ((orgx + current) % maxx, orgy + (orgx + current) / maxx); GetCursorXY (&curx, &cury); } else { /*if second TAB, list matches*/ if (ShowCompletionMatches (str, charcount)) { PrintPrompt(); GetCursorXY(&orgx, &orgy); ConOutPrintf(_T("%s"), str); /* set cursor position */ SetCursorXY((orgx + current) % maxx, orgy + (orgx + current) / maxx); GetCursorXY(&curx, &cury); } } } else { MessageBeep(-1); } #endif #ifdef FEATURE_4NT_FILENAME_COMPLETION /* used to later see if we went down to the next line */ tempscreen = charcount; szPath[0]=_T('\0'); /* str is the whole things that is on the current line that is and and out. arg 2 is weather it goes back one file or forward one file */ CompleteFilename(str, !(ir.Event.KeyEvent.dwControlKeyState & SHIFT_PRESSED), szPath, current); /* Attempt to clear the line */ ClearCommandLine (str, maxlen, orgx, orgy); curx = orgx; cury = orgy; current = charcount = 0; /* Everything is deleted, lets add it back in */ _tcscpy(str,szPath); /* Figure out where cusor is going to be after we print it */ charcount = _tcslen(str); current = charcount; SetCursorXY(orgx, orgy); /* Print out what we have now */ ConOutPrintf(_T("%s"), str); /* Move cursor accordingly */ if (tempscreen > charcount) { GetCursorXY(&curx, &cury); for(count = tempscreen - charcount; count--; ) ConOutChar(_T(' ')); SetCursorXY(curx, cury); } else { if (((charcount + orgx) / maxx) + orgy > maxy - 1) orgy += maxy - ((charcount + orgx) / maxx + orgy + 1); } SetCursorXY((short)(((int)orgx + current) % maxx), (short)((int)orgy + ((int)orgx + current) / maxx)); GetCursorXY(&curx, &cury); #endif break; case _T('M'): case _T('C'): /* ^M does the same as return */ bCharInput = TRUE; if (!(ir.Event.KeyEvent.dwControlKeyState & (RIGHT_CTRL_PRESSED|LEFT_CTRL_PRESSED))) { break; } case VK_RETURN: /* end input, return to main */ #ifdef FEATURE_HISTORY /* add to the history */ if (str[0]) History (0, str); #endif str[charcount++] = _T('\n'); str[charcount] = _T('\0'); ConOutChar(_T('\n')); bReturn = TRUE; break; case VK_ESCAPE: /* clear str Make this callable! */ ClearCommandLine (str, maxlen, orgx, orgy); curx = orgx; cury = orgy; current = charcount = 0; break; #ifdef FEATURE_HISTORY case VK_F3: History_move_to_bottom(); #endif case VK_UP: #ifdef FEATURE_HISTORY /* get previous command from buffer */ ClearCommandLine (str, maxlen, orgx, orgy); History (-1, str); current = charcount = _tcslen (str); if (((charcount + orgx) / maxx) + orgy > maxy - 1) orgy += maxy - ((charcount + orgx) / maxx + orgy + 1); ConOutPrintf (_T("%s"), str); GetCursorXY (&curx, &cury); #endif break; case VK_DOWN: #ifdef FEATURE_HISTORY /* get next command from buffer */ ClearCommandLine (str, maxlen, orgx, orgy); History (1, str); current = charcount = _tcslen (str); if (((charcount + orgx) / maxx) + orgy > maxy - 1) orgy += maxy - ((charcount + orgx) / maxx + orgy + 1); ConOutPrintf (_T("%s"), str); GetCursorXY (&curx, &cury); #endif break; case VK_LEFT: /* move cursor left */ if (current > 0) { current--; if (GetCursorX () == 0) { SetCursorXY ((SHORT)(maxx - 1), (SHORT)(GetCursorY () - 1)); curx = maxx - 1; cury--; } else { SetCursorXY ((SHORT)(GetCursorX () - 1), GetCursorY ()); curx--; } } else { MessageBeep (-1); } break; case VK_RIGHT: /* move cursor right */ if (current != charcount) { current++; if (GetCursorX () == maxx - 1) { SetCursorXY (0, (SHORT)(GetCursorY () + 1)); curx = 0; cury++; } else { SetCursorXY ((SHORT)(GetCursorX () + 1), GetCursorY ()); curx++; } } #ifdef FEATURE_HISTORY else { LPCTSTR last = PeekHistory(-1); if (last && charcount < (INT)_tcslen (last)) { PreviousChar = last[current]; ConOutChar(PreviousChar); GetCursorXY(&curx, &cury); str[current++] = PreviousChar; charcount++; } } #endif break; default: /* This input is just a normal char */ bCharInput = TRUE; } #ifdef _UNICODE ch = ir.Event.KeyEvent.uChar.UnicodeChar; if (ch >= 32 && (charcount != (maxlen - 2)) && bCharInput) #else ch = ir.Event.KeyEvent.uChar.AsciiChar; if ((UCHAR)ch >= 32 && (charcount != (maxlen - 2)) && bCharInput) #endif /* _UNICODE */ { /* insert character into string... */ if (bInsert && current != charcount) { /* If this character insertion will cause screen scrolling, * adjust the saved origin of the command prompt. */ tempscreen = _tcslen(str + current) + curx; if ((tempscreen % maxx) == (maxx - 1) && (tempscreen / maxx) + cury == (maxy - 1)) { orgy--; cury--; } for (count = charcount; count > current; count--) str[count] = str[count - 1]; str[current++] = ch; if (curx == maxx - 1) curx = 0, cury++; else curx++; ConOutPrintf (_T("%s"), &str[current - 1]); SetCursorXY (curx, cury); charcount++; } else { if (current == charcount) charcount++; str[current++] = ch; if (GetCursorX () == maxx - 1 && GetCursorY () == maxy - 1) orgy--, cury--; if (GetCursorX () == maxx - 1) curx = 0, cury++; else curx++; ConOutChar (ch); } } //wLastKey = ir.Event.KeyEvent.wVirtualKeyCode; } while (!bReturn); SetCursorType (bInsert, TRUE); #ifdef FEATURE_ALIASES /* expand all aliases */ ExpandAlias (str, maxlen); #endif /* FEATURE_ALIAS */ return TRUE; }