Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

77 lines
2.3KB

  1. import binascii
  2. import os
  3. import exec_helpers
  4. import re
  5. from flask import request, url_for
  6. from flask_api import FlaskAPI, status, exceptions
  7. from flask_cors import CORS
  8. app = FlaskAPI(__name__)
  9. CORS(app)
  10. @app.route("/compile", methods=['POST'])
  11. def compile():
  12. if request.method == 'POST':
  13. note = str(request.data.get('source', ''))
  14. flags = str(request.data.get('flags', ''))
  15. with open("/tmp/test.cpp", "w") as f:
  16. f.write(note)
  17. f.close()
  18. stdout = ''
  19. stderr = ''
  20. retcode = 0
  21. output = ''
  22. output_wasm = ''
  23. flags = flags.replace("\n", " ")
  24. wasm = 'cheerp-mode=wasm' in flags
  25. # Simple way to disable malicious flags (hopefully)
  26. if not re.match('^[\s\ta-zA-Z0-9=\-_\.]*$', flags):
  27. flags = ""
  28. cmd = "/opt/cheerp/bin/clang {} /tmp/test.cpp -o /tmp/test.js".format(flags)
  29. if wasm:
  30. cmd = "/opt/cheerp/bin/clang {} /tmp/test.cpp -cheerp-wasm-loader=/tmp/test.js -o /tmp/test.wasm".format(flags)
  31. with exec_helpers.Subprocess() as executor:
  32. try:
  33. ret = executor.check_call(cmd, shell=True, timeout=10)
  34. if ret:
  35. retcode = ret.exit_code
  36. output = ret.stdout_str
  37. except exec_helpers.ExecHelperTimeoutError as e:
  38. #stdout = e.stdout
  39. #stderr = e.stderr
  40. stderr = str(e)
  41. except exec_helpers.CalledProcessError as e:
  42. stdout = e.stdout
  43. stderr = e.stderr
  44. if os.path.exists("/tmp/test.js"):
  45. with open("/tmp/test.js", "r") as f:
  46. output = f.read()
  47. f.close()
  48. if wasm and os.path.exists("/tmp/test.wasm"):
  49. with open("/tmp/test.wasm", "rb") as f:
  50. output_wasm = f.read()
  51. f.close()
  52. return {
  53. 'stdout': stdout,
  54. 'stderr': stderr,
  55. 'command': cmd,
  56. 'retcode': retcode,
  57. 'javascript': output,
  58. 'wasm': binascii.b2a_base64(output_wasm).decode("utf-8") if wasm else ""
  59. }, status.HTTP_201_CREATED
  60. if __name__ == "__main__":
  61. app.run(host="0.0.0.0", debug=True)