Commit 32d0e206 authored by jan.koester's avatar jan.koester
Browse files

bugfix

parent 960d322e
Loading
Loading
Loading
Loading
+94 −2
Changes for src/shell.cpp: 94 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -584,9 +584,19 @@ std::vector<std::string> fresh::tokenizeShellArgs(const std::string &segment,boo
                ++j;
            if(j<n && (segment[j]=='>' || segment[j]=='<')){
                std::string fdprefix=segment.substr(i,j-i);
                if(segment[j]=='<'){
                if(segment[j]=='<' && j+2<n && segment[j+1]=='&' &&
                   (isdigit((unsigned char)segment[j+2]) || segment[j+2]=='-')){
                    size_t k=j+2;
                    if(segment[k]=='-') ++k;
                    else while(k<n && isdigit((unsigned char)segment[k])) ++k;
                    tokens.push_back(opTok(fdprefix+"<&"+segment.substr(j+2,k-(j+2))));
                    i=k;
                }else if(segment[j]=='<'){
                    tokens.push_back(opTok(fdprefix+"<"));
                    i=j+1;
                }else if(j+2<n && segment[j+1]=='&' && segment[j+2]=='-'){
                    tokens.push_back(opTok(fdprefix+">&-"));
                    i=j+3;
                }else if(j+1<n && segment[j+1]=='>'){
                    tokens.push_back(opTok(fdprefix+">>"));
                    i=j+2;
@@ -623,6 +633,17 @@ std::vector<std::string> fresh::tokenizeShellArgs(const std::string &segment,boo
                i=k;
                continue;
            }
            // ">&-", "<&N", "<&-": the same normalization to an explicit
            // fd number (1 for '>', 0 for '<')
            if(i+2<n && segment[i+1]=='&' &&
               (segment[i+2]=='-' || (c=='<' && isdigit((unsigned char)segment[i+2])))){
                size_t k=i+2;
                if(segment[k]=='-') ++k;
                else while(k<n && isdigit((unsigned char)segment[k])) ++k;
                tokens.push_back(opTok(std::string(c=='>' ? "1>&" : "0<&")+segment.substr(i+2,k-(i+2))));
                i=k;
                continue;
            }
            if(c=='>' && i+1<n && segment[i+1]=='>'){
                tokens.push_back(opTok(">>"));
                i+=2;
@@ -2883,12 +2904,70 @@ std::vector<std::string> fresh::extractRedirections(const std::vector<std::strin
            ++i;
            continue;
        }
        int target,source;
        if(parseFdDup(t,target,source)){
            redir.dups.emplace_back(target,source);
            continue;
        }
        cleaned.push_back(t);
    }

    return cleaned;
}

bool fresh::parseFdDup(const std::string &tok,int &target,int &source){
    size_t i=0,n=tok.size();
    while(i<n && isdigit((unsigned char)tok[i])) ++i;
    if(i+2>n || (tok[i]!='>' && tok[i]!='<') || tok[i+1]!='&') return false;
    char dir=tok[i];
    std::string fd=tok.substr(0,i),src=tok.substr(i+2);
    if(src.empty()) return false;
    if(src=="-") source=-1;
    else{
        for(char ch : src) if(!isdigit((unsigned char)ch)) return false;
        source=std::atoi(src.c_str());
    }
    target=fd.empty() ? (dir=='>' ? 1 : 0) : std::atoi(fd.c_str());
    return true;
}

bool fresh::applyFdDups(const std::vector<std::pair<int,int> > &dups,
                        std::vector<std::pair<int,int> > *saved){
    std::cout.flush();
    std::cerr.flush();
    for(const auto &d : dups){
        int target=d.first,source=d.second;
        if(source>=0 && fcntl(source,F_GETFD)<0){
            std::cerr << "fresh: " << source << ": bad file descriptor" << std::endl;
            return false;
        }
        if(saved){
            bool known=false;
            for(const auto &s : *saved) if(s.first==target) known=true;
            // the copy must not land on an fd a later dup names: >= 10,
            // like other shells keep their saved descriptors
            if(!known) saved->emplace_back(target,fcntl(target,F_DUPFD_CLOEXEC,10));
        }
        if(source<0) close(target);
        else if(source!=target) dup2(source,target);
    }
    return true;
}

void fresh::restoreFdDups(std::vector<std::pair<int,int> > &saved){
    std::cout.flush();
    std::cerr.flush();
    for(auto it=saved.rbegin(); it!=saved.rend(); ++it){
        if(it->second>=0){
            dup2(it->second,it->first);
            close(it->second);
        }else{
            close(it->first);
        }
    }
    saved.clear();
}

bool fresh::extractHeredocSpec(std::string &text,fresh::HeredocSpec &spec){
    size_t i=0,n=text.length();

@@ -3005,6 +3084,10 @@ bool fresh::CompoundRedirect::apply(const std::string &trailing,std::string &res
        return fail(r.stderrFile);
    if(r.stderrToStdout) redirect(2,dup(1),_err);
    if(r.stdoutToStderr) redirect(1,dup(2),_out);
    if(!applyFdDups(r.dups,&_dupSaved)){
        restore();
        return false;
    }
    rest=after;
    return true;
}
@@ -3012,6 +3095,7 @@ bool fresh::CompoundRedirect::apply(const std::string &trailing,std::string &res
void fresh::CompoundRedirect::restore(){
    std::cout.flush();
    std::cerr.flush();
    restoreFdDups(_dupSaved);
    if(_in>=0){ dup2(_in,0); close(_in); _in=-1; }
    if(_out>=0){ dup2(_out,1); close(_out); _out=-1; }
    if(_err>=0){ dup2(_err,2); close(_err); _err=-1; }
@@ -3381,6 +3465,8 @@ void fresh::Shell::runStageChild(const std::vector<std::string> &tokens,const Re
        dup2(1,2);
    if(redir.stdoutToStderr)
        dup2(2,1);
    if(!applyFdDups(redir.dups,nullptr))
        _exit(1);

    // "(cmds) redirection" subshell group (see extractSubshellBody()):
    // already forked (every stage here runs in its own child regardless),
@@ -3663,7 +3749,8 @@ int fresh::Shell::runSegmentWords(const std::string &input,const std::vector<She
            const std::string &t=words[redirEnd].text;
            bool takesArg=(t==">" || t==">>" || t=="1>" || t=="1>>" ||
                           t=="<" || t=="0<" || t=="2>" || t=="2>>");
            bool noArg=(t=="2>&1" || t=="1>&2");
            int dupTarget,dupSource;
            bool noArg=(t=="2>&1" || t=="1>&2" || parseFdDup(t,dupTarget,dupSource));
            if(takesArg && redirEnd+1<to){
                redirTokens.push_back(t);
                // the target word is raw text here ("${depfile}" with its
@@ -3715,10 +3802,14 @@ int fresh::Shell::runSegmentWords(const std::string &input,const std::vector<She
                if(savedStdout<0) savedStdout=dup(1);
                dup2(2,1);
            }
            std::vector<std::pair<int,int> > dupSaved;
            bool dupFailed=!openFailed && !applyFdDups(redir.dups,&dupSaved);

            if(openFailed){
                std::cerr << "fresh: " << openFailMsg << ": " << strerror(errno) << std::endl;
                status=1;
            }else if(dupFailed){
                status=1;
            }else{
                status=parse(body);
            }
@@ -3743,6 +3834,7 @@ int fresh::Shell::runSegmentWords(const std::string &input,const std::vector<She
            std::cout.flush();
            std::cerr.flush();

            restoreFdDups(dupSaved);
            if(savedStdin>=0){ dup2(savedStdin,0); close(savedStdin); }
            if(savedStdout>=0){ dup2(savedStdout,1); close(savedStdout); }
            if(savedStderr>=0){ dup2(savedStderr,2); close(savedStderr); }
+19 −1
Changes for src/shell.h: 19 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -139,13 +139,30 @@ namespace fresh {
        bool stderrAppend;
        bool stderrToStdout;
        bool stdoutToStderr;
        // every other fd duplication, in order: "N>&M"/"N<&M" make fd N a
        // copy of fd M, "N>&-"/"N<&-" close fd N (source -1). Applied after
        // the file redirections above.
        std::vector<std::pair<int,int> > dups;

        Redirection():hasStdin(false),hasStdout(false),append(false),
                      hasStderr(false),stderrAppend(false),stderrToStdout(false),
                      stdoutToStderr(false){}
        bool any() const{ return hasStdin || hasStdout || hasStderr || stderrToStdout || stdoutToStderr; }
        bool any() const{ return hasStdin || hasStdout || hasStderr || stderrToStdout || stdoutToStderr || !dups.empty(); }
    };

    // "N>&M", "N<&M", "N>&-", "N<&-" (an optional fd number, '>' or '<',
    // '&', then a fd number or '-'); without N, '>' means 1 and '<' 0.
    // source is -1 for '-'.
    bool parseFdDup(const std::string &tok,int &target,int &source);

    // Applies Redirection::dups in order. With `saved`, the previous state
    // of every fd changed is recorded first (dup of it, or -1 if it was
    // closed) so restoreFdDups() can put it back. False (with a message)
    // if a source fd is not open.
    bool applyFdDups(const std::vector<std::pair<int,int> > &dups,
                     std::vector<std::pair<int,int> > *saved);
    void restoreFdDups(std::vector<std::pair<int,int> > &saved);

    // Splits a simple-command segment on top-level '|' (quote-aware, so a
    // '|' inside '...' or "..." does not start a new stage). Each returned
    // stage still needs tokenizeShellArgs() + extractRedirections().
@@ -311,6 +328,7 @@ namespace fresh {
    private:
        bool redirect(int target,int fd,int &saved);
        int _in=-1,_out=-1,_err=-1;
        std::vector<std::pair<int,int> > _dupSaved;
        std::string _heredocTemp;
    };