msh-console/library/shell.cpp

338 lines
10 KiB
C++

/**
MIT License
Copyright (c) 2016 Claudio Maggioni
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "shell.h"
namespace mshconsole {
const std::string& Shell::getPs() const{
return ps;
}
void Shell::setPs(const std::string &value){
ps = value;
}
const std::string& Shell::getName() const{
return name;
}
void Shell::setName(const std::string &value){
name = value;
}
Shell::Shell(std::string nam, std::string ps, std::istream &i, std::ostream &o, std::ostream &e,
void (*s)(Shell*), void (*pss)(Shell*)) : cmds(this), inputStream(i),
outputStream(o), errorStream(e){
shellSetup = s;
name = nam;
this->ps = ps;
shellPostSetup = pss;
}
int Shell::launch(){
//Forbid launching shell if it is already launched in other threads.
static bool notLoop=false;
if(notLoop) return -1;
notLoop = true;
//Launch the shell setup.
if(shellSetup!=0) (*shellSetup)(this);
//Run the shell loop.
int exitCode;
std::string* line=nullptr;
std::vector<std::string> p;
try{
while(1){
delete line;
outputStream << ps << " "; //Print the prompt.
//Try reading the line. if SIGINT is caught, print another time the prompt and retry.
try{
line = readLine();
}
catch (IsUndoingLineException){
outputStream << "\n";
continue;
}
//Try line conversion from string to argc and argv. stringToArgcArgv() throws a std::runtime_error
//exception if the string has unproper quotes.
try{
p = splitLine(line);
}
catch(std::runtime_error e){
errorStream << name << ": error in line parsing\n";
errorStream << e.what() << "\n";
continue;
}
//Execute the pipe.
executePipe(p);
};
} catch(CommandExecutor::ExitException c) {
delete line;
exitCode=c.getCode();
}
//Launch postSetup().
if(shellPostSetup!=0) shellPostSetup(this);
notLoop = false;
return exitCode;
}
int Shell::executePipe(std::vector<std::string>& argv)
{
int newPipe[2], oldPipe[2], status;
pid_t pid;
std::vector<std::vector<std::string>> argvs;
size_t c=0, i=0;
for(; i<argv.size(); i++){
if(argv[i]=="|"){ //Pipe reached
if(c!=i){
//Write the command in the pipe std::vector
argvs.push_back(std::vector<std::string>(argv.begin()+c, argv.begin()+i));
}
c=i+1;
}
}
if(c!=i){
//Write the last command in the pipe std::vector
argvs.push_back(std::vector<std::string>(argv.begin()+c, argv.end()));
}
if(argvs.size()==1){
struct Params p;
vectorToArgcArgv(argvs[0], &p.argc, &p.argv);
return executeCmd(p,false);
}
for(size_t i=0; i<argvs.size(); i++){
if(cmds.found(std::string(argvs[i][0]),false)){
errorStream << name << ": non-thread command " << argv[0] << " can't be launched from a pipe" << std::endl;
return 1;
}
}
for(size_t i=0; i<argvs.size(); i++) /* For each command */
{
struct Params p;
vectorToArgcArgv(argvs[i], &p.argc, &p.argv);
/* If there still are commands to be executed */
if(i < argvs.size()-1)
{
pipe(newPipe); /* just create a pipe */
}
pid = fork();
if(pid == 0) /* Child */
{
/* If there is a previous command */
if(i > 0)
{
close(oldPipe[1]);
dup2(oldPipe[0], 0); //redirect stdin to input of the pipe
close(oldPipe[0]);
}
/* If there still are commands to be executed */
if(i < argvs.size()-1)
{
close(newPipe[0]);
dup2(newPipe[1], 1); //redirect stdout to output of the pipe
close(newPipe[1]);
}
//Execute
exit(executeCmd(p,true));
}
else if (pid < 0) {
// Error forking
errorStream << name <<": error in process forking.\n";
}
else /* Father */
{
/* If there is a previous command */
if(i > 0)
{
close(oldPipe[0]);
close(oldPipe[1]);
}
/* do we have a next command? */
if(i < argvs.size()-1)
{
oldPipe[0] = newPipe[0];
oldPipe[1] = newPipe[1];
}
/* wait for last command process? */
if(i == argvs.size()-1)
{
waitpid(pid, &status, 0);
}
}
deleteParams(p);
}
return 0;
}
int Shell::launchCmd(const struct Params& p){
int status;
pid_t pid = fork();
if (pid == 0) {
//child process
//execute threadCommand
int a;
try {
a=cmds.launch(p, true);
std::exit(EXIT_SUCCESS);
}
catch (CommandNotFoundException){}
//execute bash command or program
a=execvp(p.argv[0], p.argv);
if(a == -1) {
outputStream << name << ": execution failed. Errno is set to: "<<strerror(errno)<<"\n";
std::exit(EXIT_FAILURE);
}
else std::exit(EXIT_SUCCESS);
}
else if (pid < 0) {
// Error forking
errorStream << name <<": error in process forking.\n";
}
else {
// Parent process
do {
//wait until child finished
waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
return 1;
}
int Shell::executeCmd(const struct Params& p, bool isPipe){
if (!p.argc) return 1; //Return if the line is empty.
if(isPipe){
if(cmds.found(p.argv[0],false)){
errorStream << name << ": non-thread command " << p.argv[0] << " can't be launched from a pipe" << std::endl;
return 1;
}
}
else{
try {
//Search in non-thread commands.
return cmds.launch(p, false);
}
catch(CommandNotFoundException) {}
}
//Execute the threadCommand or the executable.
return launchCmd(p);
}
inline int Shell::executeCmd(const std::string &args){
std::vector<std::string>a =splitLine(&args);
return executePipe(a);
}
void Shell::SIGINTHandler(int,siginfo_t*, void *){
SIGINTRaised = true;
}
void Shell::setShellSetup(void (*s)(Shell *)){
shellSetup=s;
}
void (*Shell::getShellSetup())(Shell*) const{
return shellSetup;
}
void Shell::setShellPostSetup(void (*s)(Shell *)){
shellPostSetup=s;
}
void (*Shell::getShellPostSetup())(Shell*) const{
return shellPostSetup;
}
struct sigaction* setHandler(unsigned signal, void (*funcptr)(int, siginfo_t*, void*)){
struct sigaction* before = new struct sigaction();
struct sigaction sa;
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGTERM);
sa.sa_mask=mask;
sa.sa_sigaction = funcptr;
sa.sa_flags = SA_RESTART;
sigaction(signal, &sa, before);
return before;
}
void restoreHandler(unsigned signal, struct sigaction* before){
sigaction(signal, before, NULL);
delete before;
}
std::string* Shell::readLine(){
std::string* buffer = new std::string();
struct sigaction* beforeSIGINT = setHandler(SIGINT,SIGINTHandler);
getline(inputStream,*buffer); //Get line of input TODO: handle directional keys
inputStream.clear(); //Clear flags. This is needed for the detection of SIGINT
if(SIGINTRaised){
SIGINTRaised=false;
throw IsUndoingLineException();
}
restoreHandler(SIGINT, beforeSIGINT);
return buffer;
}
std::vector<std::string> Shell::splitLine(const std::string* line){
return parseStringToVector(*line);
}
void Shell::deleteParams(struct Params p){
freeString(p.argc,p.argv);
}
bool Shell::SIGINTRaised = false;
void Shell::addCmd(Command* cmd, bool isthread){
cmds.add(cmd, isthread);
}
size_t Shell::howManyCmds() const{
return cmds.howMany();
}
}