Skip to content

Commit

Permalink
CLI: Load stored scripts only from intended path;Fix SIGNAL interrupt…
Browse files Browse the repository at this point in the history
… of HIDScripts started with 'cli hid run'
  • Loading branch information
mame82 committed Nov 24, 2018
1 parent b64df8e commit 0222b81
Show file tree
Hide file tree
Showing 7 changed files with 42 additions and 38 deletions.
28 changes: 16 additions & 12 deletions cli_client/cmd_hid.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package cli_client

import (
"context"
"github.com/mame82/P4wnP1_go/common"
"github.com/spf13/cobra"
"fmt"
"path/filepath"
Expand All @@ -16,8 +18,8 @@ import (

var (
tmpHidCommands = ""
tmpRunFromServerPath = ""
tmpHidTimeout = uint32(0) // values < 0 = endless
tmpRunStored = ""
tmpHidTimeout = uint32(0) // values < 0 = endless
)

var hidCmd = &cobra.Command{
Expand Down Expand Up @@ -91,7 +93,7 @@ var hidJobCancelCmd = &cobra.Command{
// The logic above applies to both, running scripts synchronous with `run` or asynchronous with `job`


func parseHIDRunScripCmd(cmd *cobra.Command, args []string) (serverScriptPath string, err error) {
func parseHIDRunScriptCmd(cmd *cobra.Command, args []string) (serverScriptPath string, err error) {
/*
readFromStdin := false
localFile := false //if true readFilePath refers to a file on the host of the rpcClient, else to a file on the rpcServer
Expand All @@ -104,7 +106,7 @@ func parseHIDRunScripCmd(cmd *cobra.Command, args []string) (serverScriptPath st


cFlagSet := cmd.Flags().ShorthandLookup("c").Changed
rFlagSet := cmd.Flags().ShorthandLookup("r").Changed
rFlagSet := cmd.Flags().ShorthandLookup("n").Changed

switch {
case !rFlagSet && !cFlagSet:
Expand All @@ -125,13 +127,13 @@ func parseHIDRunScripCmd(cmd *cobra.Command, args []string) (serverScriptPath st
} else {
// assume RPC client is run from same host as RPC server and the script path refers to a local file
transferNeeded = false
serverScriptPath = args[0]
serverScriptPath = common.PATH_HID_SCRIPTS + "/" + args[0]
}
}
case rFlagSet:
// the flag represents a script path on the RPC server, no matter where the RPC client is running, so we assume the script is already there
transferNeeded = false
serverScriptPath = tmpRunFromServerPath
serverScriptPath = common.PATH_HID_SCRIPTS + "/" + tmpRunStored
case cFlagSet:
// script content is provided by parameter and needs to be transferred
transferNeeded = true
Expand Down Expand Up @@ -178,15 +180,17 @@ func parseHIDRunScripCmd(cmd *cobra.Command, args []string) (serverScriptPath st
if err != nil { return "",errors.New(fmt.Sprintf("Error transfering HIDScript content to P4wnP1 Server: %v", err))}
}


return
}

func cobraHidRun(cmd *cobra.Command, args []string) {
serverScriptFilePath, err := parseHIDRunScripCmd(cmd,args)
serverScriptFilePath, err := parseHIDRunScriptCmd(cmd,args)
if err != nil { log.Fatal(err)}

res,err := ClientHIDRunScript(StrRemoteHost, StrRemotePort, serverScriptFilePath, tmpHidTimeout)
ctx,cancel := context.WithCancel(context.Background())
defer cancel()

res,err := ClientHIDRunScript(StrRemoteHost, StrRemotePort, ctx, serverScriptFilePath, tmpHidTimeout)
if err != nil { log.Fatal(err) }

fmt.Printf("Result:\n%s\n", res.ResultJson)
Expand All @@ -195,7 +199,7 @@ func cobraHidRun(cmd *cobra.Command, args []string) {


func cobraHidJob(cmd *cobra.Command, args []string) {
serverScriptFilePath, err := parseHIDRunScripCmd(cmd,args)
serverScriptFilePath, err := parseHIDRunScriptCmd(cmd,args)
if err != nil { log.Fatal(err)}


Expand Down Expand Up @@ -226,10 +230,10 @@ func init() {
hidJobCmd.AddCommand(hidJobCancelCmd)

hidRunCmd.Flags().StringVarP(&tmpHidCommands, "commands","c", "", "HIDScript commands to run, given as string")
hidRunCmd.Flags().StringVarP(&tmpRunFromServerPath, "server-path","r", "", "Load HIDScript from given path on P4wnP1 server")
hidRunCmd.Flags().StringVarP(&tmpRunStored, "name","n", "", "Run a stored HIDScript")
hidRunCmd.Flags().Uint32VarP(&tmpHidTimeout, "timeout","t", 0, "Interrupt HIDScript after this timeout (seconds)")

hidJobCmd.Flags().StringVarP(&tmpHidCommands, "commands","c", "", "HIDScript commands to run, given as string")
hidJobCmd.Flags().StringVarP(&tmpRunFromServerPath, "server-path","r", "", "Load HIDScript from given path on P4wnP1 server")
hidJobCmd.Flags().StringVarP(&tmpRunStored, "name","n", "", "Run a stored HIDScript")
hidJobCmd.Flags().Uint32VarP(&tmpHidTimeout, "timeout","t", 0, "Interrupt HIDScript after this timeout (seconds)")
}
8 changes: 3 additions & 5 deletions cli_client/rpc_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"fmt"
pb "github.com/mame82/P4wnP1_go/proto"
"errors"
"golang.org/x/net/context"
"context"
"google.golang.org/grpc"
"io"
"log"
Expand Down Expand Up @@ -320,7 +320,7 @@ func ClientDeployWifiSettings(host string, port string, settings *pb.WiFiSetting
return
}

func ClientHIDRunScript(host string, port string, scriptPath string, timeoutSeconds uint32) (scriptRes *pb.HIDScriptResult, err error) {
func ClientHIDRunScript(host string, port string, ctx context.Context, scriptPath string, timeoutSeconds uint32) (scriptRes *pb.HIDScriptResult, err error) {
scriptReq := &pb.HIDScriptRequest{
ScriptPath: scriptPath,
TimeoutSeconds: timeoutSeconds,
Expand All @@ -332,10 +332,8 @@ func ClientHIDRunScript(host string, port string, scriptPath string, timeoutSeco
defer connection.Close()

rpcClient := pb.NewP4WNP1Client(connection)
// ctx, cancel := context.WithTimeout(context.Background(), time.Second * 30)
// defer cancel()

scriptRes,err = rpcClient.HIDRunScript(context.Background(), scriptReq)
scriptRes,err = rpcClient.HIDRunScript(ctx, scriptReq)
return
}

Expand Down
2 changes: 1 addition & 1 deletion common/globals.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package service
package common

const (
PATH_ROOT = "/usr/local/P4wnP1"
Expand Down
4 changes: 2 additions & 2 deletions service/SubSysTriggerAction.go
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,7 @@ func (tam *TriggerActionManager) executeActionStartHidScript(evt *pb.Event, ta *

fmt.Printf("Trigger '%s' fired -> executing action '%s' ('%s')\n", triggerName, actionName, action.ScriptName)

scriptPath := PATH_HID_SCRIPTS + "/" + action.ScriptName
scriptPath := common.PATH_HID_SCRIPTS + "/" + action.ScriptName
preScript := fmt.Sprintf("var TRIGGER='%s';\n", triggerName)

switch tt {
Expand Down Expand Up @@ -490,7 +490,7 @@ func (tam *TriggerActionManager) executeActionBashScript(evt *pb.Event, ta *pb.T
triggerName := triggerTypeString[tt]
actionName := actionTypeString[at]

scriptPath := PATH_BASH_SCRIPTS + "/" + action.ScriptName
scriptPath := common.PATH_BASH_SCRIPTS + "/" + action.ScriptName
env := []string{
fmt.Sprintf("TRIGGER=%s", triggerName),
}
Expand Down
11 changes: 6 additions & 5 deletions service/SubSysUSB.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"context"
"errors"
"fmt"
"github.com/mame82/P4wnP1_go/common"
"github.com/mame82/P4wnP1_go/hid"
pb "github.com/mame82/P4wnP1_go/proto"
"io/ioutil"
Expand Down Expand Up @@ -740,9 +741,9 @@ func (gm *UsbGadgetManager) DeployGadgetSettings(settings *pb.GadgetSettings) (e
//Provide the backing image
file := settings.UmsSettings.File
if settings.UmsSettings.Cdrom {
file = PATH_IMAGE_CDROM + "/" + file
file = common.PATH_IMAGE_CDROM + "/" + file
} else {
file = PATH_IMAGE_FLASHDRIVE + "/" + file
file = common.PATH_IMAGE_FLASHDRIVE + "/" + file
}
ioutil.WriteFile(funcdir+"/lun.0/file", []byte(file), os.ModePerm) // Set backing file (or block device) for USB Mass Storage

Expand Down Expand Up @@ -782,12 +783,12 @@ func (gm *UsbGadgetManager) DeployGadgetSettings(settings *pb.GadgetSettings) (e

//log.Printf("Starting HID controller (kbd %s, mouse %s)...\n", devPathKeyboard, devPathMouse)
var errH error
gm.hidCtl, errH = hid.NewHIDController(context.Background(), devPathKeyboard, PATH_KEYBOARD_LANGUAGE_MAPS, devPathMouse)
gm.hidCtl, errH = hid.NewHIDController(context.Background(), devPathKeyboard, common.PATH_KEYBOARD_LANGUAGE_MAPS, devPathMouse)
gm.hidCtl.SetEventHandler(gm)
if errH != nil {
log.Printf("ERROR: Couldn't bring up an instance of HIDController for keyboard: '%s', mouse: '%s' and mapping path '%s'\nReason: %v\n", devPathKeyboard, devPathMouse, PATH_KEYBOARD_LANGUAGE_MAPS, errH)
log.Printf("ERROR: Couldn't bring up an instance of HIDController for keyboard: '%s', mouse: '%s' and mapping path '%s'\nReason: %v\n", devPathKeyboard, devPathMouse, common.PATH_KEYBOARD_LANGUAGE_MAPS, errH)
} else {
log.Printf("HIDController for keyboard: '%s', mouse: '%s' and mapping path '%s' initialized\n", devPathKeyboard, devPathMouse, PATH_KEYBOARD_LANGUAGE_MAPS)
log.Printf("HIDController for keyboard: '%s', mouse: '%s' and mapping path '%s' initialized\n", devPathKeyboard, devPathMouse, common.PATH_KEYBOARD_LANGUAGE_MAPS)
}
} else {
if gm.hidCtl != nil { gm.hidCtl.Abort() }
Expand Down
22 changes: 11 additions & 11 deletions service/rpc_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,15 @@ type server struct {

func (s *server) ListUmsImageFlashdrive(ctx context.Context, e *pb.Empty) (sa *pb.StringMessageArray, err error) {
sa = &pb.StringMessageArray{}
scripts,err := ListFilesOfFolder(PATH_IMAGE_FLASHDRIVE, ".img", ".bin")
scripts,err := ListFilesOfFolder(common.PATH_IMAGE_FLASHDRIVE, ".img", ".bin")
if err != nil { return sa,err }
sa.MsgArray = scripts
return
}

func (s *server) ListUmsImageCdrom(ctx context.Context, e *pb.Empty) (sa *pb.StringMessageArray, err error) {
sa = &pb.StringMessageArray{}
scripts,err := ListFilesOfFolder(PATH_IMAGE_CDROM, ".iso")
scripts,err := ListFilesOfFolder(common.PATH_IMAGE_CDROM, ".iso")
if err != nil { return sa,err }
sa.MsgArray = scripts
return
Expand Down Expand Up @@ -386,7 +386,7 @@ func (s *server) DBBackup(ctx context.Context, filename *pb.StringMessage) (e *p
fname = fname + ".db"
}

err = s.rootSvc.SubSysDataStore.Backup(PATH_DATA_STORE_BACKUP + "/" + fname)
err = s.rootSvc.SubSysDataStore.Backup(common.PATH_DATA_STORE_BACKUP + "/" + fname)
return
}

Expand All @@ -398,13 +398,13 @@ func (s *server) DBRestore(ctx context.Context, filename *pb.StringMessage) (e *
if lext := strings.ToLower(ext); lext != ".db" {
fname = fname + ".db"
}
err = s.rootSvc.SubSysDataStore.Restore(PATH_DATA_STORE_BACKUP + "/" + fname, true)
err = s.rootSvc.SubSysDataStore.Restore(common.PATH_DATA_STORE_BACKUP + "/" + fname, true)
return
}

func (s *server) ListStoredDBBackups(ctx context.Context, e *pb.Empty) (ma *pb.StringMessageArray, err error) {
ma = &pb.StringMessageArray{}
scripts,err := ListFilesOfFolder(PATH_DATA_STORE_BACKUP, ".db")
scripts,err := ListFilesOfFolder(common.PATH_DATA_STORE_BACKUP, ".db")
if err != nil { return ma,err }
ma.MsgArray = scripts
return
Expand Down Expand Up @@ -480,15 +480,15 @@ func (s *server) ListStoredUSBSettings(ctx context.Context, e *pb.Empty) (sa *pb

func (s *server) ListStoredHIDScripts(context.Context, *pb.Empty) (sa *pb.StringMessageArray, err error) {
sa = &pb.StringMessageArray{}
scripts,err := ListFilesOfFolder(PATH_HID_SCRIPTS, ".js", ".javascript")
scripts,err := ListFilesOfFolder(common.PATH_HID_SCRIPTS, ".js", ".javascript")
if err != nil { return sa,err }
sa.MsgArray = scripts
return
}

func (s *server) ListStoredBashScripts(context.Context, *pb.Empty) (sa *pb.StringMessageArray, err error) {
sa = &pb.StringMessageArray{}
scripts,err := ListFilesOfFolder(PATH_BASH_SCRIPTS, ".sh", ".bash")
scripts,err := ListFilesOfFolder(common.PATH_BASH_SCRIPTS, ".sh", ".bash")
if err != nil { return sa,err }
sa.MsgArray = scripts
return
Expand Down Expand Up @@ -672,9 +672,9 @@ func (s *server) FSWriteFile(ctx context.Context, req *pb.WriteFileRequest) (emp
case pb.AccessibleFolder_TMP:
filePath = "/tmp" + filePath
case pb.AccessibleFolder_BASH_SCRIPTS:
filePath = PATH_BASH_SCRIPTS + filePath
filePath = common.PATH_BASH_SCRIPTS + filePath
case pb.AccessibleFolder_HID_SCRIPTS:
filePath = PATH_HID_SCRIPTS + filePath
filePath = common.PATH_HID_SCRIPTS + filePath
default:
err = errors.New("Unknown folder")
return
Expand All @@ -692,9 +692,9 @@ func (s *server) FSReadFile(ctx context.Context, req *pb.ReadFileRequest) (resp
case pb.AccessibleFolder_TMP:
filePath = "/tmp" + filePath
case pb.AccessibleFolder_BASH_SCRIPTS:
filePath = PATH_BASH_SCRIPTS + filePath
filePath = common.PATH_BASH_SCRIPTS + filePath
case pb.AccessibleFolder_HID_SCRIPTS:
filePath = PATH_HID_SCRIPTS + filePath
filePath = common.PATH_HID_SCRIPTS + filePath
default:
err = errors.New("Unknown folder")
return
Expand Down
5 changes: 3 additions & 2 deletions service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package service
import (
"context"
"fmt"
"github.com/mame82/P4wnP1_go/common"
"github.com/mame82/P4wnP1_go/common_web"
pb "github.com/mame82/P4wnP1_go/proto"
"github.com/mame82/P4wnP1_go/service/datastore"
Expand Down Expand Up @@ -140,7 +141,7 @@ func NewService() (svc *Service, err error) {
svc = &Service{}
svc.Ctx,svc.Cancel = context.WithCancel(context.Background())

svc.SubSysDataStore, err = datastore.Open(PATH_DATA_STORE, PATH_DATA_STORE_BACKUP + "/init.db")
svc.SubSysDataStore, err = datastore.Open(common.PATH_DATA_STORE, common.PATH_DATA_STORE_BACKUP + "/init.db")
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -181,7 +182,7 @@ func (s *Service) Start() (context.Context, context.CancelFunc) {
s.SubSysDwc2ConnectWatcher.Start()
s.SubSysGpio.Start()
s.SubSysLed.Start()
s.SubSysRPC.StartRpcServerAndWeb("0.0.0.0", "50051", "8000", PATH_WEBROOT) //start gRPC service
s.SubSysRPC.StartRpcServerAndWeb("0.0.0.0", "50051", "8000", common.PATH_WEBROOT) //start gRPC service
log.Println("Starting TriggerAction event listener ...")
s.SubSysTriggerActions.Start()

Expand Down

0 comments on commit 0222b81

Please sign in to comment.