Пример #1
0
// NewAccount asks the user for the password and than executes the jeth.newAccount callback in the jsre
func (self *Jeth) NewAccount(call otto.FunctionCall) (response otto.Value) {
	var passwd string
	if len(call.ArgumentList) == 0 {
		var err error
		passwd, err = PromptPassword("Passphrase: ", true)
		if err != nil {
			return otto.FalseValue()
		}
		passwd2, err := PromptPassword("Repeat passphrase: ", true)
		if err != nil {
			return otto.FalseValue()
		}

		if passwd != passwd2 {
			fmt.Println("Passphrases don't match")
			return otto.FalseValue()
		}
	} else if len(call.ArgumentList) == 1 && call.Argument(0).IsString() {
		passwd, _ = call.Argument(0).ToString()
	} else {
		fmt.Println("expected 0 or 1 string argument")
		return otto.FalseValue()
	}

	if ret, err := call.Otto.Call("jeth.newAccount", nil, passwd); err == nil {
		return ret
	} else {
		fmt.Printf("%v\n", err)
		return otto.FalseValue()
	}

	return otto.FalseValue()
}
Пример #2
0
func (js *jsre) newAccount(call otto.FunctionCall) otto.Value {
	arg := call.Argument(0)
	var passphrase string
	if arg.IsUndefined() {
		fmt.Println("The new account will be encrypted with a passphrase.")
		fmt.Println("Please enter a passphrase now.")
		auth, err := readPassword("Passphrase: ", true)
		if err != nil {
			utils.Fatalf("%v", err)
		}
		confirm, err := readPassword("Repeat Passphrase: ", false)
		if err != nil {
			utils.Fatalf("%v", err)
		}
		if auth != confirm {
			utils.Fatalf("Passphrases did not match.")
		}
		passphrase = auth
	} else {
		var err error
		passphrase, err = arg.ToString()
		if err != nil {
			fmt.Println(err)
			return otto.FalseValue()
		}
	}
	acct, err := js.ethereum.AccountManager().NewAccount(passphrase)
	if err != nil {
		fmt.Printf("Could not create the account: %v", err)
		return otto.UndefinedValue()
	}
	return js.re.ToVal("0x" + common.Bytes2Hex(acct.Address))
}
Пример #3
0
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{}
}
Пример #4
0
//COPY
//copies a file, overwriting the destination if exists.
func _file_copy(call otto.FunctionCall) otto.Value {
	sourcePath, _ := call.Argument(0).ToString()
	destinationPath, _ := call.Argument(1).ToString()

	//check if destination exists and delete if so
	if fileExists(destinationPath) {
		if err := os.Remove(destinationPath); err != nil {
			jsThrow(call, err)
		}
	}

	//read source file
	in, err := os.Open(sourcePath)
	if err != nil {
		jsThrow(call, err)
	}
	defer in.Close()

	//create destination file
	out, err := os.Create(destinationPath)
	if err != nil {
		jsThrow(call, err)
	}
	defer out.Close()

	//copy contents of source to destination
	_, err = io.Copy(out, in)
	_ = out.Close()
	if err != nil {
		jsThrow(call, err)
	}
	return otto.Value{}
}
Пример #5
0
func _gzip_compress(call otto.FunctionCall) otto.Value {
	source, _ := call.Argument(0).ToString()
	target, _ := call.Argument(1).ToString()
	reader, err := os.Open(source)
	if err != nil {
		jsThrow(call, err)
	}

	filename := filepath.Base(source)
	target = filepath.Join(target, fmt.Sprintf("%s.gz", filename))
	writer, err := os.Create(target)
	if err != nil {
		jsThrow(call, err)
	}

	defer writer.Close()

	archiver := gzip.NewWriter(writer)
	archiver.Name = filename
	defer archiver.Close()
	_, err = io.Copy(archiver, reader)
	if err != nil {
		jsThrow(call, err)
	}

	return otto.Value{}
}
Пример #6
0
// NewAccount is a wrapper around the personal.newAccount RPC method that uses a
// non-echoing password prompt to aquire the passphrase and executes the original
// RPC method (saved in jeth.newAccount) with it to actually execute the RPC call.
func (b *bridge) NewAccount(call otto.FunctionCall) (response otto.Value) {
	var (
		password string
		confirm  string
		err      error
	)
	switch {
	// No password was specified, prompt the user for it
	case len(call.ArgumentList) == 0:
		if password, err = b.prompter.PromptPassword("Passphrase: "); err != nil {
			throwJSException(err.Error())
		}
		if confirm, err = b.prompter.PromptPassword("Repeat passphrase: "); err != nil {
			throwJSException(err.Error())
		}
		if password != confirm {
			throwJSException("passphrases don't match!")
		}

	// A single string password was specified, use that
	case len(call.ArgumentList) == 1 && call.Argument(0).IsString():
		password, _ = call.Argument(0).ToString()

	// Otherwise fail with some error
	default:
		throwJSException("expected 0 or 1 string argument")
	}
	// Password aquired, execute the call and return
	ret, err := call.Otto.Call("jeth.newAccount", nil, password)
	if err != nil {
		throwJSException(err.Error())
	}
	return ret
}
Пример #7
0
// Creates new transaction
// Ex: var t = user.Do("GET", "/")
func (t JSTransaction) Do(call otto.FunctionCall) otto.Value {
	if len(call.ArgumentList) != 2 {
		panic(errors.New("Do function takes exactly 2 parameters."))
	}

	verb, err := call.Argument(0).ToString()
	utils.UnlessNilThenPanic(err)

	path, err := call.Argument(1).ToString()
	utils.UnlessNilThenPanic(err)

	t.transaction = &Transaction{
		conquest:      t.jsconquest.conquest,
		Verb:          verb,
		Path:          path,
		Headers:       map[string]interface{}{},
		Cookies:       map[string]interface{}{},
		ResConditions: map[string]interface{}{},
		Body:          map[string]interface{}{},
	}

	if t.ctx.Transactions == nil {
		t.ctx.Transactions = []*Transaction{}
	}

	t.Response.transaction = t.transaction
	t.ctx.Transactions = append(t.ctx.Transactions, t.transaction)
	return toOttoValueOrPanic(t.jsconquest.vm, t)
}
Пример #8
0
func _tar_compress(call otto.FunctionCall) otto.Value {
	var (
		baseDir string
	)
	source, _ := call.Argument(0).ToString()
	target, _ := call.Argument(1).ToString()

	filename := filepath.Base(source)
	target = filepath.Join(target, fmt.Sprintf("%s.tar", filename))
	tarfile, err := os.Create(target)
	if err != nil {
		jsThrow(call, err)
	}
	defer tarfile.Close()

	tarball := tar.NewWriter(tarfile)
	defer tarball.Close()

	info, err := os.Stat(source)
	if err != nil {
		jsThrow(call, err)
	}

	if info.IsDir() {
		baseDir = filepath.Base(source)
	}

	err = filepath.Walk(source,
		func(path string, info os.FileInfo, err error) error {
			if err != nil {
				return err
			}

			header, err := tar.FileInfoHeader(info, info.Name())
			if err != nil {
				return err
			}

			if baseDir != "" {
				header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))
			}

			if err := tarball.WriteHeader(header); err != nil {
				return err
			}

			if info.IsDir() {
				return nil
			}

			file, err := os.Open(path)
			if err != nil {
				return err
			}
			defer file.Close()
			_, err = io.Copy(tarball, file)
			return err
		})
	return otto.Value{}
}
Пример #9
0
// Inserts a map as like "StatusCode":[code] into transactions response
// conditions
// Ex: t.Response.StatusCode(200)
func (r JSTransactionResponse) StatusCode(call otto.FunctionCall) otto.Value {
	code, err := call.Argument(0).ToInteger()
	utils.UnlessNilThenPanic(err)

	r.transaction.ResConditions["StatusCode"] = code
	return toOttoValueOrPanic(r.jsconquest.vm, r)
}
Пример #10
0
// Inserts a map as like "Contains":[substr] into transactions response
// conditions
// Ex: t.Response.Contains("<h1>Fancy Header</h1>")
func (r JSTransactionResponse) Contains(call otto.FunctionCall) otto.Value {
	substr, err := call.Argument(0).ToString()
	utils.UnlessNilThenPanic(err)

	r.transaction.ResConditions["Contains"] = substr
	return toOttoValueOrPanic(r.jsconquest.vm, r)
}
Пример #11
0
// conquest.prototype.Cookies
// Sets total user count and calls user defined functions with JSTransactionCtx
// Ex: conquest.Users(100, function(user){})
func (c JSConquest) Users(call otto.FunctionCall) otto.Value {
	if len(call.ArgumentList) != 2 {
		panic(errors.New("conquest.Users method takes exactly 2 arguments."))
	}

	uc, err := call.Argument(0).ToInteger()
	utils.UnlessNilThenPanic(err)

	if uc <= 0 {
		panic(errors.New("Total users can not be equal zero or lesser."))
	}

	c.conquest.TotalUsers = uint64(uc)

	fn := call.Argument(1)
	if !fn.IsFunction() {
		panic(errors.New("Users function argument 2 must be a function."))
	}

	ctx := NewJSTransactionCtx(&c)
	ctxObj := toOttoValueOrPanic(c.vm, *ctx)

	_, err = fn.Call(fn, ctxObj)
	utils.UnlessNilThenPanic(err)

	return toOttoValueOrPanic(c.vm, c)
}
Пример #12
0
// sets initial cookies and headers for conquest
func conquestInitials(conquest *Conquest, method string, call *otto.FunctionCall) {
	arg := call.Argument(0)
	panicStr := method + " function parameter 1 must be an object."

	if arg.Class() != "Object" {
		panic(errors.New(panicStr))
	}

	argObj := arg.Object()
	if argObj == nil {
		panic(errors.New(panicStr))
	}

	for _, k := range argObj.Keys() {
		val, err := argObj.Get(k)
		if err != nil {
			panic(err)
		}

		valStr, err := val.ToString()
		if err != nil {
			panic(err)
		}

		if _, exists := conquest.Initials[method]; !exists {
			conquest.Initials[method] = map[string]interface{}{}
		}

		conquest.Initials[method][k] = valStr
	}
}
Пример #13
0
func apiGetState(call otto.FunctionCall) otto.Value {
	state := call.Argument(0).String()

	value := core.StateTracker.Get(state)
	result, _ := call.Otto.ToValue(value)
	return result
}
Пример #14
0
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
}
Пример #15
0
func command(call otto.FunctionCall) otto.Value {
	cmd, _ := call.Argument(0).ToString()
	c := NewCommand(cmd)
	c.Run()
	displayError("executing command", &c.Result)
	return convertResultToObject(&c.Result)
}
Пример #16
0
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))
}
Пример #17
0
func _gzip_decompress(call otto.FunctionCall) otto.Value {
	source, _ := call.Argument(0).ToString()
	target, _ := call.Argument(1).ToString()

	reader, err := os.Open(source)
	if err != nil {
		jsThrow(call, err)
	}

	archive, err := gzip.NewReader(reader)
	if err != nil {
		jsThrow(call, err)
	}

	defer archive.Close()

	target = filepath.Join(target, archive.Name)
	writer, err := os.Create(target)
	if err != nil {
		jsThrow(call, err)
	}
	defer writer.Close()

	_, err = io.Copy(writer, archive)
	if err != nil {
		jsThrow(call, err)
	}
	return otto.Value{}
}
Пример #18
0
// Add Response API
func plurk_AddResponse(call otto.FunctionCall) otto.Value {

	plurkID, _ := call.Argument(0).ToInteger()
	message, _ := call.Argument(1).ToString()
	qualifier, _ := call.Argument(2).ToString()

	if plurkID == 0 {
		logger.Error("Plurk ID not specify, add response failed!")
		return otto.FalseValue()
	}

	if len(message) <= 0 || message == "undefined" {
		logger.Error("No plurk content specify, add response failed!")
		return otto.FalseValue()
	}

	if qualifier == "undefined" {
		qualifier = ":"
	}

	responses := client.GetResponses()
	res, err := responses.ResponseAdd(int(plurkID), message, qualifier)

	if err != nil {
		logger.Error("Add response failed, because %s", err.Error())
	}

	logger.Info("Add response success, content is %s", res.RawContent)

	return otto.TrueValue()
}
Пример #19
0
// Sleep will block the console for the specified number of seconds.
func (b *bridge) Sleep(call otto.FunctionCall) (response otto.Value) {
	if call.Argument(0).IsNumber() {
		sleep, _ := call.Argument(0).ToInteger()
		time.Sleep(time.Duration(sleep) * time.Second)
		return otto.TrueValue()
	}
	return throwJSException("usage: sleep(<number of seconds>)")
}
Пример #20
0
func (no *testNativeObjectBinding) TestMethod(call otto.FunctionCall) otto.Value {
	m, err := call.Argument(0).ToString()
	if err != nil {
		return otto.UndefinedValue()
	}
	v, _ := call.Otto.ToValue(&msg{m})
	return v
}
Пример #21
0
func _system_kill(call otto.FunctionCall) otto.Value {
	processName, _ := call.Argument(0).ToString()
	commandStrings := []string{"/F", "/IM", processName}
	if err := exec.Command("taskkill", commandStrings...).Run(); err != nil {
		jsThrow(call, err)
	}
	return otto.Value{}
}
Пример #22
0
func symlink(call otto.FunctionCall) otto.Value {
	source, _ := call.Argument(0).ToString()
	destination, _ := call.Argument(1).ToString()
	symlink := NewSymlink(source, destination)
	symlink.Run()
	displayError("creating symlink", &symlink.Result)
	return convertResultToObject(&symlink.Result)
}
Пример #23
0
// Sets request body or query
// Ex: t.Body({
// "field1": "value",
// "field2":"value",
// "field3": function(fetch){ return fetch.FromDisk("/path", "mime-type"); },
// })
func (t JSTransaction) Body(call otto.FunctionCall) otto.Value {
	t.unlessAllocatedThenPanic()

	arg := call.Argument(0)
	panicStr := "Body function parameter 1 must be an object."

	if arg.Class() != "Object" {
		panic(errors.New(panicStr))
	}

	argObj := arg.Object()
	if argObj == nil {
		panic(errors.New(panicStr))
	}

	for _, k := range argObj.Keys() {
		val, err := argObj.Get(k)
		if err != nil {
			panic(err)
		}

		if val.IsFunction() {
			fetch := &JSFetch{
				jsconquest: t.jsconquest,
			}
			jsf := toOttoValueOrPanic(t.jsconquest.vm, *fetch)
			retfn, err := val.Call(val, jsf)
			if err != nil {
				panic(err)
			}
			exp, err := retfn.Export()
			if err != nil {
				panic(err)
			}

			notation, err := mapToFetchNotation(exp.(map[string]interface{}))
			if err != nil {
				panic(err)
			}
			if notation.Type == FETCH_DISK {
				t.transaction.isMultiPart = true
			}
			t.transaction.Body[k] = notation

			continue
		}

		valStr, err := val.ToString()
		if err != nil {
			panic(err)
		}

		t.transaction.Body[k] = valStr

	}

	return toOttoValueOrPanic(t.jsconquest.vm, t)
}
Пример #24
0
func (rt *gopacRuntime) dnsDomainLevels(call otto.FunctionCall) otto.Value {
	if host, err := call.Argument(0).ToString(); err == nil {
		if value, err := rt.vm.ToValue(gopacDnsDomainLevels(host)); err == nil {
			return value
		}
	}

	return otto.Value{}
}
Пример #25
0
func upstart(call otto.FunctionCall) otto.Value {
	svc, _ := call.Argument(0).ToString()
	action, _ := call.Argument(1).ToString()
	upstart := NewUpstart(svc, action)

	upstart.Run()
	displayError("with upstart", &upstart.Result)
	return convertResultToObject(&upstart.Result)
}
Пример #26
0
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
}
Пример #27
0
//DELETE
//deletes path/file and any children it contains
func _file_delete(call otto.FunctionCall) otto.Value {
	path, _ := call.Argument(0).ToString()

	err := os.RemoveAll(path)
	if err != nil {
		jsThrow(call, err)
	}
	return otto.Value{}
}
Пример #28
0
//MKDIR
//creates a directory, along with any necessary parents
func _file_mkdir(call otto.FunctionCall) otto.Value {
	path, _ := call.Argument(0).ToString()

	err := os.MkdirAll(path, 0755)
	if err != nil {
		jsThrow(call, err)
	}
	return otto.Value{}
}
Пример #29
0
func (rt *gopacRuntime) isPlainHostName(call otto.FunctionCall) otto.Value {
	if host, err := call.Argument(0).ToString(); err == nil {
		if value, err := rt.vm.ToValue(gopacIsPlainHostName(host)); err == nil {
			return value
		}
	}

	return otto.Value{}
}
Пример #30
0
func CmdHello(call otto.FunctionCall) (val otto.Value) {
	name, err := call.Argument(0).ToString()
	if err != nil {
		sh.PrintError(err)
		return gosh.Undefined
	}

	return sh.Value("Hello " + name)
}