#!/usr/bin/env python3
"""Serves nested.dmg as a download on http://127.0.0.1:8080/nested.dmg.

Chrome's download-protection pipeline only runs for HTTP/HTTPS downloads, so
the DMG must be fetched over the network (not opened from disk) for the
SandboxedDMGAnalyzer to run.
"""
import http.server
import os
import socketserver

PORT = 8080
HERE = os.path.dirname(os.path.abspath(__file__))


class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *a, **kw):
        super().__init__(*a, directory=HERE, **kw)

    def end_headers(self):
        if self.path.endswith(".dmg"):
            self.send_header("Content-Disposition",
                             "attachment; filename=nested.dmg")
            self.send_header("Content-Type", "application/x-apple-diskimage")
        super().end_headers()

    def do_GET(self):
        if self.path == "/":
            body = (b"<!doctype html><title>DMG nested-archive scan bypass"
                    b"</title><a id=dl href=/nested.dmg download>download</a>"
                    b"<script>dl.click()</script>")
            self.send_response(200)
            self.send_header("Content-Type", "text/html")
            self.send_header("Content-Length", str(len(body)))
            super().end_headers()
            self.wfile.write(body)
            return
        super().do_GET()


if __name__ == "__main__":
    with socketserver.TCPServer(("127.0.0.1", PORT), Handler) as httpd:
        print(f"Serving on http://127.0.0.1:{PORT}/")
        httpd.serve_forever()
