Commit 035883c0 authored by jan.koester's avatar jan.koester
Browse files

timeout added

parent 9b1a2112
Loading
Loading
Loading
Loading
+2 −1
Changes for commands/system/CMakeLists.txt: 2 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -30,8 +30,9 @@ target_sources(fresh PRIVATE
  ${CMAKE_CURRENT_SOURCE_DIR}/gzip.cpp
  ${CMAKE_CURRENT_SOURCE_DIR}/xz.cpp
  ${CMAKE_CURRENT_SOURCE_DIR}/nproc.cpp
  ${CMAKE_CURRENT_SOURCE_DIR}/sysutils.cpp
)

set(FRESH_APPLETS ${FRESH_APPLETS} uname whoami hostname id date sleep env true false clear kill
    mount umount mknod switch_root cpio mkinitramfs losetup blkid
    halt reboot poweroff sysctl swapon swapoff pivot_root fsck mkswap hwclock ps tar gzip gunzip zcat xz nproc PARENT_SCOPE)
    halt reboot poweroff sysctl swapon swapoff pivot_root fsck mkswap hwclock ps tar gzip gunzip zcat xz nproc timeout tty logname PARENT_SCOPE)
+211 −0
Changes for commands/system/sysutils.cpp: 211 added lines, 0 removed lines.
Original line number Diff line number Diff line
/*******************************************************************************
Copyright (c) 2026, Jan Koester jan.koester@gmx.net
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/


// Process/session utilities: timeout, tty, logname.

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cerrno>
#include <csignal>
#include <ctime>

#include <unistd.h>
#include <sys/wait.h>

#include "shell.h"
#include "../text/textutil.h"

namespace fresh { namespace cmd {

    namespace {
        struct SigName { const char *name; int num; };
        const SigName kSignals[]={
            {"HUP",SIGHUP},{"INT",SIGINT},{"QUIT",SIGQUIT},{"ILL",SIGILL},{"TRAP",SIGTRAP},
            {"ABRT",SIGABRT},{"BUS",SIGBUS},{"FPE",SIGFPE},{"KILL",SIGKILL},{"USR1",SIGUSR1},
            {"SEGV",SIGSEGV},{"USR2",SIGUSR2},{"PIPE",SIGPIPE},{"ALRM",SIGALRM},{"TERM",SIGTERM},
            {"CHLD",SIGCHLD},{"CONT",SIGCONT},{"STOP",SIGSTOP},{"TSTP",SIGTSTP},{"TTIN",SIGTTIN},
            {"TTOU",SIGTTOU},{"URG",SIGURG},{"XCPU",SIGXCPU},{"XFSZ",SIGXFSZ},{"VTALRM",SIGVTALRM},
            {"PROF",SIGPROF},{"WINCH",SIGWINCH},{"IO",SIGIO},{"SYS",SIGSYS}
        };
        int parseSignal(std::string s){
            if(s.empty()) return -1;
            if(isdigit((unsigned char)s[0])){
                char *e; long v=strtol(s.c_str(),&e,10);
                return *e || v<0 || v>64 ? -1 : (int)v;
            }
            for(auto &c: s) c=(char)toupper((unsigned char)c);
            if(s.compare(0,3,"SIG")==0) s=s.substr(3);
            for(auto &k: kSignals) if(s==k.name) return k.num;
            return -1;
        }
        // "1.5", "10s", "2m", "1h", "1d"; -1 on error
        double parseDuration(const std::string &s){
            if(s.empty()) return -1;
            char *e;
            double v=strtod(s.c_str(),&e);
            if(e==s.c_str() || v<0) return -1;
            std::string suf=e;
            if(suf.empty() || suf=="s") return v;
            if(suf=="m") return v*60;
            if(suf=="h") return v*3600;
            if(suf=="d") return v*86400;
            return -1;
        }
        double now(){
            struct timespec ts;
            clock_gettime(CLOCK_MONOTONIC,&ts);
            return (double)ts.tv_sec+(double)ts.tv_nsec/1e9;
        }
    }

    // timeout [-s SIGNAL] [-k DURATION] [--preserve-status] [--foreground] [-v] DURATION COMMAND [ARG]...
    // exit 124 on timeout, 125 on own failure, 126/127 if COMMAND can't run
    class TimeoutCommand : public ShellCommand {
    public:
        TimeoutCommand():ShellCommand("timeout"){}
        int runCommand(int argc,const char **argv){
            int sig=SIGTERM;
            double killAfter=-1;
            bool preserve=false,verbose=false;
            int i=1;
            for(;i<argc;++i){
                std::string a=argv[i];
                if(a=="--"){ ++i; break; }
                if(a.size()<2 || a[0]!='-' || isdigit((unsigned char)a[1])) break;
                std::string val;
                auto need=[&](const std::string &inl)->bool{
                    if(!inl.empty()){ val=inl; return true; }
                    if(i+1>=argc){ std::cerr << "timeout: option requires an argument -- '" << a << "'" << std::endl; return false; }
                    val=argv[++i]; return true;
                };
                if(a=="--preserve-status"){ preserve=true; continue; }
                if(a=="--foreground"){ continue; }
                if(a=="--verbose" || a=="-v"){ verbose=true; continue; }
                if(a.compare(0,9,"--signal=")==0 || a=="--signal" || a.compare(0,2,"-s")==0){
                    std::string inl=a.compare(0,9,"--signal=")==0 ? a.substr(9) : a.compare(0,2,"-s")==0 ? a.substr(2) : "";
                    if(!need(inl)) return 125;
                    sig=parseSignal(val);
                    if(sig<0){ std::cerr << "timeout: " << val << ": invalid signal" << std::endl; return 125; }
                    continue;
                }
                if(a.compare(0,13,"--kill-after=")==0 || a=="--kill-after" || a.compare(0,2,"-k")==0){
                    std::string inl=a.compare(0,13,"--kill-after=")==0 ? a.substr(13) : a.compare(0,2,"-k")==0 ? a.substr(2) : "";
                    if(!need(inl)) return 125;
                    killAfter=parseDuration(val);
                    if(killAfter<0){ std::cerr << "timeout: invalid time interval '" << val << "'" << std::endl; return 125; }
                    continue;
                }
                std::cerr << "timeout: invalid option -- '" << a.substr(1) << "'" << std::endl;
                return 125;
            }
            if(i+1>=argc){ std::cerr << "timeout: missing operand" << std::endl; return 125; }
            double dur=parseDuration(argv[i]);
            if(dur<0){ std::cerr << "timeout: invalid time interval '" << argv[i] << "'" << std::endl; return 125; }
            ++i;
            std::cout.flush(); std::cerr.flush();
            pid_t pid=fork();
            if(pid<0){ std::cerr << "timeout: fork system call failed: " << strerror(errno) << std::endl; return 125; }
            if(pid==0){
                signal(SIGTTIN,SIG_DFL); signal(SIGTTOU,SIG_DFL);
                execvp(argv[i],const_cast<char *const *>(argv+i));
                int e=errno;
                std::cerr << "timeout: failed to run command '" << argv[i] << "': " << strerror(e) << std::endl;
                _exit(e==ENOENT ? 127 : 126);
            }
            double start=now();
            bool timedOut=false,killed=false;
            double deadline=dur>0 ? start+dur : -1;
            int status=0;
            for(;;){
                pid_t r=waitpid(pid,&status,WNOHANG);
                if(r==pid) break;
                if(r<0 && errno!=EINTR){ status=0; break; }
                double t=now();
                if(deadline>0 && t>=deadline){
                    if(!timedOut){
                        timedOut=true;
                        if(verbose) std::cerr << "timeout: sending signal " << strsignal(sig) << " to command '" << argv[i] << "'" << std::endl;
                        kill(pid,sig);
                        if(sig!=SIGKILL && sig!=SIGCONT) kill(pid,SIGCONT);
                        deadline=killAfter>=0 ? t+killAfter : -1;
                    }else if(!killed){
                        killed=true;
                        if(verbose) std::cerr << "timeout: sending signal KILL to command '" << argv[i] << "'" << std::endl;
                        kill(pid,SIGKILL);
                        deadline=-1;
                    }
                }
                struct timespec ts{0,5*1000*1000};
                nanosleep(&ts,nullptr);
            }
            int rc=WIFEXITED(status) ? WEXITSTATUS(status) : WIFSIGNALED(status) ? 128+WTERMSIG(status) : 125;
            if(killed) return preserve ? rc : 137;
            if(timedOut && !preserve) return sig==SIGKILL ? 137 : 124;
            return rc;
        }
    };

    // tty [-s]
    class TtyCommand : public ShellCommand {
    public:
        TtyCommand():ShellCommand("tty"){}
        int runCommand(int argc,const char **argv){
            bool silent=false;
            for(int i=1;i<argc;++i){
                std::string a=argv[i];
                if(a=="-s" || a=="--silent" || a=="--quiet") silent=true;
                else{ std::cerr << "tty: extra operand '" << a << "'" << std::endl; return 2; }
            }
            const char *n=ttyname(0);
            if(silent) return n ? 0 : 1;
            if(!n){ std::cout << "not a tty" << std::endl; return 1; }
            std::cout << n << std::endl;
            return 0;
        }
    };

    // logname
    class LognameCommand : public ShellCommand {
    public:
        LognameCommand():ShellCommand("logname"){}
        int runCommand(int argc,const char **argv){
            if(argc>1){ std::cerr << "logname: extra operand '" << argv[1] << "'" << std::endl; return 1; }
            const char *n=getlogin();
            if(!n || !*n){ std::cerr << "logname: no login name" << std::endl; return 1; }
            std::cout << n << std::endl;
            return 0;
        }
    };

    FRESH_REGISTER_COMMAND(TimeoutCommand);
    FRESH_REGISTER_COMMAND(TtyCommand);
    FRESH_REGISTER_COMMAND(LognameCommand);

}}