Repository navigation
Expand file tree
/
Copy pathhttps.py
More file actions
672 lines (577 loc) · 24.3 KB
/
Copy pathhttps.py
File metadata and controls
672 lines (577 loc) · 24.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Read-only HTTPS static file server for Python 2.7 and Python 3."""
from __future__ import print_function
import argparse
import datetime
import os
import posixpath
import shutil
import socket
import ssl
import subprocess
import sys
import threading
import time
import webbrowser
try:
from http.server import HTTPServer, SimpleHTTPRequestHandler
from socketserver import ThreadingMixIn
from urllib.parse import unquote, urlsplit
except ImportError:
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
from SocketServer import ThreadingMixIn
from urllib import unquote
from urlparse import urlsplit
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
DEFAULT_CERT = os.path.join(SCRIPT_DIR, "cert.pem")
DEFAULT_KEY = os.path.join(SCRIPT_DIR, "key.pem")
ALLOWED_METHODS = "GET, HEAD, OPTIONS"
try:
text_type = unicode
binary_type = str
except NameError:
text_type = str
binary_type = bytes
MESSAGES = {
"en": {
"description": "Read-only HTTPS static file server",
"help_help": "show this help message and exit",
"port_help": "port to listen on (default: 8443)",
"directory_help": "directory to serve (default: script directory)",
"bind_help": "address to bind (default: 0.0.0.0)",
"cert_help": "TLS certificate file",
"key_help": "TLS private key file",
"no_open_help": "do not open the local URL in a browser",
"no_pause_help": "never wait for Enter after a fatal error",
"lang_help": "console language: auto, zh, or en (auto uses Chinese only at UTC+08:00)",
"port_invalid": "port must be between 1 and 65535",
"not_directory": "Not a directory: {0}",
"cert_missing": "HTTPS requires certificate files. Missing: {0}",
"cert_unreadable": "HTTPS requires readable certificate files; cannot read {0}: {1}",
"cert_unusable": "HTTPS requires usable certificate files. Could not load {0} and {1}: {2}",
"cert_generating": "Generating self-signed certificate...",
"cert_generate_failed": ("Could not create certificate files {0} and {1}. Details: {2}. "
"Install the 'cryptography' Python package or put openssl on PATH, "
"or place your own cert.pem and key.pem next to this script."),
"bind_denied": "Permission denied binding to {0}; choose a non-privileged port or check local security policy",
"bind_used": "Address {0} is already in use; choose another port",
"bind_failed": "Could not bind to {0}: {1}",
"started": "HTTPS server started",
"local_url": "Local URL: {0}",
"lan_url": "LAN access: {0}",
"lan_hint": "LAN access: use this computer's LAN IP with port {0}",
"browser_failed": "Warning: could not open browser: {0}",
"browser_manual": "Open this URL manually: {0}",
"browser_none": "no browser accepted the URL",
"stopped": "Server stopped.",
"error": "Error: {0}",
"pause": "Press Enter to close this window...",
"error_title": "HTTPS server error"
},
"zh": {
"description": u"只读 HTTPS 静态文件服务器",
"help_help": u"显示此帮助信息并退出",
"port_help": u"监听端口(默认:8443)",
"directory_help": u"要提供的目录(默认:脚本目录)",
"bind_help": u"绑定地址(默认:0.0.0.0)",
"cert_help": u"TLS 证书文件",
"key_help": u"TLS 私钥文件",
"no_open_help": u"不在浏览器中打开本地网址",
"no_pause_help": u"发生致命错误后不等待按 Enter 键",
"lang_help": u"控制台语言:auto、zh 或 en(auto 仅在 UTC+08:00 时使用中文)",
"port_invalid": u"端口必须在 1 到 65535 之间",
"not_directory": u"不是目录:{0}",
"cert_missing": u"HTTPS 需要证书文件。缺少:{0}",
"cert_unreadable": u"HTTPS 需要可读取的证书文件;无法读取 {0}:{1}",
"cert_unusable": u"HTTPS 需要有效的证书文件。无法加载 {0} 和 {1}:{2}",
"cert_generating": u"正在生成自签名证书...",
"cert_generate_failed": (u"无法创建证书文件 {0} 和 {1}。详细信息:{2}。"
u"请安装 cryptography 库或将 openssl 加入 PATH,"
u"或在此脚本旁放置 cert.pem 和 key.pem。"),
"bind_denied": u"没有权限绑定到 {0};请选择非特权端口或检查本地安全策略",
"bind_used": u"地址 {0} 已被占用;请选择其他端口",
"bind_failed": u"无法绑定到 {0}:{1}",
"started": u"HTTPS 服务器已启动",
"local_url": u"本机网址:{0}",
"lan_url": u"局域网访问:{0}",
"lan_hint": u"局域网访问:请使用此计算机的局域网 IP 和端口 {0}",
"browser_failed": u"警告:无法打开浏览器:{0}",
"browser_manual": u"请手动打开此网址:{0}",
"browser_none": u"没有浏览器接受该网址",
"stopped": u"服务器已停止。",
"error": u"错误:{0}",
"pause": u"按 Enter 键关闭此窗口...",
"error_title": u"HTTPS 服务器错误"
}
}
def unicode_text(value):
if isinstance(value, text_type):
return value
if isinstance(value, binary_type):
try:
return value.decode("utf-8")
except (UnicodeDecodeError, AttributeError):
return value.decode("utf-8", "replace")
try:
return text_type(value)
except Exception:
return text_type(repr(value))
def ascii_text(value):
value = unicode_text(value)
return "".join(ch if 32 <= ord(ch) < 127 else "?" for ch in value)
def message(lang, key, *values):
template = MESSAGES.get(lang, MESSAGES["en"])[key]
return template.format(*tuple(unicode_text(value) for value in values))
def current_utc_offset_seconds(timestamp=None):
"""Return the current local UTC offset, including the active DST rule."""
if timestamp is None:
timestamp = time.time()
local = time.localtime(timestamp)
west = time.altzone if local.tm_isdst > 0 and time.daylight else time.timezone
return -int(west)
def automatic_language(offset_seconds=None):
if offset_seconds is None:
offset_seconds = current_utc_offset_seconds()
return "zh" if offset_seconds == 8 * 60 * 60 else "en"
def prescan_language(argv):
selected = "auto"
for index, item in enumerate(argv):
if item == "--lang" and index + 1 < len(argv):
selected = argv[index + 1]
elif item.startswith("--lang="):
selected = item.split("=", 1)[1]
return automatic_language() if selected not in ("zh", "en") else selected
class Handler(SimpleHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def translate_path(self, path):
path = unquote(urlsplit(path).path)
trailing = path.endswith("/")
result = self.server.serve_directory
for word in posixpath.normpath(path).split("/"):
drive, word = os.path.splitdrive(word)
head, word = os.path.split(word)
if word and word not in (os.curdir, os.pardir):
result = os.path.join(result, word)
return result + (os.sep if trailing else "")
def end_headers(self):
self.send_header("X-Content-Type-Options", "nosniff")
self.send_header("Cache-Control", "no-store")
SimpleHTTPRequestHandler.end_headers(self)
def do_OPTIONS(self):
self.send_response(204)
self.send_header("Allow", ALLOWED_METHODS)
self.send_header("Content-Length", "0")
self.end_headers()
def reject_write(self):
self.close_connection = True
self.send_response(405, "Method Not Allowed")
self.send_header("Allow", ALLOWED_METHODS)
self.send_header("Connection", "close")
self.send_header("Content-Length", "0")
self.end_headers()
do_POST = reject_write
do_PUT = reject_write
do_DELETE = reject_write
do_PATCH = reject_write
do_TRACE = reject_write
do_CONNECT = reject_write
def log_message(self, fmt, *args):
SimpleHTTPRequestHandler.log_message(
self, ascii_text(fmt), *tuple(ascii_text(item) for item in args))
class ThreadingServer(ThreadingMixIn, HTTPServer):
allow_reuse_address = True
daemon_threads = True
class IPv6ThreadingServer(ThreadingServer):
address_family = socket.AF_INET6
def server_class(bind):
try:
info = socket.getaddrinfo(bind, None, 0, socket.SOCK_STREAM)
if info and info[0][0] == socket.AF_INET6:
return IPv6ThreadingServer
except socket.gaierror:
pass
return ThreadingServer
def ssl_context():
if not hasattr(ssl, "SSLContext"):
return None
protocol = getattr(ssl, "PROTOCOL_TLS_SERVER",
getattr(ssl, "PROTOCOL_TLS", ssl.PROTOCOL_SSLv23))
return ssl.SSLContext(protocol)
def find_executable(name):
"""Locate an executable on PATH with a Python 2.7 compatible fallback."""
which = getattr(shutil, "which", None)
if which is not None:
return which(name)
path_env = os.environ.get("PATH", "")
if os.name == "nt":
extensions = [".exe", ".bat", ".cmd", ""]
for directory in path_env.split(os.pathsep):
if not directory:
continue
for ext in extensions:
candidate = os.path.join(directory, name + ext)
if os.path.isfile(candidate):
return candidate
else:
for directory in path_env.split(os.pathsep):
if not directory:
continue
candidate = os.path.join(directory, name)
if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
return candidate
return None
def _remove_if_exists(path):
try:
if os.path.isfile(path):
os.remove(path)
except Exception:
pass
def _now_utc():
"""UTC 'now' that avoids the deprecated datetime.utcnow() when possible."""
tz = getattr(datetime, "timezone", None)
if tz is not None:
return datetime.datetime.now(tz.utc)
return datetime.datetime.utcnow()
def _generate_with_cryptography(cert_file, key_file):
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
try:
import ipaddress
except ImportError:
ipaddress = None
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
subject = x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, u"localhost"),
])
now = _now_utc()
builder = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(subject)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(now)
.not_valid_after(now + datetime.timedelta(days=3650))
)
san = [x509.DNSName(u"localhost")]
if ipaddress is not None:
try:
san.append(x509.IPAddress(ipaddress.ip_address(u"127.0.0.1")))
san.append(x509.IPAddress(ipaddress.ip_address(u"::1")))
except Exception:
pass
builder = builder.add_extension(
x509.SubjectAlternativeName(san), critical=False)
builder = builder.add_extension(
x509.BasicConstraints(ca=True, path_length=None), critical=True)
cert = builder.sign(key, hashes.SHA256())
key_bytes = key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption())
cert_bytes = cert.public_bytes(serialization.Encoding.PEM)
with open(key_file, "wb") as handle:
handle.write(key_bytes)
with open(cert_file, "wb") as handle:
handle.write(cert_bytes)
def _generate_with_openssl(cert_file, key_file):
openssl = find_executable("openssl")
if not openssl:
raise RuntimeError("openssl executable not found on PATH")
base = [
openssl, "req", "-x509", "-newkey", "rsa:2048", "-nodes",
"-days", "3650", "-subj", "/CN=localhost",
"-keyout", key_file, "-out", cert_file,
]
attempts = [
base + ["-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1,IP:::1"],
base,
]
last_error = "openssl failed"
creationflags = 0
if os.name == "nt":
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
for cmd in attempts:
_remove_if_exists(cert_file)
_remove_if_exists(key_file)
try:
process = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
creationflags=creationflags,
)
except OSError as exc:
raise RuntimeError("failed to start openssl: %s" % exc)
_, err = process.communicate()
if process.returncode == 0 and os.path.isfile(cert_file) and os.path.isfile(key_file):
return
if err:
try:
last_error = err.decode("utf-8", "replace").strip() or last_error
except Exception:
last_error = unicode_text(err) or last_error
_remove_if_exists(cert_file)
_remove_if_exists(key_file)
raise RuntimeError(last_error)
def generate_self_signed_cert(cert_file, key_file):
"""Try to create a self-signed certificate. Returns the generator name."""
errors = []
try:
_generate_with_cryptography(cert_file, key_file)
return "cryptography"
except Exception as exc:
errors.append("cryptography: %s" % exc)
_remove_if_exists(cert_file)
_remove_if_exists(key_file)
try:
_generate_with_openssl(cert_file, key_file)
return "openssl"
except Exception as exc:
errors.append("openssl: %s" % exc)
_remove_if_exists(cert_file)
_remove_if_exists(key_file)
raise RuntimeError("; ".join(errors) if errors else "no generator available")
def ensure_certificate_files(cert_file, key_file, lang="en"):
missing = []
if not os.path.isfile(cert_file):
missing.append(cert_file)
if not os.path.isfile(key_file):
missing.append(key_file)
if missing:
raise RuntimeError(message(lang, "cert_missing", ", ".join(missing)))
for path in (cert_file, key_file):
try:
handle = open(path, "rb")
handle.close()
except (IOError, OSError) as exc:
raise RuntimeError(message(lang, "cert_unreadable", path, exc))
def wrap_socket(httpd, cert_file, key_file, lang="en"):
try:
context = ssl_context()
if context is not None and hasattr(context, "load_cert_chain"):
context.load_cert_chain(cert_file, key_file)
httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
else:
httpd.socket = ssl.wrap_socket(
httpd.socket, certfile=cert_file, keyfile=key_file,
server_side=True, ssl_version=ssl.PROTOCOL_SSLv23)
except Exception as exc:
raise RuntimeError(message(lang, "cert_unusable", cert_file, key_file, exc))
def socket_error_message(exc, bind, port, lang="en"):
error_number = getattr(exc, "errno", None)
if error_number is None and getattr(exc, "args", None):
error_number = exc.args[0]
address = "%s:%s" % (bind, port)
if error_number in (13, 10013):
return message(lang, "bind_denied", address)
if error_number in (48, 98, 10048):
return message(lang, "bind_used", address)
return message(lang, "bind_failed", address, exc)
def write_line(stream, value):
"""Write Unicode when possible, with safe legacy-console fallbacks."""
if stream is None:
return False
value = unicode_text(value) + u"\n"
try:
stream.write(value)
stream.flush()
return True
except Exception:
pass
try:
encoding = getattr(stream, "encoding", None) or "ascii"
data = value.encode(encoding, "replace")
if sys.version_info[0] >= 3 and hasattr(stream, "buffer"):
stream.buffer.write(data)
else:
stream.write(data)
stream.flush()
return True
except Exception:
try:
stream.write(ascii_text(value))
stream.flush()
return True
except Exception:
return False
def local_lan_address():
"""Best-effort LAN address discovery without sending application data."""
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
probe.connect(("192.0.2.1", 9))
return probe.getsockname()[0]
except socket.error:
try:
return socket.gethostbyname(socket.gethostname())
except socket.error:
return None
finally:
probe.close()
def display_host(host):
if ":" in host and not host.startswith("["):
return "[" + host + "]"
return host
def open_browser(url, lang="en"):
"""Open a trusted, locally constructed URL using stdlib-only fallbacks."""
errors = []
try:
if webbrowser.open(url, new=2):
return True
except Exception as exc:
errors.append(exc)
if os.name == "nt" and hasattr(os, "startfile"):
try:
os.startfile(url)
return True
except Exception as exc:
errors.append(exc)
try:
controller = webbrowser.get()
if controller.open(url, new=2):
return True
except Exception as exc:
errors.append(exc)
detail = errors[-1] if errors else message(lang, "browser_none")
write_line(sys.stderr, message(lang, "browser_failed", detail))
write_line(sys.stderr, message(lang, "browser_manual", url))
return False
def delayed_browser_open(url, lang="en", delay=0.25):
time.sleep(delay)
open_browser(url, lang)
def start_browser_thread(url, lang="en"):
thread = threading.Thread(target=delayed_browser_open, args=(url, lang))
thread.daemon = True
thread.start()
return thread
def run(args):
lang = args.lang
directory = os.path.abspath(args.directory)
cert_file = os.path.abspath(args.cert)
key_file = os.path.abspath(args.key)
if not os.path.isdir(directory):
raise RuntimeError(message(lang, "not_directory", directory))
# Only auto-generate when *both* files are absent. If the user already
# supplied one of them we leave it untouched and let the normal checks
# report the missing half instead of overwriting existing material.
if not os.path.isfile(cert_file) and not os.path.isfile(key_file):
write_line(sys.stdout, message(lang, "cert_generating"))
try:
generate_self_signed_cert(cert_file, key_file)
except Exception as exc:
raise RuntimeError(message(lang, "cert_generate_failed",
cert_file, key_file, exc))
ensure_certificate_files(cert_file, key_file, lang)
try:
httpd = server_class(args.bind)((args.bind, args.port), Handler)
except (socket.error, socket.gaierror) as exc:
raise RuntimeError(socket_error_message(exc, args.bind, args.port, lang))
httpd.serve_directory = directory
try:
# Do not announce readiness or schedule a browser until the listening
# socket has successfully become a TLS socket.
wrap_socket(httpd, cert_file, key_file, lang)
port = httpd.server_address[1]
wildcard = args.bind in ("0.0.0.0", "::", "")
local_host = "::1" if args.bind == "::" else "127.0.0.1"
open_host = local_host if wildcard else args.bind
url = "https://%s:%s/" % (display_host(open_host), port)
write_line(sys.stdout, message(lang, "started"))
write_line(sys.stdout, message(lang, "local_url", url))
if wildcard:
lan_host = local_lan_address()
if lan_host:
lan_url = "https://%s:%s/" % (display_host(lan_host), port)
write_line(sys.stdout, message(lang, "lan_url", lan_url))
else:
write_line(sys.stdout, message(lang, "lan_hint", port))
# The delay runs in a daemon thread. By the time it expires,
# serve_forever below is already processing connections.
if not args.no_open:
start_browser_thread(url, lang)
httpd.serve_forever()
except KeyboardInterrupt:
write_line(sys.stdout, message(lang, "stopped"))
finally:
httpd.server_close()
def parse_args(argv=None):
actual_argv = list(sys.argv[1:] if argv is None else argv)
lang = prescan_language(actual_argv)
parser = argparse.ArgumentParser(add_help=False,
description=message(lang, "description"))
parser.add_argument("-h", "--help", action="help",
help=message(lang, "help_help"))
parser.add_argument("-p", "--port", type=int, default=8443,
help=message(lang, "port_help"))
parser.add_argument("-d", "--directory", default=SCRIPT_DIR,
help=message(lang, "directory_help"))
parser.add_argument("-b", "--bind", default="0.0.0.0",
help=message(lang, "bind_help"))
parser.add_argument("--cert", default=DEFAULT_CERT,
help=message(lang, "cert_help"))
parser.add_argument("--key", default=DEFAULT_KEY,
help=message(lang, "key_help"))
parser.add_argument("--lang", choices=("auto", "zh", "en"), default="auto",
help=message(lang, "lang_help"))
parser.add_argument("--no-open", action="store_true",
help=message(lang, "no_open_help"))
parser.add_argument("--no-pause", action="store_true",
help=message(lang, "no_pause_help"))
args = parser.parse_args(actual_argv)
args.lang = automatic_language() if args.lang == "auto" else args.lang
if not 1 <= args.port <= 65535:
parser.error(message(args.lang, "port_invalid"))
return args
def show_windows_error(value, lang="en"):
"""Show a fatal error when pythonw provides no console streams."""
if os.name != "nt":
return False
try:
import ctypes
ctypes.windll.user32.MessageBoxW(
None, unicode_text(value), message(lang, "error_title"), 0x10)
return True
except Exception:
return False
def stdin_is_interactive():
if sys.stdin is None:
return False
try:
return bool(sys.stdin.isatty())
except Exception:
return False
def pause_after_fatal_error(no_pause, lang="en"):
if no_pause or os.name != "nt" or not stdin_is_interactive():
return
write_line(sys.stdout, message(lang, "pause"))
try:
input_function = raw_input
except NameError:
input_function = input
try:
input_function()
except (EOFError, KeyboardInterrupt):
pass
def report_fatal_error(exc, no_pause=False, lang="en"):
rendered = message(lang, "error", exc)
visible = write_line(sys.stderr, rendered)
if not visible and sys.stdout is not sys.stderr:
visible = write_line(sys.stdout, rendered)
if not visible:
show_windows_error(rendered, lang)
pause_after_fatal_error(no_pause, lang)
def main(argv=None):
args = parse_args(argv)
try:
run(args)
return 0
except Exception as exc:
report_fatal_error(exc, args.no_pause, args.lang)
return 1
if __name__ == "__main__":
sys.exit(main())