prompt: You will be provided with a partial code base and an issue statement explaining a problem to resolve.
  <issue>
  Support for SRS
  See https://en.wikipedia.org/wiki/Sender_Rewriting_Scheme and https://github.com/roehling/postsrsd
  
  </issue>
  <code>
  [start of core/admin/mailu/internal/views/postfix.py]
  1 from mailu import models
  2 from mailu.internal import internal
  3 
  4 import flask
  5 import re
  6 
  7 
  8 @internal.route("/postfix/domain/<domain_name>")
  9 def postfix_mailbox_domain(domain_name):
  10     if re.match("^\[.*\]$", domain_name):
  11         return flask.abort(404)
  12     domain = models.Domain.query.get(domain_name) or \
  13              models.Alternative.query.get(domain_name) or \
  14              flask.abort(404)
  15     return flask.jsonify(domain.name)
  16 
  17 
  18 @internal.route("/postfix/mailbox/<path:email>")
  19 def postfix_mailbox_map(email):
  20     user = models.User.query.get(email) or flask.abort(404)
  21     return flask.jsonify(user.email)
  22 
  23 
  24 @internal.route("/postfix/alias/<path:alias>")
  25 def postfix_alias_map(alias):
  26     localpart, domain_name = models.Email.resolve_domain(alias)
  27     if localpart is None:
  28         return flask.jsonify(domain_name)
  29     destination = models.Email.resolve_destination(localpart, domain_name)
  30     return flask.jsonify(",".join(destination)) if destination else flask.abort(404)
  31 
  32 
  33 @internal.route("/postfix/transport/<path:email>")
  34 def postfix_transport(email):
  35     if email == '*' or re.match("(^|.*@)\[.*\]$", email):
  36         return flask.abort(404)
  37     localpart, domain_name = models.Email.resolve_domain(email)
  38     relay = models.Relay.query.get(domain_name) or flask.abort(404)
  39     return flask.jsonify("smtp:[{}]".format(relay.smtp))
  40 
  41 
  42 @internal.route("/postfix/sender/login/<path:sender>")
  43 def postfix_sender_login(sender):
  44     localpart, domain_name = models.Email.resolve_domain(sender)
  45     if localpart is None:
  46         return flask.abort(404)
  47     destination = models.Email.resolve_destination(localpart, domain_name, True)
  48     return flask.jsonify(",".join(destination)) if destination else flask.abort(404)
  49 
  50 
  51 @internal.route("/postfix/sender/access/<path:sender>")
  52 def postfix_sender_access(sender):
  53     """ Simply reject any sender that pretends to be from a local domain
  54     """
  55     if not is_void_address(sender):
  56         localpart, domain_name = models.Email.resolve_domain(sender)
  57         return flask.jsonify("REJECT") if models.Domain.query.get(domain_name) else flask.abort(404)
  58     else:
  59         return flask.abort(404)
  60 
  61 
  62 def is_void_address(email):
  63     '''True if the email is void (null) email address.
  64     '''
  65     if email.startswith('<') and email.endswith('>'):
  66         email = email[1:-1]
  67     # Some MTAs use things like '<MAILER-DAEMON>' instead of '<>'; so let's
  68     # consider void any such thing.
  69     return '@' not in email
  70
  [end of core/admin/mailu/internal/views/postfix.py]
  [start of core/postfix/start.py]
  1 #!/usr/bin/python3
  2 
  3 import os
  4 import glob
  5 import shutil
  6 import multiprocessing
  7 import logging as log
  8 import sys
  9 
  10 from podop   import run_server
  11 from socrate import system, conf
  12 
  13 log.basicConfig(stream=sys.stderr, level=os.environ.get("LOG_LEVEL", "WARNING"))
  14 
  15 def start_podop():
  16     os.setuid(100)
  17     url = "http://" + os.environ["ADMIN_ADDRESS"] + "/internal/postfix/"
  18     # TODO: Remove verbosity setting from Podop?
  19     run_server(0, "postfix", "/tmp/podop.socket", [
  20 		("transport", "url", url + "transport/§"),
  21 		("alias", "url", url + "alias/§"),
  22 		("domain", "url", url + "domain/§"),
  23         ("mailbox", "url", url + "mailbox/§"),
  24         ("senderaccess", "url", url + "sender/access/§"),
  25         ("senderlogin", "url", url + "sender/login/§")
  26     ])
  27 
  28 # Actual startup script
  29 os.environ["FRONT_ADDRESS"] = system.get_host_address_from_environment("FRONT", "front")
  30 os.environ["ADMIN_ADDRESS"] = system.get_host_address_from_environment("ADMIN", "admin")
  31 os.environ["ANTISPAM_MILTER_ADDRESS"] = system.get_host_address_from_environment("ANTISPAM_MILTER", "antispam:11332")
  32 os.environ["LMTP_ADDRESS"] = system.get_host_address_from_environment("LMTP", "imap:2525")
  33 
  34 for postfix_file in glob.glob("/conf/*.cf"):
  35     conf.jinja(postfix_file, os.environ, os.path.join("/etc/postfix", os.path.basename(postfix_file)))
  36 
  37 if os.path.exists("/overrides/postfix.cf"):
  38     for line in open("/overrides/postfix.cf").read().strip().split("\n"):
  39         os.system('postconf -e "{}"'.format(line))
  40 
  41 if os.path.exists("/overrides/postfix.master"):
  42     for line in open("/overrides/postfix.master").read().strip().split("\n"):
  43         os.system('postconf -Me "{}"'.format(line))
  44 
  45 for map_file in glob.glob("/overrides/*.map"):
  46     destination = os.path.join("/etc/postfix", os.path.basename(map_file))
  47     shutil.copyfile(map_file, destination)
  48     os.system("postmap {}".format(destination))
  49     os.remove(destination)
  50 
  51 if "RELAYUSER" in os.environ:
  52     path = "/etc/postfix/sasl_passwd"
  53     conf.jinja("/conf/sasl_passwd", os.environ, path)
  54     os.system("postmap {}".format(path))
  55 
  56 # Run Podop and Postfix
  57 multiprocessing.Process(target=start_podop).start()
  58 os.system("/usr/libexec/postfix/post-install meta_directory=/etc/postfix create-missing")
  59 os.system("postfix start-fg")
  60
  [end of core/postfix/start.py]
  </code>
  
  I need you to solve this issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the following format.
  <patch>
  diff --git a/file.py b/file.py
  --- a/file.py
  +++ b/file.py
  @@ -1,27 +1,35 @@
   def euclidean(a, b):
  -    while b:
  -        a, b = b, a % b
  -    return a
  +    if b == 0:
  +        return a
  +    return euclidean(b, a % b)
   
   
   def bresenham(x0, y0, x1, y1):
       points = []
       dx = abs(x1 - x0)
       dy = abs(y1 - y0)
  -    sx = 1 if x0 < x1 else -1
  -    sy = 1 if y0 < y1 else -1
  -    err = dx - dy
  +    x, y = x0, y0
  +    sx = -1 if x0 > x1 else 1
  +    sy = -1 if y0 > y1 else 1
   
  -    while True:
  -        points.append((x0, y0))
  -        if x0 == x1 and y0 == y1:
  -            break
  -        e2 = 2 * err
  -        if e2 > -dy:
  -            err -= dy
  -            x0 += sx
  -        if e2 < dx:
  -            err += dx
  -            y0 += sy
  +    if dx > dy:
  +        err = dx / 2.0
  +        while x != x1:
  +            points.append((x, y))
  +            err -= dy
  +            if err < 0:
  +                y += sy
  +                err += dx
  +            x += sx
  +    else:
  +        err = dy / 2.0
  +        while y != y1:
  +            points.append((x, y))
  +            err -= dx
  +            if err < 0:
  +                x += sx
  +                err += dy
  +            y += sy
  +
  +    points.append((x, y))
       return points
  
  </patch>
golden_diff: diff --git a/core/admin/mailu/internal/views/postfix.py b/core/admin/mailu/internal/views/postfix.py
  --- a/core/admin/mailu/internal/views/postfix.py
  +++ b/core/admin/mailu/internal/views/postfix.py
  @@ -3,6 +3,7 @@
   
   import flask
   import re
  +import srslib
   
   
   @internal.route("/postfix/domain/<domain_name>")
  @@ -39,6 +40,38 @@
       return flask.jsonify("smtp:[{}]".format(relay.smtp))
   
   
  +@internal.route("/postfix/recipient/map/<path:recipient>")
  +def postfix_recipient_map(recipient):
  +    """ Rewrite the envelope recipient if it is a valid SRS address.
  +
  +    This is meant for bounces to go back to the original sender.
  +    """
  +    srs = srslib.SRS(flask.current_app.config["SECRET_KEY"])
  +    if srslib.SRS.is_srs_address(recipient):
  +        try:
  +            return flask.jsonify(srs.reverse(recipient))
  +        except srslib.Error as error:
  +            return flask.abort(404)
  +    return flask.abort(404)
  +
  +
  +@internal.route("/postfix/sender/map/<path:sender>")
  +def postfix_sender_map(sender):
  +    """ Rewrite the envelope sender in case the mail was not emitted by us.
  +
  +    This is for bounces to come back the reverse path properly.
  +    """
  +    srs = srslib.SRS(flask.current_app.config["SECRET_KEY"])
  +    domain = flask.current_app.config["DOMAIN"]
  +    try:
  +        localpart, domain_name = models.Email.resolve_domain(sender)
  +    except Exception as error:
  +        return flask.abort(404)
  +    if models.Domain.query.get(domain_name):
  +        return flask.abort(404)
  +    return flask.jsonify(srs.forward(sender, domain))
  +
  +
   @internal.route("/postfix/sender/login/<path:sender>")
   def postfix_sender_login(sender):
       localpart, domain_name = models.Email.resolve_domain(sender)
  diff --git a/core/postfix/start.py b/core/postfix/start.py
  --- a/core/postfix/start.py
  +++ b/core/postfix/start.py
  @@ -21,6 +21,8 @@
   		("alias", "url", url + "alias/§"),
   		("domain", "url", url + "domain/§"),
           ("mailbox", "url", url + "mailbox/§"),
  +        ("recipientmap", "url", url + "recipient/map/§"),
  +        ("sendermap", "url", url + "sender/map/§"),
           ("senderaccess", "url", url + "sender/access/§"),
           ("senderlogin", "url", url + "sender/login/§")
       ])
  
verification_info: {"golden_diff": "diff --git a/core/admin/mailu/internal/views/postfix.py b/core/admin/mailu/internal/views/postfix.py\n--- a/core/admin/mailu/internal/views/postfix.py\n+++ b/core/admin/mailu/internal/views/postfix.py\n@@ -3,6 +3,7 @@\n \n import flask\n import re\n+import srslib\n \n \n @internal.route(\"/postfix/domain/<domain_name>\")\n@@ -39,6 +40,38 @@\n     return flask.jsonify(\"smtp:[{}]\".format(relay.smtp))\n \n \n+@internal.route(\"/postfix/recipient/map/<path:recipient>\")\n+def postfix_recipient_map(recipient):\n+    \"\"\" Rewrite the envelope recipient if it is a valid SRS address.\n+\n+    This is meant for bounces to go back to the original sender.\n+    \"\"\"\n+    srs = srslib.SRS(flask.current_app.config[\"SECRET_KEY\"])\n+    if srslib.SRS.is_srs_address(recipient):\n+        try:\n+            return flask.jsonify(srs.reverse(recipient))\n+        except srslib.Error as error:\n+            return flask.abort(404)\n+    return flask.abort(404)\n+\n+\n+@internal.route(\"/postfix/sender/map/<path:sender>\")\n+def postfix_sender_map(sender):\n+    \"\"\" Rewrite the envelope sender in case the mail was not emitted by us.\n+\n+    This is for bounces to come back the reverse path properly.\n+    \"\"\"\n+    srs = srslib.SRS(flask.current_app.config[\"SECRET_KEY\"])\n+    domain = flask.current_app.config[\"DOMAIN\"]\n+    try:\n+        localpart, domain_name = models.Email.resolve_domain(sender)\n+    except Exception as error:\n+        return flask.abort(404)\n+    if models.Domain.query.get(domain_name):\n+        return flask.abort(404)\n+    return flask.jsonify(srs.forward(sender, domain))\n+\n+\n @internal.route(\"/postfix/sender/login/<path:sender>\")\n def postfix_sender_login(sender):\n     localpart, domain_name = models.Email.resolve_domain(sender)\ndiff --git a/core/postfix/start.py b/core/postfix/start.py\n--- a/core/postfix/start.py\n+++ b/core/postfix/start.py\n@@ -21,6 +21,8 @@\n \t\t(\"alias\", \"url\", url + \"alias/\u00a7\"),\n \t\t(\"domain\", \"url\", url + \"domain/\u00a7\"),\n         (\"mailbox\", \"url\", url + \"mailbox/\u00a7\"),\n+        (\"recipientmap\", \"url\", url + \"recipient/map/\u00a7\"),\n+        (\"sendermap\", \"url\", url + \"sender/map/\u00a7\"),\n         (\"senderaccess\", \"url\", url + \"sender/access/\u00a7\"),\n         (\"senderlogin\", \"url\", url + \"sender/login/\u00a7\")\n     ])\n", "issue": "Support for SRS\nSee https://en.wikipedia.org/wiki/Sender_Rewriting_Scheme and https://github.com/roehling/postsrsd\n", "before_files": [{"content": "from mailu import models\nfrom mailu.internal import internal\n\nimport flask\nimport re\n\n\n@internal.route(\"/postfix/domain/<domain_name>\")\ndef postfix_mailbox_domain(domain_name):\n    if re.match(\"^\\[.*\\]$\", domain_name):\n        return flask.abort(404)\n    domain = models.Domain.query.get(domain_name) or \\\n             models.Alternative.query.get(domain_name) or \\\n             flask.abort(404)\n    return flask.jsonify(domain.name)\n\n\n@internal.route(\"/postfix/mailbox/<path:email>\")\ndef postfix_mailbox_map(email):\n    user = models.User.query.get(email) or flask.abort(404)\n    return flask.jsonify(user.email)\n\n\n@internal.route(\"/postfix/alias/<path:alias>\")\ndef postfix_alias_map(alias):\n    localpart, domain_name = models.Email.resolve_domain(alias)\n    if localpart is None:\n        return flask.jsonify(domain_name)\n    destination = models.Email.resolve_destination(localpart, domain_name)\n    return flask.jsonify(\",\".join(destination)) if destination else flask.abort(404)\n\n\n@internal.route(\"/postfix/transport/<path:email>\")\ndef postfix_transport(email):\n    if email == '*' or re.match(\"(^|.*@)\\[.*\\]$\", email):\n        return flask.abort(404)\n    localpart, domain_name = models.Email.resolve_domain(email)\n    relay = models.Relay.query.get(domain_name) or flask.abort(404)\n    return flask.jsonify(\"smtp:[{}]\".format(relay.smtp))\n\n\n@internal.route(\"/postfix/sender/login/<path:sender>\")\ndef postfix_sender_login(sender):\n    localpart, domain_name = models.Email.resolve_domain(sender)\n    if localpart is None:\n        return flask.abort(404)\n    destination = models.Email.resolve_destination(localpart, domain_name, True)\n    return flask.jsonify(\",\".join(destination)) if destination else flask.abort(404)\n\n\n@internal.route(\"/postfix/sender/access/<path:sender>\")\ndef postfix_sender_access(sender):\n    \"\"\" Simply reject any sender that pretends to be from a local domain\n    \"\"\"\n    if not is_void_address(sender):\n        localpart, domain_name = models.Email.resolve_domain(sender)\n        return flask.jsonify(\"REJECT\") if models.Domain.query.get(domain_name) else flask.abort(404)\n    else:\n        return flask.abort(404)\n\n\ndef is_void_address(email):\n    '''True if the email is void (null) email address.\n    '''\n    if email.startswith('<') and email.endswith('>'):\n        email = email[1:-1]\n    # Some MTAs use things like '<MAILER-DAEMON>' instead of '<>'; so let's\n    # consider void any such thing.\n    return '@' not in email\n", "path": "core/admin/mailu/internal/views/postfix.py"}, {"content": "#!/usr/bin/python3\n\nimport os\nimport glob\nimport shutil\nimport multiprocessing\nimport logging as log\nimport sys\n\nfrom podop   import run_server\nfrom socrate import system, conf\n\nlog.basicConfig(stream=sys.stderr, level=os.environ.get(\"LOG_LEVEL\", \"WARNING\"))\n\ndef start_podop():\n    os.setuid(100)\n    url = \"http://\" + os.environ[\"ADMIN_ADDRESS\"] + \"/internal/postfix/\"\n    # TODO: Remove verbosity setting from Podop?\n    run_server(0, \"postfix\", \"/tmp/podop.socket\", [\n\t\t(\"transport\", \"url\", url + \"transport/\u00a7\"),\n\t\t(\"alias\", \"url\", url + \"alias/\u00a7\"),\n\t\t(\"domain\", \"url\", url + \"domain/\u00a7\"),\n        (\"mailbox\", \"url\", url + \"mailbox/\u00a7\"),\n        (\"senderaccess\", \"url\", url + \"sender/access/\u00a7\"),\n        (\"senderlogin\", \"url\", url + \"sender/login/\u00a7\")\n    ])\n\n# Actual startup script\nos.environ[\"FRONT_ADDRESS\"] = system.get_host_address_from_environment(\"FRONT\", \"front\")\nos.environ[\"ADMIN_ADDRESS\"] = system.get_host_address_from_environment(\"ADMIN\", \"admin\")\nos.environ[\"ANTISPAM_MILTER_ADDRESS\"] = system.get_host_address_from_environment(\"ANTISPAM_MILTER\", \"antispam:11332\")\nos.environ[\"LMTP_ADDRESS\"] = system.get_host_address_from_environment(\"LMTP\", \"imap:2525\")\n\nfor postfix_file in glob.glob(\"/conf/*.cf\"):\n    conf.jinja(postfix_file, os.environ, os.path.join(\"/etc/postfix\", os.path.basename(postfix_file)))\n\nif os.path.exists(\"/overrides/postfix.cf\"):\n    for line in open(\"/overrides/postfix.cf\").read().strip().split(\"\\n\"):\n        os.system('postconf -e \"{}\"'.format(line))\n\nif os.path.exists(\"/overrides/postfix.master\"):\n    for line in open(\"/overrides/postfix.master\").read().strip().split(\"\\n\"):\n        os.system('postconf -Me \"{}\"'.format(line))\n\nfor map_file in glob.glob(\"/overrides/*.map\"):\n    destination = os.path.join(\"/etc/postfix\", os.path.basename(map_file))\n    shutil.copyfile(map_file, destination)\n    os.system(\"postmap {}\".format(destination))\n    os.remove(destination)\n\nif \"RELAYUSER\" in os.environ:\n    path = \"/etc/postfix/sasl_passwd\"\n    conf.jinja(\"/conf/sasl_passwd\", os.environ, path)\n    os.system(\"postmap {}\".format(path))\n\n# Run Podop and Postfix\nmultiprocessing.Process(target=start_podop).start()\nos.system(\"/usr/libexec/postfix/post-install meta_directory=/etc/postfix create-missing\")\nos.system(\"postfix start-fg\")\n", "path": "core/postfix/start.py"}]}