forked from andrew/karung-counting-feedmill-semarang
215 lines
8.0 KiB
Python
215 lines
8.0 KiB
Python
#!/usr/bin/env python3
|
|
|
|
"""
|
|
External Service Proxy for Karung Counting Platform
|
|
|
|
This script acts as a reverse proxy to handle external requests for
|
|
https://semarang.fcp.zenai.id and route them to the appropriate internal services
|
|
running on ports 5000 (operator) and 5721 (office).
|
|
|
|
Usage:
|
|
python external_proxy.py
|
|
|
|
The script will:
|
|
1. Listen on port 80 for HTTP requests
|
|
2. Listen on port 443 for HTTPS requests
|
|
3. Route requests based on path and host header
|
|
4. Forward to internal services (192.168.192.96:5000 or 192.168.192.96:5721)
|
|
5. Handle SSL termination
|
|
"""
|
|
|
|
import sys
|
|
import os
|
|
import ssl
|
|
import socket
|
|
from http.server import HTTPServer, BaseHTTPRequestHandler
|
|
from urllib.parse import urlparse
|
|
import threading
|
|
import json
|
|
from datetime
|
|
|
|
# Configuration
|
|
EXTERNAL_DOMAIN = "semarang.fcp.zenai.id"
|
|
JETSEN_IP = "192.168.192.96"
|
|
OPERATOR_PORT = 5000
|
|
OFFICE_PORT = 5721
|
|
|
|
class ExternalServiceProxy:
|
|
def __init__(self):
|
|
self.server = None
|
|
self.https_server = None
|
|
self.running = False
|
|
|
|
def start_http_server(self):
|
|
"""Start HTTP server on port 80 for HTTP traffic"""
|
|
class HTTPHandler(BaseHTTPRequestHandler):
|
|
def do_GET(self):
|
|
self.handle_request(self.server)
|
|
|
|
def do_POST(self):
|
|
self.handle_request(self.server)
|
|
|
|
def handle_request(self, proxy_server):
|
|
# Get the full path including query parameters
|
|
path = self.path
|
|
if len(path) > 1:
|
|
path = path[1:]
|
|
|
|
# Determine target server based on host header or path
|
|
if self.headers.get('Host', '').startswith('api.' + EXTERNAL_DOMAIN):
|
|
target_port = OFFICE_PORT
|
|
elif self.headers.get('Host', '').startswith('operator.' + EXTERNAL_DOMAIN):
|
|
target_port = OPERATOR_PORT
|
|
elif '/api/' in path:
|
|
target_port = OFFICE_PORT
|
|
else:
|
|
target_port = OPERATOR_PORT
|
|
|
|
# Forward request to target server
|
|
try:
|
|
response = proxy_server.make_request('GET', f"http://{JETSEN_IP}:{target_port}/{path}")
|
|
self.send_response(response.status_code)
|
|
for header, value in response.headers.items():
|
|
self.send_header(header, value)
|
|
self.end_headers()
|
|
self.wfile.write(response.data)
|
|
except Exception as e:
|
|
self.send_response(500)
|
|
self.send_header('Content-Type', 'text/plain')
|
|
self.end_headers()
|
|
self.wfile.write(f"Error forwarding request: {str(e)}".encode())
|
|
|
|
http_server = HTTPServer(('0.0.0.0', 80), HTTPHandler)
|
|
http_server.proxy_server = self
|
|
self.server = http_server
|
|
print(f"[INFO] HTTP server started on port 80 for {EXTERNAL_DOMAIN}")
|
|
http_server.serve_forever()
|
|
|
|
def start_https_server(self):
|
|
"""Start HTTPS server on port 443 for HTTPS traffic"""
|
|
try:
|
|
# Try to load SSL certificates
|
|
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
|
|
|
|
# Try to load certificates from various locations
|
|
cert_paths = [
|
|
'/etc/ssl/certs/karung-cert.pem',
|
|
'/home/jetson/karung/ssl/karung-cert.pem',
|
|
'/opt/ssl/certs/karung-cert.pem'
|
|
]
|
|
|
|
key_paths = [
|
|
'/etc/ssl/private/karung-key.pem',
|
|
'/home/jetson/karung/ssl/karung-key.pem',
|
|
'/opt/ssl/private/karung-key.pem'
|
|
]
|
|
|
|
cert_path = None
|
|
key_path = None
|
|
|
|
for cp in cert_paths:
|
|
if os.path.exists(cp):
|
|
cert_path = cp
|
|
break
|
|
|
|
for kp in key_paths:
|
|
if os.path.exists(kp):
|
|
key_path = kp
|
|
break
|
|
|
|
if cert_path and key_path:
|
|
context.load_cert_chain(cert_path, key_path)
|
|
print(f"[INFO] SSL certificates loaded: {cert_path}, {key_path}")
|
|
else:
|
|
print(f"[WARN] SSL certificates not found at standard locations. Self-signed certificates will be used.")
|
|
# Generate self-signed certificate if not exists
|
|
import subprocess
|
|
subprocess.run([
|
|
'openssl', 'req', '-x509', '-newkey', 'rsa:2048',
|
|
'-keyout', '/tmp/karung-key.pem',
|
|
'-out', '/tmp/karung-cert.pem',
|
|
'-days', '365', '-nodes',
|
|
'-subj', '/C=US/ST=State/L=City/O=Organization/OU=Org Unit/CN=semarang.fcp.zenai.id'
|
|
], capture_output=True)
|
|
context.load_cert_chain('/tmp/karung-cert.pem', '/tmp/karung-key.pem')
|
|
print(f"[INFO] Self-signed SSL certificates generated")
|
|
|
|
https_server = HTTPServer(('0.0.0.0', 443), HTTPHandler)
|
|
https_server.proxy_server = self
|
|
self.https_server = https_server
|
|
print(f"[INFO] HTTPS server started on port 443 for {EXTERNAL_DOMAIN}")
|
|
https_server.serve_forever()
|
|
except Exception as e:
|
|
print(f"[ERROR] Failed to start HTTPS server: {e}")
|
|
raise
|
|
|
|
def make_request(self, method, url):
|
|
"""Make request to internal service"""
|
|
import urllib.request
|
|
import urllib.error
|
|
|
|
try:
|
|
req = urllib.request.Request(url)
|
|
req.add_header('User-Agent', 'Karung-External-Service/1.0')
|
|
req.add_header('X-Forwarded-Host', EXTERNAL_DOMAIN)
|
|
req.add_header('X-Forwarded-For', 'external')
|
|
|
|
with urllib.request.urlopen(req, timeout=30) as response:
|
|
return type('Response', (), {
|
|
'status_code': response.getcode(),
|
|
'headers': dict(response.headers),
|
|
'data': response.read()
|
|
})()
|
|
except urllib.error.HTTPError as e:
|
|
return type('Response', (), {
|
|
'status_code': e.code,
|
|
'headers': dict(e.headers) if hasattr(e, 'headers') else {},
|
|
'data': e.read() if hasattr(e, 'read') else b''
|
|
})()
|
|
except Exception as e:
|
|
raise Exception(f"Request failed: {str(e)}")
|
|
|
|
def start(self):
|
|
"""Start both HTTP and HTTPS servers"""
|
|
print(f"[INFO] Starting external service proxy for {EXTERNAL_DOMAIN}")
|
|
print(f"[INFO] Jetton IP: {JETSEN_IP}")
|
|
print(f"[INFO] Operator port: {OPERATOR_PORT}")
|
|
print(f"[INFO] Office port: {OFFICE_PORT}")
|
|
|
|
# Start HTTP server
|
|
http_thread = threading.Thread(target=self.start_http_server, daemon=True)
|
|
http_thread.start()
|
|
|
|
# Start HTTPS server
|
|
https_thread = threading.Thread(target=self.start_https_server, daemon=True)
|
|
https_thread.start()
|
|
|
|
self.running = True
|
|
print(f"[INFO] External service proxy is running on {EXTERNAL_DOMAIN}")
|
|
print(f"[INFO] Access: http://{EXTERNAL_DOMAIN} and https://{EXTERNAL_DOMAIN}")
|
|
|
|
try:
|
|
while self.running:
|
|
import time
|
|
time.sleep(1)
|
|
except KeyboardInterrupt:
|
|
print("\n[INFO] Shutting down external service proxy...")
|
|
self.running = False
|
|
if http_thread:
|
|
http_thread.join(timeout=5)
|
|
if https_thread:
|
|
https_thread.join(timeout=5)
|
|
|
|
def main():
|
|
proxy = ExternalServiceProxy()
|
|
try:
|
|
proxy.start()
|
|
except KeyboardInterrupt:
|
|
print("\n[INFO] External service proxy stopped")
|
|
except Exception as e:
|
|
print(f"[ERROR] External service proxy failed: {e}")
|
|
sys.exit(1)
|
|
|
|
if __name__ == '__main__':
|
|
main()
|