SHS/stdlib/shell.go

460 lines
11 KiB
Go
Raw Normal View History

/* SHS: Syntactically Homogeneous Shell
* Copyright (C) 2019 Aidan Hahn
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package stdlib
import (
"os"
2020-07-22 21:56:31 -07:00
"io"
"fmt"
"bytes"
2020-07-22 00:22:39 -07:00
"errors"
"os/exec"
2020-07-22 00:22:39 -07:00
"context"
"syscall"
2020-07-22 21:56:31 -07:00
"strconv"
"os/signal"
2020-07-22 00:22:39 -07:00
"golang.org/x/sys/unix"
2020-07-22 21:56:31 -07:00
"gitlab.com/whom/shs/ast"
"gitlab.com/whom/shs/log"
)
2020-07-22 00:22:39 -07:00
var sigChan chan os.Signal
var waitChan chan error
/* mapping of pid to Proc
*/
var JobMap = map[int]Proc{}
/* id of shell process group
*/
2020-07-22 21:56:31 -07:00
var pgid, pid int
2020-07-22 00:22:39 -07:00
2020-07-22 22:30:56 -07:00
/* cancel func for current running process
*/
var CurCancel *context.CancelFunc
2020-07-22 00:22:39 -07:00
/* Holds an os/exec Cmd object and its context cancel function
*/
type Proc struct {
Ctl *exec.Cmd
Cancel context.CancelFunc
}
var catchMe = []os.Signal{
syscall.SIGINT,
2020-06-29 21:21:30 -07:00
}
2020-07-19 14:37:20 -07:00
/* Exit code of last run process
*/
var LastExitCode int
2020-07-22 00:22:39 -07:00
// Job control handlers
func signalHandler() {
for {
2020-07-22 22:30:56 -07:00
<- sigChan
log.Log(log.DEBUG,
"caught SIGINT",
"jobctl")
if CurCancel != nil {
(*CurCancel)()
2020-07-22 00:22:39 -07:00
}
}
}
func waitHandler() {
for {
w := <- waitChan
exit := 0
if w != nil {
log.Log(log.ERR,
2020-07-22 22:30:56 -07:00
"Child returned: " + w.Error(),
2020-07-22 00:22:39 -07:00
"jobctl")
// something outrageous
exit = -1024
var e *exec.ExitError
if errors.As(w, &e) {
exit = e.Pid()
}
LastExitCode = exit
}
}
}
2020-07-22 21:56:31 -07:00
// for some reason not implemented in stdlib
func tcsetpgrp(fd int, pgrp int) error {
return unix.IoctlSetPointerInt(fd, unix.TIOCSPGRP, pgrp)
}
// wrapper for convenience
func setSigState() {
signal.Ignore(syscall.SIGTTOU, syscall.SIGTTIN, syscall.SIGTSTP)
2020-07-22 22:30:56 -07:00
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGQUIT)
2020-07-22 21:56:31 -07:00
}
2020-07-22 00:22:39 -07:00
/* Sets pgid
* Installs a sigchld handler
* returns true if success, false on error
*/
func InitShellFeatures() bool {
2020-07-22 21:56:31 -07:00
// TODO: adjust capacity, make configurable maybe?
2020-07-22 00:22:39 -07:00
sigChan = make(chan os.Signal, 5)
waitChan = make(chan error, 5)
go signalHandler()
go waitHandler()
2020-07-22 21:56:31 -07:00
setSigState()
pid = os.Getpid()
var errr error
pgid, errr = syscall.Getpgid(pid)
if errr != nil {
log.Log(log.ERR,
"Failure to get pgid: " + errr.Error(),
"jobctl")
return false
}
termPgrp, err := unix.IoctlGetInt(0, unix.TIOCGPGRP)
if err != nil {
log.Log(log.ERR,
"Failure to get pgrp: " + err.Error(),
"jobctl")
return false
2020-07-22 00:22:39 -07:00
}
2020-07-22 21:56:31 -07:00
if pgid != termPgrp {
syscall.Kill(-termPgrp, unix.SIGTTIN)
}
syscall.Setpgid(0, 0)
2020-07-22 00:22:39 -07:00
tcsetpgrp(0, pid)
return true
}
/* Tears down session
*/
func TeardownShell() {
close(sigChan)
close(waitChan)
// TODO: Exit all processes in the JobMap
}
/* Makes and stores a new process in the job control
* uses os/exec Cmd object. sets SysProcAttr.Foreground
* calls Cmd.Start()
*/
2020-07-22 21:56:31 -07:00
func LaunchProcess(
path string,
args []string,
background bool,
stdin io.Reader,
stdout io.Writer,
stderr io.Writer ) {
2020-07-22 00:22:39 -07:00
c, cancel := context.WithCancel(context.Background())
cmd := exec.CommandContext(c, path, args...)
2020-07-22 21:56:31 -07:00
cmd.SysProcAttr = &syscall.SysProcAttr{Foreground: !background, Setpgid: true}
2020-07-22 00:22:39 -07:00
2020-07-22 21:56:31 -07:00
if stdin == nil {
stdin = os.Stdin
}
if stdout == nil {
stdout = os.Stdout
}
if stderr == nil {
stderr = os.Stderr
}
cmd.Stdin = stdin
cmd.Stdout = stdout
cmd.Stderr = stderr
2020-07-22 00:22:39 -07:00
cmd.Start()
2020-07-22 22:30:56 -07:00
cpid := cmd.Process.Pid
2020-07-22 00:22:39 -07:00
// TODO: check for clobber?
2020-07-22 21:56:31 -07:00
// unlikely, but PIDs do reset after a while
2020-07-22 22:30:56 -07:00
JobMap[cpid] = Proc{ Ctl: cmd, Cancel: cancel }
CurCancel = &cancel
2020-07-22 00:22:39 -07:00
if background {
2020-07-22 21:56:31 -07:00
go func(){
waitChan <- cmd.Wait()
2020-07-22 22:30:56 -07:00
delete(JobMap, cpid)
CurCancel = nil
2020-07-22 21:56:31 -07:00
}()
} else {
cmd.Wait()
tcsetpgrp(0, pgid)
2020-07-22 22:30:56 -07:00
delete(JobMap, cpid)
CurCancel = nil
2020-07-22 00:22:39 -07:00
}
}
2020-07-19 14:37:20 -07:00
/* Takes n arguments (list of tokens generated by lexing a shell command)
* Evaluates arguments, but does not err on undefined symbols (note the last arg to Eval(...))
* Executes shell command and returns nil
*
* Example (l vim file.txt)
*/
func Call(in *ast.Token, vt ast.VarTable, ft ast.FuncTable) *ast.Token {
in = in.Eval(ft, vt, true)
if in == nil {
return nil
}
if in.Tag == ast.LIST {
log.Log(log.ERR, "couldnt exec, target bin is a list", "call")
return nil
}
path, err := exec.LookPath(in.Value())
if err != nil {
log.Log(log.ERR, "Couldnt exec " + in.Value() + ", file not found", "call")
return nil
}
args := []string{}
for i := in.Next; i != nil; i = i.Next {
if i.Tag == ast.LIST {
log.Log(log.ERR, "Couldnt exec " + path + ", element in arguments is a list", "call")
return nil
}
args = append(args, i.Value())
}
2020-07-22 21:56:31 -07:00
LaunchProcess(path, args, false, nil, nil, nil)
return nil
}
2020-07-19 14:37:20 -07:00
/* Starts a call in the background
* Takes n args (a shell command not delimited by string delimiters)
*
* Example: (bg vim file.txt)
*/
func Bgcall(in *ast.Token, vt ast.VarTable, ft ast.FuncTable) *ast.Token {
2020-07-22 21:56:31 -07:00
in = in.Eval(ft, vt, true)
if in == nil {
return nil
}
if in.Tag == ast.LIST {
log.Log(log.ERR, "couldnt exec, target bin is a list", "call")
return nil
}
path, err := exec.LookPath(in.Value())
if err != nil {
log.Log(log.ERR, "Couldnt exec " + in.Value() + ", file not found", "call")
return nil
}
args := []string{}
for i := in.Next; i != nil; i = i.Next {
if i.Tag == ast.LIST {
log.Log(log.ERR, "Couldnt exec " + path + ", element in arguments is a list", "call")
return nil
}
args = append(args, i.Value())
}
2020-07-22 21:56:31 -07:00
LaunchProcess(path, args, true, nil, nil, nil)
return nil
}
2020-07-22 21:56:31 -07:00
/* takes one argument: pid of process to foreground
2020-07-19 14:37:20 -07:00
* returns nil
*
* Example:
* (bg vim file.txt)
2020-07-22 21:56:31 -07:00
* ( <call to ps or jobs> )
* (fg <pid>)
2020-07-19 14:37:20 -07:00
*/
func Fg(in *ast.Token, vt ast.VarTable, ft ast.FuncTable) *ast.Token {
2020-07-22 21:56:31 -07:00
if len(JobMap) < 1 {
return nil
}
in = in.Eval(ft, vt, false)
if in.Tag != ast.NUMBER && in.Tag != ast.STRING {
log.Log(log.ERR,
"must supply a number or string to fg",
"fg")
return nil
}
2020-07-22 21:56:31 -07:00
pid, err := strconv.ParseFloat(in.Value(), 64)
if err != nil {
log.Log(log.ERR,
"value supplied to fg could not be cast to float",
"fg")
return nil
}
2020-07-22 21:56:31 -07:00
ipid := int(pid)
proc, ok := JobMap[ipid]
if !ok {
log.Log(log.ERR,
"Process not found, was it started by this shell?",
"fg")
return nil
}
2020-07-22 21:56:31 -07:00
cmd := proc.Ctl
cmd.Process.Signal(syscall.SIGCONT)
2020-07-22 21:56:31 -07:00
err = cmd.Wait()
if err != nil {
if exitError, ok := err.(*exec.ExitError); ok {
LastExitCode = exitError.ExitCode()
} else {
log.Log(log.ERR, "Execution step returned error: " + err.Error(), "call")
}
}
return nil
}
2020-07-19 14:37:20 -07:00
/* Takes 0 args
2020-07-22 21:56:31 -07:00
* returns a list of PIDs
2020-07-19 14:37:20 -07:00
*
* Example:
* (bg ping google.com)
* (bg .........)
* (jobs)
*/
func Jobs(in *ast.Token, vt ast.VarTable, fg ast.FuncTable) *ast.Token {
ret := &ast.Token{
Tag: ast.LIST,
}
2020-07-22 21:56:31 -07:00
var _inner *ast.Token
iter := &_inner
2020-07-22 21:56:31 -07:00
for k := range JobMap {
(*iter) = &ast.Token{
Tag: ast.STRING,
}
2020-07-22 21:56:31 -07:00
(*iter).Set(fmt.Sprintf("%d", k))
iter = &(*iter).Next
}
2020-07-22 21:56:31 -07:00
ret.Direct(_inner)
return ret
}
2020-07-19 14:37:20 -07:00
/* calls a command (blocks until completion)
* captures stdout and returns it as a string
*
* Example: ($ echo hello world)
*/
func ReadCmd(in *ast.Token, vt ast.VarTable, ft ast.FuncTable) *ast.Token {
in = in.Eval(ft, vt, true)
if in == nil {
return nil
}
if in.Tag == ast.LIST {
log.Log(log.ERR, "couldnt exec, target bin is a list", "call")
return nil
}
2020-07-22 21:56:31 -07:00
out := new(bytes.Buffer)
path, err := exec.LookPath(in.Value())
if err != nil {
log.Log(log.ERR, "Couldnt exec " + in.Value() + ", file not found", "call")
return nil
}
args := []string{}
for i := in.Next; i != nil; i = i.Next {
if i.Tag == ast.LIST {
log.Log(log.ERR, "Couldnt exec " + path + ", element in arguments is a list", "call")
return nil
}
args = append(args, i.Value())
}
2020-07-22 21:56:31 -07:00
LaunchProcess(path, args, false, nil, out, nil)
output := out.String()
olen := len(output)
if olen > 0 && output[olen - 1] == '\n' {
output = output[:olen - 1]
}
ret := &ast.Token{Tag: ast.STRING}
ret.Set(output)
return ret
}
2020-07-19 14:37:20 -07:00
/* Takes 0 arguments
* returns the exit code of the last executed program
*
* Example:
* (sudo apt update)
* (?) <- gets exit code
*/
func GetExit(in *ast.Token, vt ast.VarTable, ft ast.FuncTable) *ast.Token {
ret := &ast.Token{Tag: ast.NUMBER}
ret.Set(fmt.Sprintf("%d", LastExitCode))
return ret
}
2020-07-19 14:37:20 -07:00
/* takes an argument (pid of process to be killed)
* calls Process.Kill() on it
* do not use this if you already have a native implementation
* (this function not added to functable in stdlib.go)
*/
func Kill(in *ast.Token, vt ast.VarTable, ft ast.FuncTable) *ast.Token {
in = in.Eval(ft, vt, true)
if in.Tag == ast.LIST {
log.Log(log.ERR, "non-number argument to kill function", "kill")
return nil
}
pid, err := strconv.ParseInt(in.Value(), 10, 64)
if err != nil {
log.Log(log.ERR, "error parsing arg to kill: " + err.Error(), "kill")
return nil
}
2020-07-22 21:56:31 -07:00
proc, ok := JobMap[int(pid)]
if !ok {
log.Log(log.ERR,
"Couldnt find process " + in.Value() + ", was it started by this shell?",
"kill")
return nil
}
2020-07-22 21:56:31 -07:00
// if this doesnt work do proc.Ctl.Kill()
proc.Cancel()
delete(JobMap, int(pid))
return nil
}