1 {pkgs, lib, config, system, ...}:
2 let inherit (builtins) toString toFile;
4 inherit (config.services) dovecot2 postfix x509 openldap;
5 unlines = lib.concatStringsSep "\n";
6 when = x: y: if x == null then "" else y;
7 extSep = postfix.recipientDelimiter;
9 libDir = "/var/lib/dovecot";
10 mailDir = "${libDir}/mail";
11 sieveDir = "${libDir}/sieve";
12 authDir = "${libDir}/auth";
13 authUser = dovecot2.mailUser; # TODO: php_roundcube
14 authGroup = dovecot2.mailGroup; # TODO: php_roundcube
15 escapeGroup = lib.stringAsChars (c: if "a"<=c && c<="z"
20 { target = "dovecot/${config.networking.domain}/dovecot-ldap.conf";
21 source = pkgs.writeText "dovecot-ldap.conf" ''
22 ${lib.optionalString dovecot2.debug ''
28 base = ou=posix,${openldap.domainSuffix}
32 # NOTE: sufficient for small systems and uses less resources.
37 dn = cn=admin,${openldap.domainSuffix}
38 #dnpass = useless with sasl_mech=EXTERNAL
40 #auth_bind_userdn = cn=%n,ou=accounts,ou=posix,dc=${openldap.domainSuffix}
42 # dovecot passdb query
43 pass_filter = (&(objectClass=posixAccount)(uid=%n))
44 pass_attrs = userPassword=password,\
45 uidNumber=userdb_uid,\
46 gidNumber=userdb_gid,\
47 mailGroupMember=mail_access_groups,\
49 #homeDirectory=userdb_home
50 #quotaBytes=userdb_quota_rule=*:bytes=%{ldap:quotaBytes}
51 # TODO: userdb_quota_rule=*:storage=
52 # TODO: userdb_mail_access_groups
53 # DOC: http://wiki2.dovecot.org/PasswordDatabase/ExtraFields
54 default_pass_scheme = CRYPT
56 # dovecot userdb query
57 user_filter = (&(objectClass=posixAccount)(uid=%n))
58 #user_filter = (&(objectClass=inetOrgPerson)(uid=%n)(mailEnabled=TRUE))
59 # # DOC: http://wiki2.dovecot.org/Variables
60 #user_attrs = homeDirectory=home,uidNumber=uid,gidNumber=gid
61 #user_attrs = mailHomeDirectory=home,\
62 # mailStorageDirectory=mail,\
65 # mailQuota=quota_rule=*:bytes=%$
66 # # DOC: http://wiki2.dovecot.org/UserDatabase/ExtraFields
69 iterate_attrs = =user=%{ldap:uid}@${config.networking.domain}
70 iterate_filter = (objectClass=posixAccount)
77 dovecot/autoconfig.nix
80 systemd.services.dovecot2.after = [ "postfix.service" ];
81 systemd.services.dovecot2.restartTriggers =
82 map (f: f.source) etc_dovecot;
83 environment.etc = etc_dovecot;
84 #services.postfix.mapFiles."transport-dovecot" =
85 # toFile "transport-dovecot"
88 # (dom: {...}: "${transportSubDomain}.${dom} lmtp:unix:private/dovecot-lmtp")
92 # uid = config.ids.uids.dovecot2;
93 # description = "Dovecot user";
94 # group = dovecot2.group;
100 { name = escapeGroup "${dovecot2.mailGroup}-${domain}";
103 systemd.services.dovecot2.preStart =
105 pkgs.writeText "list.sieve" ''
113 if currentdate :matches "year" "*" { set "year" "''${1}"; }
114 if currentdate :matches "month" "*" { set "month" "''${1}"; }
116 if exists "List-ID" {
117 if header :matches "List-ID" "*<*.*.*.*>*" {
119 set "domain" "''${4}";
121 elsif header :matches "List-ID" "*<*.*.*>*" {
123 set "domain" "''${3}";
125 fileinto :create "Listes+''${domain}+''${list}+''${year}+''${month}";
130 pkgs.writeText "spam.sieve" ''
135 if header :contains "X-Spam-Level" "***" {
140 pkgs.writeText "extension.sieve" ''
148 if envelope :matches :detail "TO" "*" {
149 set "extension" "''${1}";
151 if not string :is "''${extension}" "" {
152 fileinto :create "Plus+''${extension}";
157 pkgs.writeText "dovecot-virtual" ''
163 # SEE: http://wiki2.dovecot.org/SharedMailboxes/Permissions
164 # The sticky bit is to allow the acl.db{.lock,} done by dovecot
165 install -D -d -m 2771 \
166 -o ${dovecot2.mailUser} \
167 -g ${dovecot2.mailGroup} \
170 # Install global sieves
171 install -D -d -m 0755 \
175 ${sieveDir}/after.d \
176 ${sieveDir}/before.d \
178 ln -fns ${sieveList} ${sieveDir}/global.d/list.sieve
179 ln -fns ${sieveExtension} ${sieveDir}/global.d/extension.sieve
180 ln -fns ${sieveSpam} ${sieveDir}/global.d/spam.sieve
181 for f in ${sieveDir}/*/*.sieve
182 do ${pkgs.dovecot_pigeonhole}/bin/sievec $f
190 ${libDir}/pop3/INBOX/dovecot-virtual
196 + unlines (lib.mapAttrsToList (domain: {accounts, ...}:
197 let domainGroup = escapeGroup "${dovecot2.mailGroup}-${domain}"; in
199 install -D -d -m 1770 \
200 -o ${dovecot2.mailUser} \
202 ${mailDir}/${domain} \
203 ${libDir}/control/${domain} \
204 ${libDir}/index/${domain}
205 install -D -d -m 1770 \
206 -o ${dovecot2.mailUser} \
209 ${libDir}/auth/${domain}
210 dir_passwd=${authDir}/${domain}
211 old_passwd=$dir_passwd/passwd
212 new_passwd=$(TMPDIR= mktemp --tmpdir=$dir_passwd -t passwd.XXXXXXXX.tmp)
216 + unlines (lib.mapAttrsToList (user: acct: ''
218 home=${mailDir}/${domain}/${user}
220 shell=/run/current-system/sw/bin/nologin
223 uid=$(stat -c %u $home)
224 gid=$(stat -c %g $home)
226 [ "''${uid:+set}" ] || {
227 while test exists = "$(find $(dirname $home) -mindepth 1 -maxdepth 1 -uid $new_uid -printf exists -quit)"
228 do new_uid=$((new_uid + 1))
233 install -D -d -o $uid -g $gid -m 2770 $home $home/Maildir
234 install -d -o $uid -g $gid -m 0700 $home/sieve
236 + unlines (lib.mapAttrsToList
238 install -D -m 640 -o $uid -g $gid \
239 ${pkgs.writeText "${n}.sieve" v} \
240 $home/sieve/${n}.sieve
241 ${pkgs.dovecot_pigeonhole}/bin/sievec \
242 $home/sieve/${n}.sieve
246 mail_access_groups=${lib.concatStringsSep "," ([domainGroup] ++ acct.groups)}
247 quota=${if lib.isString acct.quota
248 then ''"userdb_quota_rule=*:storage=${acct.quota}"''
250 extra_fields="userdb_uid=$uid userdb_gid=$gid userdb_mail_access_groups=$mail_access_groups $quota"
251 #test ! -e $old_passwd || {
252 # # Preserve password changed by another mechanism, eg. roundcube.
253 # # But this also does not overwrite any old password set by this config.
254 # pass="$(sed -ne "s/^${user}:\([^:]*\):.*/\1/p" $old_passwd)"
256 [ "''${pass:+set}" ] || {
257 pass=${lib.escapeShellArg acct.password}
259 printf '%s\n' >>$new_passwd \
260 "${user}:$pass:$uid:$gid:$gecos:$home:$shell:$extra_fields"
264 install -o ${authUser} -g ${authGroup} -m 0640 $new_passwd $old_passwd
268 services.dovecot2 = {
271 mailUser = "dovemail";
272 mailGroup = "dovemail";
274 #pkgs.dovecot_antispam
275 pkgs.dovecot_pigeonhole
277 configFile = toString (pkgs.writeText "dovecot.conf" ''
280 args = /etc/dovecot/${config.networking.domain}/dovecot-ldap.conf
288 # NOTE: this userdb is only used by lda.
290 args = /etc/dovecot/${config.networking.domain}/dovecot-ldap.conf
296 # driver = passwd-file
297 # args = scheme=crypt username_format=%n ${authDir}/%d/passwd
300 # # NOTE: this userdb is only used by lda.
301 # driver = passwd-file
302 # args = username_format=%n ${authDir}/%d/passwd
303 # #default_fields = home=${mailDir}/%d/%n
306 mail_home = ${mailDir}/%d/%n
307 # NOTE: if needed, may be overrided by userdb_mail
308 mail_location = maildir:${mailDir}/%d/%n/Maildir:LAYOUT=fs:INDEX=${libDir}/index/%d/%n:CONTROL=${libDir}/control/%d/%n
309 # NOTE: if needed, may be overrided by userdb_mail
310 # NOTE: INDEX and CONTROL are on a partition without quota, as explain in the doc.
311 # SEE: http://wiki2.dovecot.org/Quota/FS
312 auth_mechanisms = plain login
313 auth_ssl_require_client_cert = no
314 # NOTE: postfix does not supply a client cert.
315 auth_ssl_username_from_cert = yes
317 auth_username_format = %Lu
318 # NOTE: lowercase the username, help with LDAP?
319 ${lib.optionalString dovecot2.debug ''
324 default_internal_user = ${dovecot2.user}
325 default_internal_group = ${dovecot2.group}
326 disable_plaintext_auth = yes
327 first_valid_uid = 1000
328 lda_mailbox_autocreate = yes
329 lda_mailbox_autosubscribe = yes
331 log_timestamp = "%Y-%m-%d %H:%M:%S "
332 #maildir_copy_with_hardlinks = yes
334 # NOTE: here because protocol sieve {namespace inbox{}} does not seem to work.
339 separator = ${dirSep}
344 location = maildir:${mailDir}/%d/%n/Maildir:LAYOUT=fs:INDEX=${libDir}/index/%d/%n/Shared/%n:CONTROL=${libDir}/control/%d/%n/Shared/%n
345 # FIXME: %d not working
346 prefix = Partages+%%n+
347 separator = ${dirSep}
351 mail_plugins = $mail_plugins acl quota virtual
352 #mail_uid = ${dovecot2.mailUser}
353 #mail_gid = ${dovecot2.mailGroup}
354 # NOTE: each user has a dedicated (uid,gid) pair
355 #mail_privileged_group = mail
356 #mail_access_groups =
358 acl = vfile:/etc/dovecot/acl/global.d
360 acl_shared_dict = file:${mailDir}/%d/acl.db
361 # NOTE: to let users LIST mailboxes shared by other users,
362 # Dovecot needs a shared mailbox dictionary.
363 # FIXME: %d not working with userdb ldap
364 ##antispam_allow_append_to_spam = yes
365 # # NOTE: pour offlineimap
366 #antispam_backend = pipe
367 ##antispam_crm_args = -u;${mailDir}/%d/.crm114;/usr/share/crm114/mailfilter.crm
368 #antispam_crm_args = -u;${mailDir}/crm114;/usr/share/crm114/mailfilter.crm
369 #antispam_crm_binary = /usr/bin/crm
370 #antispam_debug_target = syslog
371 ##antispam_crm_env = HOME=%h;USER=%u
372 #antispam_ham_keywords = NonJunk
373 #antispam_pipe_program = /usr/bin/crm
374 #antispam_pipe_program_args = -u;${mailDir}/crm114;/usr/share/crm114/mailfilter.crm;--stats_only;--force
375 #antispam_pipe_program_notspam_arg = --learnnonspam
376 #antispam_pipe_program_spam_arg = --learnspam
377 #antispam_pipe_program_unlearn_spam_args = --unlearn;--learnspam
378 #antispam_pipe_program_unlearn_notspam_args = --unlearn;--learnnonspam
379 #antispam_pipe_tmpdir = ${mailDir}/crm114/tmp
380 #antispam_signature = X-CRM114-CacheID
381 #antispam_signature_missing = move
382 #antispam_spam = Junk
383 #antispam_spam_keywords = Junk
384 #antispam_trash = Trash
385 #antispam_unsure = Unsure
386 #antispam_verbose_debug = 0
387 quota = maildir:User quota
388 quota_rule = *:storage=256M
389 quota_rule2 = Trash:storage=+64M
390 quota_max_mail_size = 20M
391 #quota_exceeded_message = </path/to/quota_exceeded_message.txt
392 quota_warning = storage=95%% quota-warning 95 %u
393 quota_warning2 = storage=80%% quota-warning 80 %u
394 quota_warning3 = -storage=100%% quota-warning below %u
395 # NOTE: user is no longer over quota
396 recipient_delimiter = ${extSep}
397 sieve = file:${mailDir}/%d/%n/sieve;active=${mailDir}/%d/%n/sieve/main.sieve
398 #sieve_default = file:${mailDir}/%u/default.sieve
399 #sieve_default_name = default
400 sieve_after = ${sieveDir}/after.d/
401 sieve_before = ${sieveDir}/before.d/
402 sieve_dir = ${mailDir}/%d/%n/sieve/
403 #sieve_extensions = +spamtest +spamtestplus
404 sieve_global_dir = ${sieveDir}/global.d/
405 sieve_max_script_size = 1M
406 sieve_quota_max_scripts = 0
407 sieve_quota_max_storage = 10M
408 sieve_spamtest_max_value = 10
409 sieve_spamtest_status_header = X-Spam-Score
410 sieve_spamtest_status_type = strlen
411 sieve_user_log = /var/log/dovecot/%d/sieve.%n.log
413 service quota-warning {
414 executable = script ${
415 pkgs.writeScript "quota-warning" ''
419 cat << EOF | ${pkgs.dovecot}/libexec/dovecot/dovecot-lda -d $USER -o
420 "plugin/quota=maildir:User quota:noenforcing"
421 From: postmaster@${config.networking.domain}
422 Subject: [WARNING] your mailbox is now $PERCENT% full.
424 Please remove some mails to make room for new ones.
428 # use some unprivileged user for executing the quota warnings
429 user = ${dovecot2.user}
430 unix_listener quota-warning {
434 #mail_max_userip_connections = 10
435 mail_plugins = $mail_plugins imap_acl imap_quota # antispam
441 special_use = \Drafts
449 mailbox "Sent Messages" {
456 separator = ${dirSep}
460 auth_socket_path = /var/run/dovecot/auth-userdb
461 hostname = ${config.networking.domain}
464 mail_plugins = $mail_plugins sieve
470 separator = ${dirSep}
472 postmaster_address = postmaster${extSep}dovecot${extSep}lda@${config.networking.domain}
473 syslog_facility = mail
476 #info_log_path = /tmp/dovecot-lmtp.log
477 mail_plugins = $mail_plugins sieve
483 separator = ${dirSep}
485 postmaster_address = postmaster${extSep}dovecot${extSep}lmtp@${config.networking.domain}
488 #mail_max_userip_connections = 10
490 # NOTE: used by ${libDir}/pop3/INBOX/dovecot-virtual
495 separator = ${dirSep}
497 # Virtual namespace for the virtual INBOX.
498 # Use a global directory for dovecot-virtual files.
503 location = virtual:${libDir}/pop3:INDEX=${libDir}/index/%d/%n/POP3:LAYOUT=fs
505 separator = ${dirSep}
507 pop3_client_workarounds =
508 pop3_fast_size_lookups = yes
509 pop3_lock_session = yes
510 pop3_no_flag_updates = yes
511 # Use GUIDs to avoid accidental POP3 UIDL changes instead of IMAP UIDs.
512 pop3_uidl_format = %g
515 #mail_max_userip_connections = 10
516 #managesieve_implementation_string = Dovecot Pigeonhole
517 managesieve_max_compile_errors = 5
518 #managesieve_max_line_length = 65536
519 #managesieve_notify_capability = mailto
520 #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
522 protocols = imap lmtp pop3 sieve
524 #executable = lmtp -L
525 process_min_avail = 2
526 unix_listener /var/lib/postfix/queue/private/dovecot-lmtp {
527 user = ${postfix.user}
528 group = ${postfix.group}
535 # FIXME: may be user=dovecot-auth with LDAP?
536 unix_listener auth-userdb {
537 user = ${dovecot2.user}
538 group = ${dovecot2.group}
541 unix_listener /var/lib/postfix/queue/private/auth {
542 user = ${postfix.user}
543 group = ${postfix.group}
548 # Most of the memory goes to mmap()ing files.
549 # You may need to increase this limit if you have huge mailboxes.
554 #inet_listener imap {
555 # address = 127.0.0.1
559 inet_listener imaps {
568 inet_listener pop3s {
574 ssl_dh = <${x509.dir}/dh.pem
575 ssl_cipher_list = HIGH:!LOW:!SSLv2:!EXP:!aNULL
576 ssl_cert = <${x509.cert}
577 ssl_key = <${x509.key}
578 #ssl_ca = <''${caPath}
579 #ssl_verify_client_cert = yes
581 #${lib.concatMapStringsSep "\n"
583 # local_name mail.${dom} {
584 # #ssl_ca = <''${caPath}
585 # ssl_cert = <${x509.cert dom}
586 # ssl_key = <${x509.key dom}