Browse code

Add HTTPS server with self-signed certificate

Robert Cranston authored on 17/07/2025 18:22:31
Showing 5 changed files

1 1
new file mode 100644
... ...
@@ -0,0 +1,2 @@
1
+/cert.pem
2
+/key.pem
0 3
new file mode 100644
... ...
@@ -0,0 +1,9 @@
1
+.PHONY: all
2
+all: cert.pem key.pem
3
+	./serve.py
4
+
5
+cert.pem: key.pem
6
+	openssl req -x509 -subj "/" -key $^ -out $@
7
+
8
+key.pem:
9
+	openssl genrsa -out $@
... ...
@@ -5,6 +5,20 @@ Web server and client code to [POST][] camera frames.
5 5
 [`web-post-camera`]: https://git.rcrnstn.net/rcrnstn/web-post-camera
6 6
 [POST]: https://en.wikipedia.org/wiki/POST_(HTTP)
7 7
 
8
+## Usage
9
+
10
+To generate a self-signed certificate and start the server on the default port
11
+and interface, run `make`.
12
+
13
+To only generate the certificate, run `make cert.pem`.
14
+
15
+To start the server, run `./serve.py [port [host]]`.
16
+
17
+The defaults are:
18
+
19
+-   `port`: `8000`
20
+-   `host`: `""` (bind to all interfaces)
21
+
8 22
 ## License
9 23
 
10 24
 Licensed under the [ISC License][] unless otherwise noted, see the
11 25
new file mode 100644
... ...
@@ -0,0 +1,8 @@
1
+<!DOCTYPE html>
2
+<html>
3
+    <head>
4
+        <meta name="viewport" content="width=device-width, initial-scale=1">
5
+    </head>
6
+    <body>
7
+    </body>
8
+</html>
0 9
new file mode 100755
... ...
@@ -0,0 +1,29 @@
1
+#!/usr/bin/env python3
2
+
3
+import sys
4
+import http.server
5
+import ssl
6
+
7
+
8
+PORT   = 8000
9
+HOST   = ""
10
+PUBLIC = "public"
11
+
12
+
13
+class Handler(http.server.SimpleHTTPRequestHandler):
14
+
15
+    def __init__(self, *args, **kwargs):
16
+        super().__init__(*args, **kwargs, directory=PUBLIC)
17
+
18
+
19
+args = iter(sys.argv[1:])
20
+port = int(next(args, PORT))
21
+host = str(next(args, HOST))
22
+
23
+context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
24
+context.load_cert_chain("cert.pem", "key.pem")
25
+
26
+httpd = http.server.HTTPServer((host, port), Handler)
27
+httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
28
+
29
+httpd.serve_forever()