Skip to content

Instantly share code, notes, and snippets.

@strazzere
Created June 27, 2017 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save strazzere/69a57c2c71a54ab8d510b67b68dcc7a3 to your computer and use it in GitHub Desktop.
Save strazzere/69a57c2c71a54ab8d510b67b68dcc7a3 to your computer and use it in GitHub Desktop.
safer unsafe otto run
package main
import (
"errors"
"fmt"
"os"
"time"
"github.com/robertkrimen/otto"
)
var halt = errors.New("Stahp")
func main() {
runUnsafe("(0)(eval&^=(eval))")
}
func runUnsafe(unsafe string) {
defer func() {
if caught := recover(); caught != nil {
fmt.Println("Recovered inside runUnsafe : ", caught)
}
}()
runUnsafeVM(unsafe)
}
func runUnsafeVM(unsafe string) {
start := time.Now()
defer func() {
duration := time.Since(start)
if caught := recover(); caught != nil {
if caught == halt {
fmt.Fprintf(os.Stderr, "Some code took to long! Stopping after: %v\n", duration)
return
}
panic(caught) // Something else happened, repanic!
}
fmt.Fprintf(os.Stderr, "Ran code successfully: %v\n", duration)
}()
vm := otto.New()
vm.Interrupt = make(chan func(), 1) // The buffer prevents blocking
go func() {
time.Sleep(2 * time.Second) // Stop after two seconds
vm.Interrupt <- func() {
panic(halt)
}
}()
vm.Run(unsafe) // Here be dragons (risky code)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment