Example #1
0
  def doPost(self, request, response):
    c = NomjycContainer()
    c.parameters = request.getParameterMap()

    log = open("/var/log/nomjyc/sandbox.log","a")
    safelog = dict(c.parameters)
    if "pass" in safelog:
      safelog["pass"]=len(safelog["pass"])
    log.write(("[[%s]] %s %s\n" % (request.getRemoteAddr(), datetime.utcnow(), self.yaml.dump(safelog))).encode("utf-8"))
    log.close()

    output = "<div class=\"infobox\"><span class=\"gh\">nomjyc 0.1</span>\n"
    c.session    = {}
    if len(c.parameters)==0:
      output += "<pre>%s</pre>" % self.__doc__
    output += "</div>"

    c.salt="dckx"

    try:
      c.data = self.yaml.load(FileInputStream("/var/lib/tomcat6/webapps/nomjyc/data/nomjyc.yaml"))
    except:
      output += self.explainException("Error while initiating game state")

    # Print some debug information - for now.
    output += self.divHideCode("infobox", "Request", "reqi", self.dumpYaml(c.parameters), visible=True)
    output += self.divHideCode("infobox", "Data read", "dri", self.dumpYaml(c.data))

    # Add a final rule, if the test parameter is set
    if "test" in c.parameters:
      for code in c.parameters["test"]:
        c.data["rules"].add({"author":"impromptu", "code":code, "creation":datetime.utcnow(), "title":"test rule"})

    cycles = 1
    if "cycles" in c.parameters:
      try: 
        cycles = int(c.parameters["cycles"][0])
      except:
        pass
    if cycles<0 or cycles>3:
      cycles = 1

    # Execute all rules against the user input
    brain = PythonInterpreter()
    c.sandbox = True # a flag that gives away that we are in a sandbox
    for i in range(cycles):
      c.cycle = i    # a counter for the cycle we are in
      for rule in c.data["rules"][:]: # we are going to modify the rules. a lot. this prevents concurrent modification.
        try:
          output += self.divHideCode("rulebox", "Executing rule '%s'" % rule["title"], "id"+str(random()), self.dumpPython(rule["code"]), openend=True)
   	  err = StringWriter()
  	  out = StringWriter()
          checksum = hashlib.md5(self.yaml.dump(c.data)).hexdigest()
          brain.set("self", c)
          brain.setErr(err)
          brain.setOut(out)
          before = time.time()
          timeout (brain.exec,(rule["code"],),timeout_duration=30)
          runtime = int((time.time()-before) * 1000)
          changes = (checksum != hashlib.md5(self.yaml.dump(c.data)).hexdigest())
          output += "<div class=\"ruleoutput\">"
          if changes: output += "<div class=\"erroroutput\">This rule changed the game data.</div>"
          if (err.getBuffer().length()): output += "<div class=\"erroroutput\">Err:<br />%s</div>" % self.dumpPythonTB(err.toString().strip())
          if (out.getBuffer().length()): output += "<div class=\"gu\">Out:</div>"+out.toString().strip()
          output += "<div>(runtime: %sms)</div></div></div>" % runtime

        except Exception, ex:
          output += self.explainException("Execution failed") + "</div>"
Example #2
0
  def doPost(self, request, response):
    c = NomjycContainer() # re-initialized container upon every request    
    c.parameters = request.getParameterMap()
    
    log = open("/var/log/nomjyc/nomjyc.log","a")
    safelog = dict(c.parameters)
    if "pass" in safelog:
      safelog["pass"]=len(safelog["pass"])
    log.write(("[[%s]] %s %s\n" % (request.getRemoteAddr(), datetime.utcnow(), self.yaml.dump(safelog))).encode("utf-8"))
    log.close()

    output = "<div class=\"infobox\"><span class=\"gh\">nomjyc 0.1</span>\n"
    c.session    = {}
    if len(c.parameters)==0:
      output += "<pre>%s</pre>" % self.__doc__
    output += "</div>"

    c.salt="dckx"

    try:
      c.data = self.yaml.load(FileInputStream("/var/lib/tomcat6/webapps/nomjyc/data/nomjyc.yaml"))
    except:
      output += self.explainException("Error while initiating game state - trying to load backup.")
      c.data = self.yaml.load(FileInputStream("/var/lib/tomcat6/webapps/nomjyc/data/nomjyc.bak"))

    # Print some debug information - for now.
    output += self.divHideCode("infobox", "Request", "reqi", self.dumpYaml(c.parameters), visible=True)
    output += self.divHideCode("infobox", "Data read", "dri", self.dumpYaml(c.data))

    # If we have come so far, we assume that it is safe to write a backup.
    try:
      self.yaml.dump(c.data, FileWriter("/var/lib/tomcat6/webapps/nomjyc/data/nomjyc.bak"))    
    except:
      output += self.explainException("Error while storing backup game state")
    
    # Execute all rules against the user input
    brain = PythonInterpreter()
    c.sandbox = False # a flag that tells that we are not in a sandbox
    checksum = hashlib.md5(self.yaml.dump(c.data)).hexdigest()
    for rule in c.data["rules"][:]: # we are going to modify the rules. a lot. this prevents concurrent modification.
      try:
        output += self.divHideCode("rulebox", "Executing rule '%s'" % rule["title"], "id"+str(random()), self.dumpPython(rule["code"]), openend=True)
        err = StringWriter()
        out = StringWriter()
        # Compile the rule into a jython/java class
        brain.set("self", c) # expose the container to the rules
        brain.setErr(err)
        brain.setOut(out)
        before = time.time()
        timeout (brain.exec,(rule["code"],),timeout_duration=30)
        runtime = int((time.time()-before) * 1000)
        newsum   = hashlib.md5(self.yaml.dump(c.data)).hexdigest()
        changes  = (checksum != newsum)
        checksum = newsum
        output += "<div class=\"ruleoutput\">" 
        if changes: output += "<div class=\"erroroutput\">This rule changed the game data.</div>"
        if (err.getBuffer().length()): output += "<div class=\"erroroutput\">Err:<br />%s</div>" % self.dumpPythonTB(err.toString())
        if (out.getBuffer().length()): output += "<div class=\"gu\">Out:</div>"+out.toString()
        output += "<div>(runtime: %sms)</div></div></div>" % runtime

      except Exception, ex:
        output += self.explainException("Execution failed") + "</div>"