/utils/web.py

https://github.com/paraboul/noVNC · Python · 53 lines · 33 code · 9 blank · 11 comment · 6 complexity · 95c782e3c36967f419d04601a8475acf MD5 · raw file

  1. #!/usr/bin/python
  2. '''
  3. A super simple HTTP/HTTPS webserver for python. Automatically detect
  4. You can make a cert/key with openssl using:
  5. openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem
  6. as taken from http://docs.python.org/dev/library/ssl.html#certificates
  7. '''
  8. import traceback, sys
  9. import socket
  10. import ssl
  11. #import http.server as server # python 3.X
  12. import SimpleHTTPServer as server # python 2.X
  13. def do_request(connstream, from_addr):
  14. x = object()
  15. server.SimpleHTTPRequestHandler(connstream, from_addr, x)
  16. def serve():
  17. bindsocket = socket.socket()
  18. #bindsocket.bind(('localhost', PORT))
  19. bindsocket.bind(('', PORT))
  20. bindsocket.listen(5)
  21. print("serving on port", PORT)
  22. while True:
  23. try:
  24. newsocket, from_addr = bindsocket.accept()
  25. peek = newsocket.recv(1024, socket.MSG_PEEK)
  26. if peek.startswith("\x16"):
  27. connstream = ssl.wrap_socket(
  28. newsocket,
  29. server_side=True,
  30. certfile='self.pem',
  31. ssl_version=ssl.PROTOCOL_TLSv1)
  32. else:
  33. connstream = newsocket
  34. do_request(connstream, from_addr)
  35. except Exception:
  36. traceback.print_exc()
  37. try:
  38. PORT = int(sys.argv[1])
  39. except:
  40. print "%s port" % sys.argv[0]
  41. sys.exit(2)
  42. serve()