1# ----------------------------------------------------------------------------- 2# Copyright (c) 2014-2019, PyInstaller Development Team. 3# 4# Distributed under the terms of the GNU General Public License with exception 5# for distributing bootloader. 6# 7# The full license is in the file COPYING.txt, distributed with this software. 8# ----------------------------------------------------------------------------- 9import socket 10 11try: 12 import BaseHTTPServer 13 import SimpleHTTPServer 14except ImportError: 15 import http.server as BaseHTTPServer 16 import http.server as SimpleHTTPServer 17 18import os 19import ssl 20import sys 21import threading 22import time 23 24import requests 25 26""" 27Note: to re-create the server.pem file use the 28following commands. 29 30cd /path/to/pyinstaller.git/tests/functional 31openssl req -new -x509 -keyout data/requests/server.pem \ 32 -text -out data/requests/server.pem -days 36500 \ 33 -nodes -config data/requests/openssl.conf 34""" 35 36if getattr(sys, 'frozen', False): 37 # we are running in a |PyInstaller| bundle 38 basedir = sys._MEIPASS 39else: 40 # we are running in a normal Python environment 41 basedir = os.path.dirname(__file__) 42 43 44SERVER_CERT = os.path.join(basedir, u"server.pem") 45 46 47if not os.path.exists(SERVER_CERT): 48 raise SystemExit('Certificate-File %s is missing' % SERVER_CERT) 49 50 51def main(): 52 53 SERVER_PORT = 8443 54 httpd = None 55 56 # Since unit tests run in parallel, the port may be in use, so 57 # retry creating the server while incrementing the port number 58 while SERVER_PORT < 8493: # Max 50 retries 59 try: 60 # SSL server copied from here: 61 # http://www.piware.de/2011/01/creating-an-https-server-in-python/ 62 httpd = BaseHTTPServer.HTTPServer( 63 ('localhost', SERVER_PORT), 64 SimpleHTTPServer.SimpleHTTPRequestHandler) 65 except socket.error as e: 66 if e.errno == 98: # Address in use 67 SERVER_PORT += 1 68 continue 69 else: 70 # Some other socket.error 71 raise 72 else: 73 # Success 74 break 75 else: 76 # Did not break from loop, so we ran out of retries 77 assert False, "Could not bind server port: all ports in use." 78 79 httpd.socket = ssl.wrap_socket( 80 httpd.socket, certfile=SERVER_CERT, server_side=True 81 ) 82 83 def ssl_server(): 84 httpd.serve_forever() 85 86 # Start the SSL server 87 thread = threading.Thread(target=ssl_server) 88 thread.daemon = True 89 thread.start() 90 91 # Wait a bit for the server to start 92 time.sleep(1) 93 94 # Use requests to get a page from the server 95 requests.get( 96 u"https://localhost:{}".format(SERVER_PORT), 97 verify=SERVER_CERT) 98 # requests.get("https://github.com") 99 100if __name__ == '__main__': 101 main() 102