From 3610d3dd84173fcff2cf67bdd2a4d826a26aedd1 Mon Sep 17 00:00:00 2001 From: yaling888 <73897884+yaling888@users.noreply.github.com> Date: Mon, 6 Jun 2022 05:20:59 +0800 Subject: [PATCH] Feature: add `path` to script config script: path: ./script.star --- README.md | 1 + config/config.go | 27 +++++++++++++++++++++++++-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a035c4b5..2f114b25 100644 --- a/README.md +++ b/README.md @@ -252,6 +252,7 @@ Script enables users to programmatically select a policy for the packets with mo mode: script script: + # path: ./script.star code: | def main(ctx, metadata): if metadata["process_name"] == 'apsd': diff --git a/config/config.go b/config/config.go index 7b288237..e581aed2 100644 --- a/config/config.go +++ b/config/config.go @@ -112,6 +112,7 @@ type Tun struct { // Script config type Script struct { MainCode string `yaml:"code" json:"code"` + MainPath string `yaml:"path" json:"path"` ShortcutsCode map[string]string `yaml:"shortcuts" json:"shortcuts"` } @@ -853,8 +854,26 @@ func parseAuthentication(rawRecords []string) []auth.AuthUser { } func parseScript(script Script, rawRules []string) ([]string, error) { - mainCode := script.MainCode - shortcutsCode := script.ShortcutsCode + var ( + path = script.MainPath + mainCode = script.MainCode + shortcutsCode = script.ShortcutsCode + ) + + if path != "" { + if !strings.HasSuffix(path, ".star") { + return nil, fmt.Errorf("initialized script file failure, script path [%s] invalid", path) + } + path = C.Path.Resolve(path) + if _, err := os.Stat(path); os.IsNotExist(err) { + return nil, fmt.Errorf("initialized script file failure, script path invalid: %w", err) + } + data, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("initialized script file failure, read file error: %w", err) + } + mainCode = string(data) + } if strings.TrimSpace(mainCode) == "" { mainCode = ` @@ -865,6 +884,10 @@ def main(ctx, metadata): mainCode = cleanPyKeywords(mainCode) } + if !strings.Contains(mainCode, "def main(ctx, metadata):") { + return nil, fmt.Errorf(`initialized script code failure, the function 'def main(ctx, metadata):' is required`) + } + content := `# -*- coding: UTF-8 -*- from datetime import datetime as whatever