shell: gnupg: always update conf
[sourcephile-nix.git] / servers / mermet / dovecot.nix
index aa3c32077017ded57dd43ba6db226637c2f7c50c..3cb4ed3f6e3278c3a6d97f1628ace393750e61d7 100644 (file)
 { pkgs, lib, config, system, ... }:
-let inherit (builtins) toString toFile;
-    inherit (builtins.extraBuiltins) pass;
-    inherit (lib) types;
-    inherit (pkgs.lib) loadFile unlines unlinesAttrs unlinesValues unwords;
-    inherit (config) networking;
-    inherit (config.services) dovecot2 postfix openldap;
-    when        = x: y: if x == null then "" else y;
-    extSep      = postfix.recipientDelimiter;
-    dirSep      = extSep;
-    # NOTE: nixpkgs' dovecot2.stateDir is currently not exported
-    stateDir    = "/var/lib/dovecot";
-    mailDir     = "${stateDir}/mail";
-    sieveDir    = "${stateDir}/sieve";
-    authDir     = "${stateDir}/auth";
-    authUser    = dovecot2.mailUser;  # TODO: php_roundcube
-    authGroup   = dovecot2.mailGroup; # TODO: php_roundcube
-    escapeGroup = lib.stringAsChars (c: if "a"<=c && c<="z"
-                                        || "0"<=c && c<="9"
-                                        || c=="-"
-                                        then c else "_");
-    domainGroup = escapeGroup "${networking.domainBase}";
-    etc_dovecot = [
-      { target = "dovecot/${networking.domain}/dovecot-ldap.conf";
-        source = pkgs.writeText "dovecot-ldap.conf" ''
-          debug_level = 0
-
-          # LDAP database
-          uris = ldapi://
-          base = ou=posix,${openldap.domainSuffix}
-          scope = subtree
-          deref = never
-          # NOTE: sufficient for small systems and uses less resources.
-          blocking = no
-
-          # LDAP auth
-          sasl_bind = yes
-          sasl_mech = EXTERNAL
-          #dn = cn=admin,${openldap.domainSuffix}
-          #dnpass = useless with sasl_mech=EXTERNAL
-          auth_bind = no
-          #auth_bind_userdn = cn=%n,ou=accounts,ou=posix,dc=${openldap.domainSuffix}
-
-          # dovecot passdb query
-          # DOC: http://wiki2.dovecot.org/PasswordDatabase/ExtraFields
-          pass_filter = (&(objectClass=posixAccount)(uid=%n)(mailEnabled=TRUE))
-          # TODO: userdb_quota_rule=*:storage=
-          pass_attrs = userPassword=password,\
-                       uidNumber=userdb_uid,\
-                       gidNumber=userdb_gid,\
-                       mailGroupMember=userdb_mail_access_groups=${domainGroup},\
-                       quotaBytes=userdb_quota_rule=*:bytes=%{ldap:quotaBytes},\
-                       =user=%n@%d
-                       #homeDirectory=userdb_home
-          default_pass_scheme = CRYPT
-
-          # dovecot userdb query
-          # DOC: http://wiki2.dovecot.org/UserDatabase/ExtraFields
-          user_filter = (&(objectClass=posixAccount)(uid=%n)(mailEnabled=TRUE))
-          #user_filter = (&(objectClass=inetOrgPerson)(uid=%n))
-          #user_attrs = homeDirectory=home,uidNumber=uid,gidNumber=gid
-          #user_attrs = mailHomeDirectory=home,\
-          #              mailStorageDirectory=mail,\
-          #              mailUidNumber=uid,\
-          #              mailGidNumber=gid,\
-          #              mailQuota=quota_rule=*:bytes=%$
-
-          # doveadm user query
-          iterate_attrs = =user=%{ldap:uid}@${networking.domain}
-          iterate_filter = (&(objectClass=posixAccount)(mailEnabled=TRUE))
-        '';
-      }
+let
+  inherit (builtins) toString toFile readFile;
+  inherit (builtins.extraBuiltins) pass;
+  inherit (lib) types;
+  inherit (pkgs.lib) loadFile unlines unlinesAttrs unlinesValues unwords;
+  inherit (config) networking;
+  inherit (config.services) dovecot2 postfix openldap;
+
+  # NOTE: nixpkgs' dovecot2.stateDir is currently not exported
+  stateDir = "/var/lib/dovecot";
+
+  sieve_pipe_bin_dir = pkgs.buildEnv {
+    name = "sieve_pipe_bin_dir";
+    pathsToLink = [ "/bin" ];
+    paths = [
+      learn-spam
+      learn-ham
     ];
-    dovecot-virtual-pop3 = pkgs.writeTextFile {
-      name = "dovecot-virtual-pop3";
-      destination = "/pop3/INBOX/dovecot-virtual";
-      text = ''
-        All
-        All+*
-          all
-      '';
-    };
-
-    learn-spam = pkgs.writeShellScriptBin "learn-spam.sh" ''
-      exec ${pkgs.rspamd}/bin/rspamc -h /run/rspamd/learner.sock learn_spam
+  };
+  learn-spam = pkgs.writeShellScriptBin "learn-spam.sh" ''
+    exec ${pkgs.rspamd}/bin/rspamc -h /run/rspamd/learner.sock learn_spam
+  '';
+  learn-ham = pkgs.writeShellScriptBin "learn-ham.sh" ''
+    exec ${pkgs.rspamd}/bin/rspamc -h /run/rspamd/learner.sock learn_ham
+  '';
+
+  dovecot-virtual = pkgs.buildEnv {
+    name = "dovecot-virtual";
+    pathsToLink = [ "/" ];
+    paths = [
+      dovecot-virtual-all
+      dovecot-virtual-recents
+    ];
+  };
+  dovecot-virtual-all = pkgs.writeTextFile {
+    name = "dovecot-virtual-all";
+    destination = "/All/dovecot-virtual";
+    text = ''
+      *
+        all
     '';
-    learn-ham = pkgs.writeShellScriptBin "learn-ham.sh" ''
-      exec ${pkgs.rspamd}/bin/rspamc -h /run/rspamd/learner.sock learn_ham
+  };
+  dovecot-virtual-recents = pkgs.writeTextFile {
+    name = "dovecot-virtual-recents";
+    destination = "/Recents/dovecot-virtual";
+    text = ''
+      *
+        all younger 172800
+    '';
+  };
+  dovecot-virtual-pop3 = pkgs.writeTextFile {
+    name = "dovecot-virtual-pop3";
+    destination = "/pop3/INBOX/dovecot-virtual";
+    text = ''
+      All
+      All+*
+        all
     '';
-    sieve_pipe_bin_dir = pkgs.buildEnv {
-      name = "sieve_pipe_bin_dir";
-      pathsToLink = [ "/bin" ];
-      paths = [
-        learn-spam
-        learn-ham
-      ];
-    };
-    dovecot-virtual-all = pkgs.writeTextFile {
-      name = "dovecot-virtual-all";
-      destination = "/All/dovecot-virtual";
-      text = ''
-        *
-          all
-      '';
-    };
-    dovecot-virtual-recents = pkgs.writeTextFile {
-      name = "dovecot-virtual-recents";
-      destination = "/Recents/dovecot-virtual";
-      text = ''
-        *
-          all younger 172800
-      '';
-    };
-    dovecot-virtual = pkgs.buildEnv {
-      name = "dovecot-virtual";
-      pathsToLink = [ "/" ];
-      paths = [
-        dovecot-virtual-all
-        dovecot-virtual-recents
-      ];
-    };
+  };
 in
 {
-  imports = [
-    dovecot/autoconfig.nix
+imports = [
+  dovecot/sourcephile.fr.nix
+  dovecot/autogeree.net.nix
+];
+systemd.services.dovecot2 = {
+  after = [
+    "postfix.service"
+    "openldap.service"
+    "${networking.domain}.key.pem-key.service"
   ];
-  #services.postfix.mapFiles."transport-dovecot" =
-  #  toFile "transport-dovecot"
-  #   (unlines
-  #     (lib.mapAttrsToList
-  #       (dom: {...}: "${transportSubDomain}.${dom} lmtp:unix:private/dovecot-lmtp")
-  #       dovecot2.domains));
-  systemd.services.dovecot2 = {
-    after = [
-      "postfix.service"
-      "openldap.service"
-      "dovecot.${networking.domainBase}.key.pem-key.service"
-    ];
-    restartTriggers = map (f: f.source) etc_dovecot;
-  };
-  deployment.keys = {
-    "dovecot.${networking.domainBase}.key.pem" = {
-      text        = pass "x509/${networking.domainBase}/key.pem";
-      user        = dovecot2.user;
-      group       = "root";
-      destDir     = "/run/keys/";
-      permissions = "0400"; # WARNING: not enforced when deployment.storeKeysOnMachine = true
-    };
+  /*
+  preStart = ''
+    # SEE: http://wiki2.dovecot.org/SharedMailboxes/Permissions
+    install -D -d -m 0771 \
+     -o "${dovecot2.user}" \
+     -g "${dovecot2.group}" \
+     ${stateDir}/mail
+  '';
+  */
+};
+#users.users."${dovecot2.mailUser}".isSystemUser = true; # Fix nixpkgs
+services.dovecot2 = {
+  enable = true;
+  modules = [
+    pkgs.dovecot_pigeonhole
+    pkgs.dovecot_fts_xapian
+  ];
+  enablePAM = false;
+  enableImap = true;
+  enableLmtp = true;
+  enablePop3 = true;
+  protocols = [ "sieve" ];
+  # If needed, may be overrided by userdb_mail= in passdb, or mail= in userdb
+  # Here INDEX and CONTROL are separated,
+  # it's not useful since there is not quota at the filesystem level
+  # it's just to let this possibility later on.
+  mailLocation = "sdbox:${stateDir}/home/%d/%n/mail:UTF-8:CONTROL=${stateDir}/control/%d/%n:INDEX=${stateDir}/index/%d/%n";
+  createMailUser = false;
+  mailUser = "";
+  mailGroup = "";
+  sslServerCert = null;
+  sieveScripts = {
+    global = dovecot/sieve/global;
   };
-  environment.etc = etc_dovecot;
-  users.users."${dovecot2.mailUser}".isSystemUser = true; # Fix nixpkgs
-  services.dovecot2 = {
-    enable    = true;
-    mailUser  = "dovemail";
-    mailGroup = "dovemail";
-    modules   = [
-      pkgs.dovecot_pigeonhole
-      pkgs.dovecot_fts_xapian
-    ];
-    sieves = {
-      global = {
-        list = ''
-          require [ "date", "fileinto", "mailbox", "variables" ];
-
-          if currentdate :matches "year"  "*" { set "year"  "''${1}"; }
-          if currentdate :matches "month" "*" { set "month" "''${1}"; }
-
-          if exists "List-ID" {
-            if header :matches "List-ID" "*<*.*.*.*>*" {
-              set "list"   "''${2}";
-              set "domain" "''${4}";
-            }
-            elsif header :matches "List-ID" "*<*.*.*>*" {
-              set "list"   "''${2}";
-              set "domain" "''${3}";
-            }
-            fileinto :create "Listes+''${domain}+''${list}+''${year}+''${month}";
-            stop;
-           }
-        '';
-        spam = ''
-          require [ "imap4flags" ];
-
-          if header :contains "X-Spam-Level" "***" {
-            addflag "Junk";
-          }
-        '';
-        extension = ''
-          require
-           [ "envelope"
-           , "fileinto"
-           , "mailbox"
-           , "subaddress"
-           , "variables"
-           ];
-          if envelope :matches :detail "TO" "*" {
-            set "extension" "''${1}";
-          }
-          if not string :is "''${extension}" "" {
-            fileinto :create "INBOX+''${extension}";
-            stop;
-          }
-        '';
-        spam-or-ham = ''
-          require ["vnd.dovecot.pipe", "copy", "imapsieve", "variables", "imap4flags", "environment"];
-
-          if environment :is "imap.changedflags" "Junk" {
-            if hasflag :is "Junk" {
-              pipe :copy :try "learn-spam.sh";
-            } elsif not hasflag :is "Junk" {
-              pipe :copy :try "learn-ham.sh";
-            }
-          }
-        '';
-        report-spam = ''
-          require ["vnd.dovecot.pipe", "copy", "imapsieve", "environment", "variables"];
-
-          if environment :matches "imap.user" "*" {
-            set "username" "''${1}";
-          }
-
-          pipe :copy :try "learn-spam.sh" [ "''${username}" ];
-        '';
-        report-ham = ''
-          require ["vnd.dovecot.pipe", "copy", "imapsieve", "environment", "variables"];
-
-          if environment :matches "imap.mailbox" "*" {
-            set "mailbox" "''${1}";
-          }
-
-          if string "''${mailbox}" "Trash" {
-            stop;
-          }
-
-          if environment :matches "imap.user" "*" {
-            set "username" "''${1}";
-          }
-
-          pipe :copy :try "learn-ham.sh" [ "''${username}" ];
-        '';
-      };
-    };
-    configFile = toString ( pkgs.writeText "dovecot.conf" ''
-      auth_debug  = yes
-      mail_debug  = yes
-      verbose_ssl = yes
-
-      passdb {
-        driver = ldap
-        args = /etc/dovecot/${networking.domain}/dovecot-ldap.conf
-        default_fields = userdb_mail_access_groups=${domainGroup}
-        override_fields =
+  extraConfig = ''
+    auth_verbose = no
+    auth_debug = no
+    mail_debug = no
+    verbose_ssl = no
+    log_timestamp = "%Y-%m-%d %H:%M:%S "
+
+    ssl = required
+    ssl_dh = <${../../../sec/openssl/dh.pem}
+    ssl_cipher_list = HIGH:!LOW:!SSLv2:!EXP:!aNULL
+    ssl_prefer_server_ciphers = yes
+    ssl_cert = <${loadFile (../../../sec + "/openssl/${networking.domain}/cert.self-signed.pem")}
+    ssl_key = </run/keys/${networking.domain}.key.pem
+    #ssl_ca = <''${caPath}
+    #ssl_verify_client_cert = yes
+
+    listen = *
+    # If needed, may be overrided by userdb_mail
+    mail_home = ${stateDir}/home/%d/%n
+    # Read multiple mails in parallel, improves performance
+    mail_prefetch_count = 20
+    # Default VSZ (virtual memory size) limit for service processes. This is mainly
+    # intended to catch and kill processes that leak memory before they eat up everything.
+    # Increased for fts_xapian.
+    default_vsz_limit = 1G
+
+    # DOC: https://doc.dovecot.org/configuration_manual/authentication/authentication_mechanisms/
+    # DOC: https://ldapwiki.com/wiki/DIGEST-MD5
+    # The misunderstanding is the notion "password sent over the network in plain-text" is not secure,
+    # when in fact, storing the password in the directory server using a Salted SHA-2 hash
+    # and transmitting the clear text password over a secure connection
+    # is more secure than having the directory server store the password in clear text
+    # or in a reversible encryption scheme.
+    # Therefore, SASL with DIGEST-MD5 (or CRAM-MD5) should be avoided.
+    # Use doveadm pw -s SSHA
+    # or doveadm pw -s PBKDF2 -r 10000
+    # or slappasswd -o module-load=pw-pbkdf2 -h "{PBKDF2-SHA256}"
+    auth_mechanisms = plain login
+    auth_username_format = %Ln
+    service auth {
+      user = ${dovecot2.user}
+      # auth_socket_path points to this userdb socket by default. It's typically
+      # used by dovecot-lda, doveadm, possibly imap process, etc.
+      # Users that have access to this socket are able to get a list
+      # of all usernames and get results of everyone's userdb lookups.
+      unix_listener auth-userdb {
+        user  = ${dovecot2.user}
+        group = ${dovecot2.group}
+        mode  = 0660
       }
-      userdb {
-        driver = prefetch
+      unix_listener /var/lib/postfix/queue/private/auth {
+        user  = ${postfix.user}
+        group = ${postfix.group}
+        mode  = 0660
       }
-      userdb {
-        # NOTE: this userdb is only used by lda.
-        driver = ldap
-        args = /etc/dovecot/${networking.domain}/dovecot-ldap.conf
-        default_fields = mail_access_groups=${domainGroup}
-        override_fields =
-        skip = found
+    }
+    service auth-worker {
+      user = ${dovecot2.user}
+    }
+    auth_cache_verify_password_with_worker = yes
+    # SEE: http://wiki2.dovecot.org/Quota/FS
+    # NOTE: postfix does not supply a client cert.
+    auth_ssl_require_client_cert = no
+    #auth_ssl_username_from_cert = yes
+    # NOTE: lowercase the username, help with LDAP?
+    auth_username_format = %Lu
+    # NOTE: sync with LDAP's data.
+    first_valid_uid = 1000
+    disable_plaintext_auth = yes
+
+    userdb {
+      driver = ldap
+      # A different path than passdb's args enables non-blocking LDAP requests
+      args = ${dovecot/ldap.conf}
+      default_fields =
+      override_fields =
+    }
+
+    # No dirty syncs for maildir: locations which may be used directly by neomutt
+    maildir_very_dirty_syncs = no
+    namespace Inbox {
+      type      = private
+      inbox     = yes
+      hidden    = no
+      list      = yes
+      prefix    =
+      separator = +
+    }
+    namespace Shared {
+      type = shared
+      #list = children
+      # NOTE: always listed in the LIST command.
+      list = yes
+      # NOTE: how to access the other users' mailboxes.
+      # NOTE: %var expands to the logged in user's variable, while
+      #       %%var expands to the other users' variables.
+      # NOTE: INDEX and CONTROL are shared, INDEXPVT is not.
+      location = sdbox:${stateDir}/home/%%d/%%n/${stateDir}/mail:UTF-8:CONTROL=${stateDir}/control/%%d/%%n/shared:INDEX=${stateDir}/index/%%d/%%n/shared:INDEXPVT=${stateDir}/index/%d/%n/shared/%%n
+      prefix = Partages+%%n+
+      separator = +
+      subscriptions = yes
+    }
+    mail_plugins = $mail_plugins virtual
+    namespace Virtual {
+      prefix = Virtual+
+      separator = +
+      hidden = no
+      list = yes
+      subscriptions = no
+      location = virtual:${dovecot-virtual}:UTF-8:INDEX=${stateDir}/index/%d/%n/virtual
+    }
+
+    mail_plugins = $mail_plugins acl
+    plugin {
+      acl = vfile:/etc/dovecot/acl/global
+      acl_anyone = allow
+      # NOTE: to let users LIST mailboxes shared by other users,
+      #       Dovecot needs a shared mailbox dictionary.
+      # FIXME: %d not working with userdb ldap
+      acl_shared_dict = file:${stateDir}/acl/%d/acl.db
+    }
+
+    mail_plugins = $mail_plugins fts fts_xapian
+    plugin {
+      plugin = fts fts_xapian
+      fts = xapian
+      fts_autoindex = yes
+      fts_autoindex_exclude = \Junk
+      fts_autoindex_exclude2 = \Trash
+      fts_enforced = yes
+      # 2 and 20 are the NGram values for header fields, which means the
+      # keywords created for fields (To, Cc, ...) are between is 2 and 20 chars long.
+      # Full words are also added by default.
+      fts_xapian = partial=2 full=20 verbose=0
+    }
+
+    mail_plugins = $mail_plugins quota
+    plugin {
+      quota = maildir:User quota
+      quota_rule = *:storage=256M
+      quota_rule2 = Trash:storage=+64M
+      quota_max_mail_size = 20M
+      #quota_exceeded_message = </path/to/quota_exceeded_message.txt
+      quota_warning  = storage=95%% quota-warning 95 %u
+      quota_warning2 = storage=80%% quota-warning 80 %u
+      quota_warning3 = -storage=100%% quota-warning below %u
+    }
+
+    protocol lda {
+      hostname = ${networking.domain}
+      mail_plugins = $mail_plugins sieve
+      postmaster_address = postmaster+dovecot+lda@${networking.domain}
+      syslog_facility = mail
+    }
+    lda_mailbox_autocreate = yes
+    lda_mailbox_autosubscribe = yes
+
+    protocol lmtp {
+      mail_plugins = $mail_plugins sieve
+      postmaster_address = postmaster+dovecot+lmtp@${networking.domain}
+    }
+    service lmtp {
+      process_min_avail = ${toString config.nix.maxJobs}
+      unix_listener /var/lib/postfix/queue/private/dovecot-lmtp {
+        user  = ${postfix.user}
+        group = ${postfix.group}
+        mode  = 0600
       }
-      auth_cache_verify_password_with_worker = yes
-      #passdb {
-      #  driver = passwd-file
-      #  args   = scheme=crypt username_format=%n ${authDir}/%d/passwd
-      #}
-      #userdb {
-      #  # NOTE: this userdb is only used by lda.
-      #  driver = passwd-file
-      #  args = username_format=%n ${authDir}/%d/passwd
-      #  #default_fields = home=${mailDir}/%d/%n
-      #  skip = found
+    }
+    plugin {
+      # Let extension.sieve do the handling of the detail
+      #lmtp_save_to_detail_mailbox = yes
+      recipient_delimiter = ${postfix.recipientDelimiter}
+    }
+
+    service imap {
+      # Most of the memory goes to mmap()ing files.
+      # You may need to increase this limit if you have huge mailboxes.
+      #vsz_limit =
+      process_limit = 1024
+    }
+    service imap-login {
+      #inet_listener imap {
+      #  address = 127.0.0.1
+      #  port    = 143
+      #  ssl     = no
       #}
-      # If needed, may be overrided by userdb_mail
-      mail_home = ${mailDir}/%d/%n
-      # NOTE: if needed, may be overrided by userdb_mail
-      # NOTE: INDEX and CONTROL are on a partition without quota, as explain in the doc.
-      # SEE: http://wiki2.dovecot.org/Quota/FS
-      auth_mechanisms = plain login
-      # NOTE: postfix does not supply a client cert.
-      auth_ssl_require_client_cert = no
-      #auth_ssl_username_from_cert = yes
-      auth_verbose = yes
-      # NOTE: lowercase the username, help with LDAP?
-      auth_username_format = %Lu
-      default_internal_user = ${dovecot2.user}
-      default_internal_group = ${dovecot2.group}
-      disable_plaintext_auth = yes
-      # NOTE: sync with LDAP's data.
-      first_valid_uid = 1000
-      lda_mailbox_autocreate = yes
-      lda_mailbox_autosubscribe = yes
-      listen = *
-      log_timestamp = "%Y-%m-%d %H:%M:%S "
-      mail_location = sdbox:/var/lib/dovecot/mail/%d/%n/mail.d:UTF-8:CONTROL=/var/lib/dovecot/control/%d/%n:INDEX=/var/lib/dovecot/index/%d/%n
-      # No dirty syncs while I'm using neomutt directly on the Maildirs
-      #maildir_very_dirty_syncs = yes
-      #maildir_copy_with_hardlinks = yes
-      namespace Inbox {
-        type      = private
-        inbox     = yes
-        hidden    = no
-        list      = yes
-        prefix    =
-        separator = ${dirSep}
-      }
-      namespace Shared {
-        type = shared
-        #list = children
-        # NOTE: always listed in the LIST command.
-        list = yes
-        # NOTE: how to access the other users' mailboxes.
-        # NOTE: %var expands to the logged in user's variable, while
-        #       %%var expands to the other users' variables.
-        # NOTE: INDEX and CONTROL are shared, INDEXPVT is not.
-        location = sdbox:${mailDir}/%%d/%%n/mail.d:UTF-8:CONTROL=${stateDir}/control/%%d/%%n/Shared:INDEX=${stateDir}/index/%%d/%%n/Shared:INDEXPVT=${stateDir}/index/%d/%n/Shared/%%n
-        prefix = Partages+%%n+
-        separator = ${dirSep}
-        subscriptions = yes
-      }
-      namespace Virtual {
-        prefix = Virtual+
-        separator = ${dirSep}
-        hidden = no
-        list = yes
-        subscriptions = no
-        location = virtual:${dovecot-virtual}:UTF-8:INDEX=${stateDir}/index/%d/%n/virtual
-      }
-      # Default VSZ (virtual memory size) limit for service processes. This is mainly
-      # intended to catch and kill processes that leak memory before they eat up everything.
-      # Increased for fts_xapian.
-      default_vsz_limit = 1G
-      mail_plugins = $mail_plugins acl quota virtual fts fts_xapian
-      #mail_uid = ${dovecot2.mailUser}
-      #mail_gid = ${dovecot2.mailGroup}
-        # NOTE: each user has a dedicated (uid,gid) pair
-      #mail_privileged_group = mail
-      #mail_access_groups =
-      plugin {
-        plugin = fts fts_xapian
-
-        acl = vfile:/etc/dovecot/acl/global.d
-        acl_anyone = allow
-        # NOTE: to let users LIST mailboxes shared by other users,
-        #       Dovecot needs a shared mailbox dictionary.
-        # FIXME: %d not working with userdb ldap
-        acl_shared_dict = file:${stateDir}/acl/%d/acl.db
-
-        fts = xapian
-        fts_autoindex = yes
-        fts_autoindex_exclude = \Junk
-        fts_autoindex_exclude2 = \Trash
-        fts_enforced = yes
-        # 2 and 20 are the NGram values for header fields, which means the
-        # keywords created for fields (To, Cc, ...) are between is 2 and 20 chars long.
-        # Full words are also added by default.
-        fts_xapian = partial=2 full=20 verbose=0
-
-        quota = maildir:User quota
-        quota_rule = *:storage=256M
-        quota_rule2 = Trash:storage=+64M
-        quota_max_mail_size = 20M
-        #quota_exceeded_message = </path/to/quota_exceeded_message.txt
-        quota_warning  = storage=95%% quota-warning 95 %u
-        quota_warning2 = storage=80%% quota-warning 80 %u
-        quota_warning3 = -storage=100%% quota-warning below %u
-
-        # Let extension.sieve do the handling of the detail
-        #lmtp_save_to_detail_mailbox = yes
-        recipient_delimiter = ${extSep}
-
-        #sieve_default = file:${mailDir}/%u/default.sieve
-        #sieve_default_name = default
-        sieve_plugins = sieve_imapsieve sieve_extprograms
-        sieve_global_extensions = +vnd.dovecot.pipe +vnd.dovecot.environment
-        #sieve_extensions = +editheader
-        sieve = file:~/sieve.d;active=~/sieve
-        sieve_after = ${sieveDir}/after.d/
-        sieve_before = ${sieveDir}/before.d/
-        sieve_pipe_bin_dir = ${sieve_pipe_bin_dir}/bin
-        sieve_global = ${sieveDir}/global.d/
-        sieve_max_script_size = 1M
-        sieve_quota_max_scripts = 0
-        sieve_quota_max_storage = 10M
-        #sieve_spamtest_max_value = 10
-        #sieve_spamtest_status_header = X-Spam-Score
-        #sieve_spamtest_status_type = strlen
-        sieve_user_log = /var/log/dovecot/%d/sieve.%n.log
-        # Enables support for user Sieve scripts in IMAP
-        #imapsieve_url = sieve://mail.${networking.domain}:4190
-
-        # When a flag changes, spam or ham according to the \Junk or \NonJunk flags
-        imapsieve_mailbox1_name = *
-        imapsieve_mailbox1_causes = FLAG
-        imapsieve_mailbox1_before = file:${sieveDir}/global.d/spam-or-ham.sieve
-
-        # From elsewhere to Junk folder
-        imapsieve_mailbox2_name = Pourriel
-        imapsieve_mailbox2_causes = COPY APPEND
-        imapsieve_mailbox2_before = file:${sieveDir}/global.d/report-spam.sieve
-
-        # From Junk folder to elsewhere
-        imapsieve_mailbox3_name = *
-        imapsieve_mailbox3_from = Pourriel
-        imapsieve_mailbox3_causes = COPY
-        imapsieve_mailbox3_before = file:${sieveDir}/global.d/report-ham.sieve
+      inet_listener imaps {
+        port = 993
+        ssl  = yes
       }
-      # If you have Dovecot v2.2.8+ you may get a significant performance improvement with fetch-headers:
-      imapc_features = $imapc_features fetch-headers
-      # Read multiple mails in parallel, improves performance
-      mail_prefetch_count = 20
-      service quota-warning {
-        executable = script ${
-          pkgs.writeScript "quota-warning" ''
-            #!/bin/sh -eu
-            PERCENT=$1
-            USER=$2
-            cat << EOF | ${pkgs.dovecot}/libexec/dovecot/dovecot-lda -d $USER -o
-            "plugin/quota=maildir:User quota:noenforcing"
-            From: postmaster@${networking.domain}
-            Subject: [WARNING] your mailbox is now $PERCENT% full.
+    }
+    # Store METADATA information within user's HOME directory
+    mail_attribute_dict = file:%h/dovecot-attributes
+    # If you have Dovecot v2.2.8+ you may get a significant performance improvement with fetch-headers:
+    imapc_features = $imapc_features fetch-headers
+    protocol imap {
+      #mail_max_userip_connections = 10
+      mail_plugins = $mail_plugins imap_acl imap_quota imap_sieve virtual
+      imap_metadata = yes
+
+      # DOC: https://wiki.dovecot.org/MailboxSettings
+      # Due to a bug in Dovecot v2.2.30+ if special-use flags are used,
+      # SPECIAL-USE needs to be added to post-login CAPABILITY response as RFC 6154 mandates.
+      imap_capability = +SPECIAL-USE
 
-            Please remove some mails to make room for new ones.
-            EOF
-          ''
+      namespace Inbox {
+        mailbox "Archives" {
+          auto = subscribe
+          special_use = \Archive
         }
-        # use some unprivileged user for executing the quota warnings
-        user = ${dovecot2.user}
-        unix_listener quota-warning {
+        mailbox "Drafts" {
+          auto = no
+          special_use = \Drafts
         }
-      }
-      # Store METADATA information within user's HOME directory
-      mail_attribute_dict = file:%h/dovecot-attributes
-      protocol imap {
-        #mail_max_userip_connections = 10
-        mail_plugins = $mail_plugins imap_acl imap_quota imap_sieve virtual
-        imap_metadata = yes
-
-        # DOC: https://wiki.dovecot.org/MailboxSettings
-        # Due to a bug in Dovecot v2.2.30+ if special-use flags are used,
-        # SPECIAL-USE needs to be added to post-login CAPABILITY response as RFC 6154 mandates.
-        imap_capability = +SPECIAL-USE
-
-        namespace Inbox {
-          mailbox "Archives" {
-            auto = subscribe
-            special_use = \Archive
-          }
-          mailbox "Drafts" {
-            auto = no
-            special_use = \Drafts
-          }
-          mailbox "Brouillons" {
-            auto = subscribe
-            special_use = \Drafts
-          }
-          mailbox "Junk" {
-            auto = no
-            #autoexpunge = 30d
-            special_use = \Junk
-          }
-          mailbox "Spams" {
-            auto = no
-            special_use = \Junk
-          }
-          mailbox "Spam" {
-            auto = no
-            special_use = \Junk
-          }
-          mailbox "Pourriels" {
-            auto = no
-            special_use = \Junk
-          }
-          mailbox "Pourriel" {
-            auto = no
-            special_use = \Junk
-          }
-          mailbox "Sent" {
-            auto = no
-            special_use = \Sent
-          }
-          mailbox "Sent Items" {
-            auto = no
-            special_use = \Sent
-          }
-          mailbox "Sent Messages" {
-            auto = no
-            special_use = \Sent
-          }
-          mailbox "Envoyés" {
-            auto = no
-            special_use = \Sent
-          }
-          mailbox "Trash" {
-            auto = no
-            special_use = \Trash
-            #autoexpunge = 30d
-          }
-          mailbox "Corbeille" {
-            auto = no
-            special_use = \Trash
-          }
+        mailbox "Brouillons" {
+          auto = subscribe
+          special_use = \Drafts
         }
-        namespace Virtual {
-          mailbox All {
-            auto = no
-            comment = All messages from all mailboxes
-            special_use = \All
-          }
-          mailbox Recents {
-            auto = no
-            comment = All messages from all mailboxes arrived in the past 48h
-          }
+        mailbox "Junk" {
+          auto = no
+          #autoexpunge = 30d
+          special_use = \Junk
         }
-      }
-      protocol lda {
-        auth_socket_path = /var/run/dovecot/auth-userdb
-        hostname         = ${networking.domain}
-        info_log_path    =
-        log_path         =
-        mail_plugins     = $mail_plugins sieve
-        postmaster_address = postmaster${extSep}dovecot${extSep}lda@${networking.domain}
-        syslog_facility = mail
-      }
-      protocol lmtp {
-        #info_log_path = /tmp/dovecot-lmtp.log
-        mail_plugins = $mail_plugins sieve
-        postmaster_address = postmaster${extSep}dovecot${extSep}lmtp@${networking.domain}
-      }
-      protocol pop3 {
-        mail_plugins = $mail_plugins virtual
-        #mail_max_userip_connections = 10
-        # Virtual namespace for the virtual INBOX.
-        # Use a global directory for dovecot-virtual files.
-        #namespace Inbox {
-        #  hidden    = yes
-        #  list      = no
-        #  location  = virtual:''${dovecot-virtual-pop3}/pop3:INDEX=${stateDir}/index/%d/%n/virtual/pop3:LAYOUT=fs
-        #  prefix    = pop3+
-        #}
-        pop3_client_workarounds =
-        pop3_fast_size_lookups = yes
-        pop3_lock_session = yes
-        pop3_no_flag_updates = yes
-        # Use GUIDs to avoid accidental POP3 UIDL changes instead of IMAP UIDs.
-        pop3_uidl_format = %g
-      }
-      # DOC: https://wiki2.dovecot.org/Pigeonhole/ManageSieve/Configuration
-      protocol sieve {
-        # Maximum number of ManageSieve connections allowed for a user from each IP address.
-        # NOTE: The username is compared case-sensitively.
-        mail_max_userip_connections = 10
-
-        # To fool ManageSieve clients that are focused on CMU's timesieved you can specify
-        # the IMPLEMENTATION capability that the dovecot reports to clients.
-        # For example: 'Cyrus timsieved v2.2.13'
-        managesieve_implementation_string = Dovecot Pigeonhole
-
-        # The maximum number of compile errors that are returned to the client upon script
-        # upload or script verification.
-        managesieve_max_compile_errors = 5
-
-        #mail_max_userip_connections = 10
-        #managesieve_implementation_string = Dovecot Pigeonhole
-        managesieve_max_compile_errors = 5
-        #managesieve_max_line_length = 65536
-        #managesieve_notify_capability = mailto
-        #managesieve_sieve_capability = fileinto reject envelope encoded-character vacation subaddress comparator-i;ascii-numeric relational regex imap4flags copy include variables body enotify environment mailbox date ihave
-      }
-      protocols = imap lmtp pop3 sieve
-      service lmtp {
-        #executable = lmtp -L
-        process_min_avail = ${toString config.nix.maxJobs}
-        unix_listener /var/lib/postfix/queue/private/dovecot-lmtp {
-          user  = ${postfix.user}
-          group = ${postfix.group}
-          mode  = 0600
+        mailbox "Spams" {
+          auto = no
+          special_use = \Junk
         }
-        #user = mail
-      }
-      service auth {
-        # FIXME: may be user=dovecot-auth with LDAP?
-        user = root
-        unix_listener auth-userdb {
-          user  = ${dovecot2.user}
-          group = ${dovecot2.group}
-          mode  = 0660
+        mailbox "Spam" {
+          auto = no
+          special_use = \Junk
         }
-        unix_listener /var/lib/postfix/queue/private/auth {
-          user  = ${postfix.user}
-          group = ${postfix.group}
-          mode  = 0660
+        mailbox "Pourriels" {
+          auto = no
+          special_use = \Junk
         }
-      }
-      service imap {
-        # Most of the memory goes to mmap()ing files.
-        # You may need to increase this limit if you have huge mailboxes.
-        #vsz_limit =
-        process_limit = 1024
-      }
-      service imap-login {
-        #inet_listener imap {
-        #  address = 127.0.0.1
-        #  port    = 143
-        #  ssl     = no
-        #}
-        inet_listener imaps {
-          port = 993
-          ssl  = yes
+        mailbox "Pourriel" {
+          auto = no
+          special_use = \Junk
         }
-      }
-      service pop3 {
-        process_limit = 1024
-      }
-      service pop3-login {
-        inet_listener pop3s {
-          port = 995
-          ssl  = yes
+        mailbox "Sent" {
+          auto = no
+          special_use = \Sent
+        }
+        mailbox "Sent Items" {
+          auto = no
+          special_use = \Sent
+        }
+        mailbox "Sent Messages" {
+          auto = no
+          special_use = \Sent
+        }
+        mailbox "Envoyés" {
+          auto = no
+          special_use = \Sent
+        }
+        mailbox "Trash" {
+          auto = no
+          special_use = \Trash
+          #autoexpunge = 30d
+        }
+        mailbox "Corbeille" {
+          auto = no
+          special_use = \Trash
         }
       }
-      service managesieve-login {
-        inet_listener sieve {
-          port = 4190
-          #ssl  = yes
+      namespace Virtual {
+        mailbox All {
+          auto = no
+          comment = All messages from all mailboxes
+          special_use = \All
         }
+        mailbox Recents {
+          auto = no
+          comment = All messages from all mailboxes arrived in the past 48h
+        }
+      }
+    }
+    plugin {
+      sieve_plugins = sieve_imapsieve sieve_extprograms
+      sieve_global_extensions = +vnd.dovecot.environment +vnd.dovecot.pipe
+      #sieve_extensions = +editheader
+      sieve = file:~/sieve;active=~/active.sieve
+      sieve_default = file:${stateDir}/sieve/global/default.sieve
+      sieve_default_name = main
+      sieve_pipe_bin_dir = ${sieve_pipe_bin_dir}/bin
+      sieve_max_script_size = 1M
+      sieve_quota_max_scripts = 0
+      sieve_quota_max_storage = 10M
+      #sieve_spamtest_max_value = 10
+      #sieve_spamtest_status_header = X-Spam-Score
+      #sieve_spamtest_status_type = strlen
+      #sieve_user_log = /var/log/dovecot/%d/sieve.%n.log
+      # Enables support for user Sieve scripts in IMAP
+      #imapsieve_url = sieve://mail.${networking.domain}:4190
+
+      # When a flag changes, spam or ham according to the \Junk or \NonJunk flags
+      imapsieve_mailbox1_name = *
+      imapsieve_mailbox1_causes = FLAG
+      imapsieve_mailbox1_before = file:${stateDir}/sieve/global/spam-or-ham.sieve
+
+      # From elsewhere to Junk folder
+      imapsieve_mailbox2_name = Pourriel
+      imapsieve_mailbox2_causes = COPY APPEND
+      imapsieve_mailbox2_before = file:${stateDir}/sieve/global/report-spam.sieve
+
+      # From Junk folder to elsewhere
+      imapsieve_mailbox3_name = *
+      imapsieve_mailbox3_from = Pourriel
+      imapsieve_mailbox3_causes = COPY
+      imapsieve_mailbox3_before = file:${stateDir}/sieve/global/report-ham.sieve
+    }
+    protocol sieve {
+      # Maximum number of ManageSieve connections allowed for a user from each IP address.
+      # NOTE: The username is compared case-sensitively.
+      mail_max_userip_connections = 10
+
+      # To fool ManageSieve clients that are focused on CMU's timesieved you can specify
+      # the IMPLEMENTATION capability that the dovecot reports to clients.
+      # For example: 'Cyrus timsieved v2.2.13'
+      managesieve_implementation_string = Dovecot Pigeonhole
+
+      # The maximum number of compile errors that are returned to the client upon script
+      # upload or script verification.
+      managesieve_max_compile_errors = 5
+
+      #mail_max_userip_connections = 10
+      #managesieve_implementation_string = Dovecot Pigeonhole
+      managesieve_max_compile_errors = 5
+      #managesieve_max_line_length = 65536
+      #managesieve_notify_capability = mailto
+      #managesieve_sieve_capability = fileinto reject envelope encoded-character vacation subaddress comparator-i;ascii-numeric relational regex imap4flags copy include variables body enotify environment mailbox date ihave
+    }
+    service managesieve-login {
+      inet_listener sieve {
+        port = 4190
+        #ssl  = yes
+      }
 
-        # Number of connections to handle before starting a new process. Typically
-        # the only useful values are 0 (unlimited) or 1. 1 is more secure, but 0
-        # is faster. <doc/wiki/LoginProcess.txt>
-        service_count = 1
-
-        # Number of processes to always keep waiting for more connections.
-        process_min_avail = 0
-
-        # If you set service_count=0, you probably need to grow this.
-        #vsz_limit = 64M
+      # Number of connections to handle before starting a new process. Typically
+      # the only useful values are 0 (unlimited) or 1. 1 is more secure, but 0
+      # is faster. <doc/wiki/LoginProcess.txt>
+      service_count = 1
+
+      # Number of processes to always keep waiting for more connections.
+      process_min_avail = 0
+
+      # If you set service_count=0, you probably need to grow this.
+      #vsz_limit = 64M
+    }
+
+    service quota-warning {
+      executable = script ${
+        pkgs.writeShellScript "quota-warning" ''
+          set -eu
+          PERCENT=$1
+          USER=$2
+          cat << EOF | ${pkgs.dovecot}/libexec/dovecot/dovecot-lda -d $USER -o
+          "plugin/quota=maildir:User quota:noenforcing"
+          From: postmaster@${networking.domain}
+          Subject: [WARNING] your mailbox is now $PERCENT% full.
+
+          Please remove some mails to make room for new ones.
+          EOF
+        ''
+      }
+      # use some unprivileged user for executing the quota warnings
+      user = ${dovecot2.user}
+      unix_listener quota-warning {
       }
-      ssl = required
-      ssl_dh = <${../../../sec/openssl/dh.pem}
-      ssl_cipher_list = HIGH:!LOW:!SSLv2:!EXP:!aNULL
-      ssl_cert = <${loadFile (../../../sec + "/openssl/${networking.domainBase}/cert.self-signed.pem")}
-      ssl_key = </run/keys/dovecot.${networking.domainBase}.key.pem
-      #ssl_ca = <''${caPath}
-      #ssl_verify_client_cert = yes
-    '' );
-      #${lib.concatMapStringsSep "\n"
-      #    (dom: ''
-      #      local_name mail.${dom} {
-      #        #ssl_ca   = <''${caPath}
-      #        ssl_cert = <${x509.cert dom}
-      #        ssl_key  = <${x509.key dom}
-      #        }
-      #    '')
-      #    dovecot2.domains
+    }
+
+    protocol pop3 {
+      mail_plugins = $mail_plugins virtual
+      #mail_max_userip_connections = 10
+      # Virtual namespace for the virtual INBOX.
+      # Use a global directory for dovecot-virtual files.
+      #namespace Inbox {
+      #  hidden    = yes
+      #  list      = no
+      #  location  = virtual:''${dovecot-virtual-pop3}/pop3:INDEX=${stateDir}/index/%d/%n/virtual/pop3:LAYOUT=fs
+      #  prefix    = pop3+
       #}
-  };
+      pop3_client_workarounds =
+      pop3_fast_size_lookups = yes
+      pop3_lock_session = yes
+      pop3_no_flag_updates = yes
+      # Use GUIDs to avoid accidental POP3 UIDL changes instead of IMAP UIDs.
+      pop3_uidl_format = %g
+    }
+    service pop3 {
+      process_limit = 1024
+    }
+    service pop3-login {
+      inet_listener pop3s {
+        port = 995
+        ssl  = yes
+      }
+    }
+  '';
+};
 }