1
0
mirror of https://github.com/Mailu/Mailu.git synced 2025-04-25 12:15:02 +02:00
Mailu/core/nginx/letsencrypt.py

79 lines
2.4 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
2023-08-09 15:28:07 +02:00
import logging as log
import os
2023-08-09 15:28:07 +02:00
import requests
import sys
import subprocess
2023-08-09 15:28:07 +02:00
import time
from threading import Thread
from http.server import HTTPServer, SimpleHTTPRequestHandler
2023-08-09 15:28:07 +02:00
log.basicConfig(stream=sys.stderr, level="WARNING")
2022-03-17 11:35:31 +01:00
hostnames = ','.join(set(host.strip() for host in os.environ['HOSTNAMES'].split(',')))
2022-03-10 12:31:01 +01:00
command = [
"certbot",
"-n", "--agree-tos", # non-interactive
2022-03-10 12:31:01 +01:00
"-d", hostnames, "--expand", "--allow-subset-of-names",
"-m", "{}@{}".format(os.environ["POSTMASTER"], os.environ["DOMAIN"]),
"certonly", "--standalone",
"--cert-name", "mailu",
"--preferred-challenges", "http", "--http-01-port", "8008",
"--keep-until-expiring",
"--allow-subset-of-names",
2021-08-23 19:41:44 +02:00
"--renew-with-new-domains",
2021-08-09 21:06:15 +02:00
"--config-dir", "/certs/letsencrypt",
"--post-hook", "/config.py"
]
command2 = [
"certbot",
"-n", "--agree-tos", # non-interactive
2022-03-10 12:31:01 +01:00
"-d", hostnames, "--expand", "--allow-subset-of-names",
2021-08-09 21:06:15 +02:00
"-m", "{}@{}".format(os.environ["POSTMASTER"], os.environ["DOMAIN"]),
"certonly", "--standalone",
"--cert-name", "mailu-ecdsa",
"--preferred-challenges", "http", "--http-01-port", "8008",
"--keep-until-expiring",
"--allow-subset-of-names",
2021-08-09 21:06:15 +02:00
"--key-type", "ecdsa",
2021-08-23 19:41:44 +02:00
"--renew-with-new-domains",
"--config-dir", "/certs/letsencrypt",
"--post-hook", "/config.py"
]
# Wait for nginx to start
time.sleep(5)
2023-08-09 19:10:07 +02:00
class MyRequestHandler(SimpleHTTPRequestHandler):
def do_GET(self):
2023-10-06 13:48:09 +02:00
if self.path == '/.well-known/acme-challenge/testing':
self.send_response(204)
else:
self.send_response(404)
self.send_header('Content-Type', 'text/plain')
self.end_headers()
2023-08-09 19:10:07 +02:00
2023-08-09 15:28:07 +02:00
def serve_one_request():
2023-10-06 13:48:09 +02:00
with HTTPServer(("127.0.0.1", 8008), MyRequestHandler) as server:
2023-08-09 15:28:07 +02:00
server.handle_request()
# Run certbot every day
while True:
2023-08-09 15:28:07 +02:00
while True:
2023-10-17 13:58:38 +02:00
hostname = os.environ['HOSTNAMES'].split(',')[0]
2023-08-09 15:28:07 +02:00
target = f'http://{hostname}/.well-known/acme-challenge/testing'
thread = Thread(target=serve_one_request)
thread.start()
r = requests.get(target)
if r.status_code != 204:
2023-10-17 14:05:08 +02:00
log.critical(f"Can't reach {target}!, please ensure it's fixed or change the TLS_FLAVOR.")
2023-08-09 15:28:07 +02:00
time.sleep(5)
else:
break
thread.join()
subprocess.call(command)
2021-08-09 21:06:15 +02:00
subprocess.call(command2)
time.sleep(86400)