func javascriptReduceCount(call otto.FunctionCall) otto.Value { rere, err := call.Argument(2).ToBoolean() if err != nil { return ottoMust(otto.ToValue(fmt.Sprintf("Error getting rere flag: %v", err))) } ob, err := call.Argument(1).Export() if err != nil { return ottoMust(otto.ToValue(fmt.Sprintf("Error getting stuff: %v", err))) } l, ok := ob.([]interface{}) if !ok { return ottoMust(otto.ToValue(fmt.Sprintf("unhandled %v/%T", ob, ob))) } if !rere { return ottoMust(otto.ToValue(len(l))) } rv := float64(0) for _, i := range l { rv += zeroate(i) } return ottoMust(otto.ToValue(rv)) }
func apiServiceCall(call otto.FunctionCall) otto.Value { svc := call.Argument(0).String() interfaceValue, err := call.Argument(1).Export() if err != nil { logrus.Errorf("Plugins: rules: javascript supplied invalid parameters") return otto.UndefinedValue() } params := interfaceValue.(map[string]interface{}) future := service.CallService(svc, params) result := <-future.Result var res otto.Value if _, ok := result.(error); ok { res, err = otto.ToValue(result.(error).Error()) } else { res, err = otto.ToValue(result) } if err != nil { logrus.Errorf("Plugins: rules: failed to convert service result to javascript") return otto.UndefinedValue() } return res }
func javascriptReduceStats(call otto.FunctionCall) otto.Value { rere, err := call.Argument(2).ToBoolean() if err != nil { return ottoMust(otto.ToValue(fmt.Sprintf("Error getting rere flag: %v", err))) } ob, err := call.Argument(1).Export() if err != nil { return ottoMust(otto.ToValue(fmt.Sprintf("Error getting stuff: %v", err))) } l, ok := ob.([]interface{}) if !ok { return ottoMust(otto.ToValue(fmt.Sprintf("unhandled %v/%T", ob, ob))) } rv := statsResult{} if len(l) == 0 { return rv.toOtto() } if rere { // Rereduction goes here. rv.load(l[0]) for i := 1; i < len(l); i++ { ob := statsResult{} ob.load(l[i]) rv.Add(ob) } return rv.toOtto() } // Initial reduction rv.count = 1 rv.sum = zeroate(l[0]) rv.min = rv.sum rv.max = rv.sum rv.sumsqr = rv.sum * rv.sum for i := 1; i < len(l); i++ { v := zeroate(l[i]) rv.count++ rv.sum += v rv.min = math.Min(rv.min, v) rv.max = math.Max(rv.max, v) rv.sumsqr += (v * v) } return rv.toOtto() }
// stringToValue makes an otto.Value containing the specified string. func stringToValue(message string) otto.Value { val, err := otto.ToValue(message) if err != nil { return otto.UndefinedValue() } return val }
func main() { if len(os.Args) != 2 { usage() } vm := motto.New() vm.Set("fib", func(call otto.FunctionCall) otto.Value { ret := fib(40) v, _ := otto.ToValue(ret) return v }) vm.Set("XHR", func(call otto.FunctionCall) otto.Value { return otto.UndefinedValue() }) vm.Set("XHR.prototype.hello", func(call otto.FunctionCall) otto.Value { return otto.UndefinedValue() }) _, err := vm.Run(os.Args[1]) fmt.Printf("%v", err) }
func (rc *RunContext) RunScript(call otto.FunctionCall) otto.Value { if len(call.ArgumentList) != 2 { return rc.Err("RunScript must be (string, interface{}") } script, err := call.ArgumentList[0].ToString() if err != nil { log.Println(err.Error()) return rc.Err(err.Error()) } parametersRaw := call.ArgumentList[1].String() if err != nil { log.Println(err.Error()) return rc.Err(err.Error()) } parameters := map[string]interface{}{} json.Unmarshal([]byte(parametersRaw), ¶meters) result, err := rc.runner.RunScript(script, parameters, rc.db) if err != nil { log.Println(err.Error()) return rc.Err(err.Error()) } resultJson, err := json.Marshal(result) if err != nil { log.Println(err.Error()) return rc.Err(err.Error()) } r, err := otto.ToValue(string(resultJson)) if err != nil { log.Println(err.Error()) return rc.Err(err.Error()) } return r }
// Parse parses the buffer and adds it to the line struct // the config[otto.script] should be a javascript function which // returns a hash. Each key in the hash will be added to the line Data // and will be indexed func (op *Parser) Parse(buffer []byte, line *ql.Line, config map[string]interface{}) error { script := config["otto.script"].(string) fn, err := op.o.Run(script) if err != nil { return err } this, err := otto.ToValue(nil) if err != nil { return err } result, err := fn.Call(this, string(buffer)) if err != nil { return err } object := result.Object() for _, key := range object.Keys() { v, _ := object.Get(key) if v.IsPrimitive() { line.Data[key] = v.String() } } return nil }
//returns information about the system func _system_currentUser(call otto.FunctionCall) otto.Value { currentUser, err := user.Current() if err != nil { jsThrow(call, err) } objString := fmt.Sprintf(` ({ name: '%s', homeDir: '%s', uid: '%s', gid: '%s', username: '******' }) `, currentUser.Name, currentUser.HomeDir, currentUser.Uid, currentUser.Gid, currentUser.Username) obj, err := call.Otto.Object(objString) if err != nil { jsThrow(call, err) } v, err := otto.ToValue(obj) if err != nil { jsThrow(call, err) } return v }
func _file_eachLine(call otto.FunctionCall) otto.Value { if len(call.ArgumentList) != 2 { jsThrow(call, errors.New("Wrong number of arguments.")) } sourcePath, _ := call.Argument(0).ToString() fn := call.Argument(1) if !fileExists(sourcePath) { jsThrow(call, errors.New("Source file doesn't exist")) } file, err := os.Open(sourcePath) if err != nil { jsThrow(call, err) } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) if line != "" { v, _ := otto.ToValue(line) fn.Call(v, v) } } if err := scanner.Err(); err != nil { jsThrow(call, err) } return otto.Value{} }
// throwJSException panics on an otto.Value. The Otto VM will recover from the // Go panic and throw msg as a JavaScript error. func throwJSException(msg interface{}) otto.Value { val, err := otto.ToValue(msg) if err != nil { glog.V(logger.Error).Infof("Failed to serialize JavaScript exception %v: %v", msg, err) } panic(val) }
func (vm *RuleVM) PrepareEnv() error { Service := func(call otto.FunctionCall) otto.Value { svc := call.Argument(0).String() interfaceValue, err := call.Argument(1).Export() if err != nil { logrus.Errorf("Plugins: rules: javascript supplied invalid parameters") return otto.UndefinedValue() } params := interfaceValue.(map[string]interface{}) future := service.CallService(svc, params) result := <-future.Result var res otto.Value if _, ok := result.(error); ok { res, err = otto.ToValue(result.(error).Error()) } else { res, err = otto.ToValue(result) } if err != nil { logrus.Errorf("Plugins: rules: failed to convert service result to javascript") return otto.UndefinedValue() } return res } Log := func(call otto.FunctionCall) otto.Value { logrus.Infof("Plugins: jsrule: %s Log: %s", vm.Name, call.Argument(0).String()) return otto.Value{} } err := vm.otto.Set("Service", Service) if err != nil { return err } err = vm.otto.Set("Log", Log) if err != nil { return err } return nil }
func BenchmarkJSON(b *testing.B) { v, _ := otto.ToValue("foo") var r string for n := 0; n < b.N; n++ { r = JSON(v) } result = r }
func _file_tempFolder(call otto.FunctionCall) otto.Value { d, err := ioutil.TempDir("", "conduit") if err != nil { jsThrow(call, err) } v, _ := otto.ToValue(d) return v }
func (rc *RunContext) SqlExec(call otto.FunctionCall) otto.Value { if len(call.ArgumentList) < 2 { return rc.Err("Sql query called with too few parameters") } sqlString, err := call.ArgumentList[0].ToString() if err != nil { return rc.Err(err.Error()) } sqlArgumentsRaw, err := call.Argument(1).Export() if err != nil { return rc.Err(err.Error()) } sqlArguments, ok := sqlArgumentsRaw.([]interface{}) if !ok { return rc.Err("Sql query parameter 2 must be an array") } log.Printf("EXEC: %s %#v\n", sqlString, sqlArguments) res, err := rc.db.Exec(sqlString, sqlArguments...) if err != nil { return rc.Err(err.Error()) } id, err := res.LastInsertId() if err == nil && id > 0 { log.Printf("Insert ID: %d\n", id) val, _ := otto.ToValue(id) return val } affected, err := res.RowsAffected() if err == nil { log.Printf("Rows: %d\n", affected) val, _ := otto.ToValue(affected) return val } val, _ := otto.ToValue(nil) return val }
func _file_tempFile(call otto.FunctionCall) otto.Value { f, err := ioutil.TempFile("", "conduit") if err != nil { jsThrow(call, err) } defer f.Close() v, _ := otto.ToValue(f.Name()) return v }
func _system_expand(call otto.FunctionCall) otto.Value { str, _ := call.Argument(0).ToString() eStr := os.ExpandEnv(str) oStr, err := otto.ToValue(eStr) if err != nil { jsThrow(call, err) } return oStr }
func _file_join(call otto.FunctionCall) otto.Value { paths := []string{} for idx, _ := range call.ArgumentList { str, _ := call.Argument(idx).ToString() paths = append(paths, str) } pathStr := filepath.Join(paths...) v, _ := otto.ToValue(pathStr) return v }
// GetX is an otto function that returns the object's X coord func (o *ObjectInterface) GetX(call otto.FunctionCall) otto.Value { transform := o.object.Component(new(TransformComponent)).(*TransformComponent) // api object doesn't have a transform component if transform == nil { return otto.NullValue() } r, _ := otto.ToValue(int64(transform.X)) return r }
// GetY is an otto function that returns the object's Y coord func (o *ObjectInterface) GetY(call otto.FunctionCall) otto.Value { transform := o.object.Component(new(TransformComponent)).(*TransformComponent) if transform == nil { return otto.NullValue() } r, _ := otto.ToValue(int64(transform.Y)) return r }
//READSTRING //returns the data within the specified file func _file_readString(call otto.FunctionCall) otto.Value { filepath, _ := call.Argument(0).ToString() data, err := ioutil.ReadFile(filepath) if err != nil { jsThrow(call, err) } v, _ := otto.ToValue(string(data)) return v }
func registerVM(vm *modules.JsVm) otto.Value { obj, _ := vm.Object("({})") obj.Set("set", func(c otto.FunctionCall) otto.Value { key, _ := c.Argument(0).ToString() val, _ := c.Argument(1).ToString() kvCache[key] = val return otto.TrueValue() }) obj.Set("get", func(c otto.FunctionCall) otto.Value { key, _ := c.Argument(0).ToString() val, ok := kvCache[key] if !ok { return otto.UndefinedValue() } retV, _ := otto.ToValue(val) return retV }) obj.Set("all", func(c otto.FunctionCall) otto.Value { kvObj, err := vm.Object("({})") for k, v := range kvCache { kvObj.Set(k, v) } return modules.ToResult(vm, kvObj, err) }) obj.Set("load", func(c otto.FunctionCall) otto.Value { path, _ := c.Argument(0).ToString() content, err := ioutil.ReadFile(path) if err != nil { return modules.ToResult(vm, nil, err) } err = json.Unmarshal(content, &kvCache) if err != nil { return modules.ToResult(vm, nil, err) } return otto.TrueValue() }) obj.Set("save", func(c otto.FunctionCall) otto.Value { path, _ := c.Argument(0).ToString() content, _ := json.Marshal(kvCache) ioutil.WriteFile(path, content, 0777) return otto.TrueValue() }) obj.Set("remove", func(c otto.FunctionCall) otto.Value { key, _ := c.Argument(0).ToString() delete(kvCache, key) return otto.TrueValue() }) return obj.Value() }
func _system_shell(call otto.FunctionCall) otto.Value { var ( cmdOut []byte err error ) cmd, _ := call.Argument(0).ToString() if cmdOut, err = exec.Command("cmd.exe", "/c", cmd).Output(); err != nil { jsThrow(call, err) } v, _ := otto.ToValue(string(cmdOut)) return v }
// KeyDown is an otto function that takes a string, which is the key. // It then tries to set the keydown state in the Input system, returning the bool result. func (i *InputInterface) KeyDown(call otto.FunctionCall) otto.Value { key, err := call.Argument(0).ToString() if err != nil { gLogger.Fatalln(err) } r, err := otto.ToValue(i.input.KeyDown(key)) if err != nil { gLogger.Fatalln(err) } return r }
func InitPlugin() *modules.Plugin { p1 := modules.Plugin{ Name: "dns", Init: func(vm *modules.JsVm) otto.Value { obj, _ := vm.Object("({})") obj.Set("resolve", func(c otto.FunctionCall) otto.Value { name, err := c.Argument(0).ToString() if err != nil { return otto.UndefinedValue() } config, _ := dns.ClientConfigFromFile("./resolv.conf") client := new(dns.Client) m := new(dns.Msg) m.SetQuestion(dns.Fqdn(name), dns.TypeANY) m.RecursionDesired = true host := net.JoinHostPort(config.Servers[0], config.Port) r, _, err := client.Exchange(m, host) if err != nil { k, _ := otto.ToValue("") return k } resp := "" for _, v := range r.Answer { resp += v.String() resp += "\n" } respV, _ := otto.ToValue(resp) return respV }) return obj.Value() }, } return &p1 }
//_file_info gathers path information. func _file_info(call otto.FunctionCall) otto.Value { filepath, _ := call.Argument(0).ToString() file, err := os.Open(filepath) if err != nil { jsThrow(call, err) } defer file.Close() info, err := file.Stat() if err != nil { jsThrow(call, err) } obj, err := call.Otto.Object(`new Object()`) if err != nil { jsThrow(call, err) } size, _ := otto.ToValue(info.Size()) obj.Set("size", size) modTime, err := otto.ToValue(info.ModTime().Unix()) if err != nil { jsThrow(call, err) } obj.Set("lastModified", modTime) name, _ := otto.ToValue(info.Name()) obj.Set("name", name) isDir, _ := otto.ToValue(info.IsDir()) obj.Set("isDir", isDir) objV, _ := otto.ToValue(obj) return objV }
// _file_eachFile finds every file that matches a pattern and calls a passed // function for each file path. func _file_eachFile(call otto.FunctionCall) otto.Value { pattern, _ := call.Argument(0).ToString() f := call.Argument(1) matches, err := filepath.Glob(pattern) if err != nil { jsThrow(call, err) } for _, m := range matches { om, _ := otto.ToValue(m) f.Call(om, om) } return otto.Value{} }
func InjectLevelDB(jsEngine *JSEngine, db *leveldb.DB) { jsEngine.Run("var db = {};") dbValue, _ := jsEngine.Get("db") dbObj := dbValue.Object() dbObj.Set("put", func(call otto.FunctionCall) otto.Value { key, err := call.Argument(0).ToString() if err != nil { log.Println("Error:", err.Error()) return otto.FalseValue() } value, err := call.Argument(1).ToString() if err != nil { log.Println("Error:", err.Error()) return otto.FalseValue() } err = db.Put([]byte(key), []byte(value), nil) if err != nil { log.Println("Error:", err.Error()) return otto.FalseValue() } return otto.TrueValue() }) dbObj.Set("get", func(call otto.FunctionCall) otto.Value { key, err := call.Argument(0).ToString() if err != nil { log.Println("Error:", err.Error()) return otto.FalseValue() } data, err := db.Get([]byte(key), nil) if err != nil { log.Println("Error:", err.Error()) return otto.FalseValue() } v, _ := otto.ToValue(string(data)) return v }) dbObj.Set("remove", func(call otto.FunctionCall) otto.Value { key, err := call.Argument(0).ToString() if err != nil { log.Println("Error:", err.Error()) return otto.FalseValue() } err = db.Delete([]byte(key), nil) if err != nil { log.Println("Error:", err.Error()) return otto.FalseValue() } return otto.TrueValue() }) }
func loadDefaults(runtime *otto.Otto) error { if err := runtime.Set("defaultTTL", ttl); err != nil { return err } if err := runtime.Set("defaultEnvironment", environment); err != nil { return err } if err := runtime.Set("cleanImageName", func(call otto.FunctionCall) otto.Value { name := call.Argument(0).String() result, _ := otto.ToValue(utils.CleanImageName(name)) return result }); err != nil { return err } if err := runtime.Set("removeSlash", func(call otto.FunctionCall) otto.Value { name := call.Argument(0).String() result, _ := otto.ToValue(utils.RemoveSlash(name)) return result }); err != nil { return err } return nil }
// myIpAddress returns the IP address of the host machine. func gopacMyIpAddress() otto.Value { hostname, err := os.Hostname() if err != nil { return otto.UndefinedValue() } address := gopacDnsResolve(hostname) if value, err := otto.ToValue(address); err == nil { return value } return otto.UndefinedValue() }
func registerVM(vm *modules.JsVm) otto.Value { obj, _ := vm.Object("({})") obj.Set("md5", func(c otto.FunctionCall) otto.Value { arg1, _ := c.Argument(0).ToString() k := md5.Sum([]byte(arg1)) resp := hex.EncodeToString(k[:]) oobj, _ := otto.ToValue(resp) return oobj }) obj.Set("sha256", func(c otto.FunctionCall) otto.Value { arg1, _ := c.Argument(0).ToString() k := sha256.Sum256([]byte(arg1)) resp := hex.EncodeToString(k[:]) oobj, _ := otto.ToValue(resp) return oobj }) obj.Set("newGuid", func(c otto.FunctionCall) otto.Value { u1 := uuid.NewV4() oobj, _ := otto.ToValue(u1.String()) return oobj }) return obj.Value() }