1 {pkgs, lib, config, system, ...}:
2 let inherit (builtins) toString toFile;
4 inherit (pkgs.lib) unlines;
5 inherit (config.services) dovecot2 postfix x509 openldap;
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 # NOTE: 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
191 ${libDir}/pop3/INBOX/dovecot-virtual
197 + unlines (lib.mapAttrsToList (domain: {accounts, ...}:
198 let domainGroup = escapeGroup "${dovecot2.mailGroup}-${domain}"; in
200 install -D -d -m 1770 \
201 -o ${dovecot2.mailUser} \
203 ${mailDir}/${domain} \
204 ${libDir}/control/${domain} \
205 ${libDir}/index/${domain}
206 install -D -d -m 1770 \
207 -o ${dovecot2.mailUser} \
210 ${libDir}/auth/${domain}
211 dir_passwd=${authDir}/${domain}
212 old_passwd=$dir_passwd/passwd
213 new_passwd=$(TMPDIR= mktemp --tmpdir=$dir_passwd -t passwd.XXXXXXXX.tmp)
217 + unlines (lib.mapAttrsToList (user: acct: ''
219 home=${mailDir}/${domain}/${user}
221 shell=/run/current-system/sw/bin/nologin
224 uid=$(stat -c %u $home)
225 gid=$(stat -c %g $home)
227 [ "''${uid:+set}" ] || {
228 while test exists = "$(find $(dirname $home) -mindepth 1 -maxdepth 1 -uid $new_uid -printf exists -quit)"
229 do new_uid=$((new_uid + 1))
234 install -D -d -o $uid -g $gid -m 2770 $home $home/Maildir
235 install -d -o $uid -g $gid -m 0700 $home/sieve
237 + unlines (lib.mapAttrsToList
239 install -D -m 640 -o $uid -g $gid \
240 ${pkgs.writeText "${n}.sieve" v} \
241 $home/sieve/${n}.sieve
242 ${pkgs.dovecot_pigeonhole}/bin/sievec \
243 $home/sieve/${n}.sieve
247 mail_access_groups=${lib.concatStringsSep "," ([domainGroup] ++ acct.groups)}
248 quota=${if lib.isString acct.quota
249 then ''"userdb_quota_rule=*:storage=${acct.quota}"''
251 extra_fields="userdb_uid=$uid userdb_gid=$gid userdb_mail_access_groups=$mail_access_groups $quota"
252 #test ! -e $old_passwd || {
253 # # Preserve password changed by another mechanism, eg. roundcube.
254 # # But this also does not overwrite any old password set by this config.
255 # pass="$(sed -ne "s/^${user}:\([^:]*\):.*/\1/p" $old_passwd)"
257 [ "''${pass:+set}" ] || {
258 pass=${lib.escapeShellArg acct.password}
260 printf '%s\n' >>$new_passwd \
261 "${user}:$pass:$uid:$gid:$gecos:$home:$shell:$extra_fields"
265 install -o ${authUser} -g ${authGroup} -m 0640 $new_passwd $old_passwd
275 services.dovecot2 = {
278 mailUser = "dovemail";
279 mailGroup = "dovemail";
281 #pkgs.dovecot_antispam
282 pkgs.dovecot_pigeonhole
284 configFile = toString (pkgs.writeText "dovecot.conf" ''
287 args = /etc/dovecot/${config.networking.domain}/dovecot-ldap.conf
295 # NOTE: this userdb is only used by lda.
297 args = /etc/dovecot/${config.networking.domain}/dovecot-ldap.conf
303 # driver = passwd-file
304 # args = scheme=crypt username_format=%n ${authDir}/%d/passwd
307 # # NOTE: this userdb is only used by lda.
308 # driver = passwd-file
309 # args = username_format=%n ${authDir}/%d/passwd
310 # #default_fields = home=${mailDir}/%d/%n
313 mail_home = ${mailDir}/%d/%n
314 # NOTE: if needed, may be overrided by userdb_mail
315 mail_location = maildir:${mailDir}/%d/%n/Maildir:LAYOUT=fs:INDEX=${libDir}/index/%d/%n:CONTROL=${libDir}/control/%d/%n
316 # NOTE: if needed, may be overrided by userdb_mail
317 # NOTE: INDEX and CONTROL are on a partition without quota, as explain in the doc.
318 # SEE: http://wiki2.dovecot.org/Quota/FS
319 auth_mechanisms = plain login
320 auth_ssl_require_client_cert = no
321 # NOTE: postfix does not supply a client cert.
322 auth_ssl_username_from_cert = yes
324 auth_username_format = %Lu
325 # NOTE: lowercase the username, help with LDAP?
326 ${lib.optionalString dovecot2.debug ''
331 default_internal_user = ${dovecot2.user}
332 default_internal_group = ${dovecot2.group}
333 disable_plaintext_auth = yes
334 first_valid_uid = 1000
335 lda_mailbox_autocreate = yes
336 lda_mailbox_autosubscribe = yes
338 log_timestamp = "%Y-%m-%d %H:%M:%S "
339 #maildir_copy_with_hardlinks = yes
341 # NOTE: here because protocol sieve {namespace inbox{}} does not seem to work.
346 separator = ${dirSep}
351 location = maildir:${mailDir}/%d/%n/Maildir:LAYOUT=fs:INDEX=${libDir}/index/%d/%n/Shared/%n:CONTROL=${libDir}/control/%d/%n/Shared/%n
352 # FIXME: %d not working
353 prefix = Partages+%%n+
354 separator = ${dirSep}
358 mail_plugins = $mail_plugins acl quota virtual
359 #mail_uid = ${dovecot2.mailUser}
360 #mail_gid = ${dovecot2.mailGroup}
361 # NOTE: each user has a dedicated (uid,gid) pair
362 #mail_privileged_group = mail
363 #mail_access_groups =
365 acl = vfile:/etc/dovecot/acl/global.d
367 acl_shared_dict = file:${mailDir}/%d/acl.db
368 # NOTE: to let users LIST mailboxes shared by other users,
369 # Dovecot needs a shared mailbox dictionary.
370 # FIXME: %d not working with userdb ldap
371 ##antispam_allow_append_to_spam = yes
372 # # NOTE: pour offlineimap
373 #antispam_backend = pipe
374 ##antispam_crm_args = -u;${mailDir}/%d/.crm114;/usr/share/crm114/mailfilter.crm
375 #antispam_crm_args = -u;${mailDir}/crm114;/usr/share/crm114/mailfilter.crm
376 #antispam_crm_binary = /usr/bin/crm
377 #antispam_debug_target = syslog
378 ##antispam_crm_env = HOME=%h;USER=%u
379 #antispam_ham_keywords = NonJunk
380 #antispam_pipe_program = /usr/bin/crm
381 #antispam_pipe_program_args = -u;${mailDir}/crm114;/usr/share/crm114/mailfilter.crm;--stats_only;--force
382 #antispam_pipe_program_notspam_arg = --learnnonspam
383 #antispam_pipe_program_spam_arg = --learnspam
384 #antispam_pipe_program_unlearn_spam_args = --unlearn;--learnspam
385 #antispam_pipe_program_unlearn_notspam_args = --unlearn;--learnnonspam
386 #antispam_pipe_tmpdir = ${mailDir}/crm114/tmp
387 #antispam_signature = X-CRM114-CacheID
388 #antispam_signature_missing = move
389 #antispam_spam = Junk
390 #antispam_spam_keywords = Junk
391 #antispam_trash = Trash
392 #antispam_unsure = Unsure
393 #antispam_verbose_debug = 0
394 quota = maildir:User quota
395 quota_rule = *:storage=256M
396 quota_rule2 = Trash:storage=+64M
397 quota_max_mail_size = 20M
398 #quota_exceeded_message = </path/to/quota_exceeded_message.txt
399 quota_warning = storage=95%% quota-warning 95 %u
400 quota_warning2 = storage=80%% quota-warning 80 %u
401 quota_warning3 = -storage=100%% quota-warning below %u
402 # NOTE: user is no longer over quota
403 recipient_delimiter = ${extSep}
404 sieve = file:${mailDir}/%d/%n/sieve;active=${mailDir}/%d/%n/sieve/main.sieve
405 #sieve_default = file:${mailDir}/%u/default.sieve
406 #sieve_default_name = default
407 sieve_after = ${sieveDir}/after.d/
408 sieve_before = ${sieveDir}/before.d/
409 sieve_dir = ${mailDir}/%d/%n/sieve/
410 #sieve_extensions = +spamtest +spamtestplus
411 sieve_global_dir = ${sieveDir}/global.d/
412 sieve_max_script_size = 1M
413 sieve_quota_max_scripts = 0
414 sieve_quota_max_storage = 10M
415 sieve_spamtest_max_value = 10
416 sieve_spamtest_status_header = X-Spam-Score
417 sieve_spamtest_status_type = strlen
418 sieve_user_log = /var/log/dovecot/%d/sieve.%n.log
420 service quota-warning {
421 executable = script ${
422 pkgs.writeScript "quota-warning" ''
426 cat << EOF | ${pkgs.dovecot}/libexec/dovecot/dovecot-lda -d $USER -o
427 "plugin/quota=maildir:User quota:noenforcing"
428 From: postmaster@${config.networking.domain}
429 Subject: [WARNING] your mailbox is now $PERCENT% full.
431 Please remove some mails to make room for new ones.
435 # use some unprivileged user for executing the quota warnings
436 user = ${dovecot2.user}
437 unix_listener quota-warning {
441 #mail_max_userip_connections = 10
442 mail_plugins = $mail_plugins imap_acl imap_quota # antispam
448 special_use = \Drafts
456 mailbox "Sent Messages" {
463 separator = ${dirSep}
467 auth_socket_path = /var/run/dovecot/auth-userdb
468 hostname = ${config.networking.domain}
471 mail_plugins = $mail_plugins sieve
477 separator = ${dirSep}
479 postmaster_address = postmaster${extSep}dovecot${extSep}lda@${config.networking.domain}
480 syslog_facility = mail
483 #info_log_path = /tmp/dovecot-lmtp.log
484 mail_plugins = $mail_plugins sieve
490 separator = ${dirSep}
492 postmaster_address = postmaster${extSep}dovecot${extSep}lmtp@${config.networking.domain}
495 #mail_max_userip_connections = 10
497 # NOTE: used by ${libDir}/pop3/INBOX/dovecot-virtual
502 separator = ${dirSep}
504 # Virtual namespace for the virtual INBOX.
505 # Use a global directory for dovecot-virtual files.
510 location = virtual:${libDir}/pop3:INDEX=${libDir}/index/%d/%n/POP3:LAYOUT=fs
512 separator = ${dirSep}
514 pop3_client_workarounds =
515 pop3_fast_size_lookups = yes
516 pop3_lock_session = yes
517 pop3_no_flag_updates = yes
518 # Use GUIDs to avoid accidental POP3 UIDL changes instead of IMAP UIDs.
519 pop3_uidl_format = %g
522 #mail_max_userip_connections = 10
523 #managesieve_implementation_string = Dovecot Pigeonhole
524 managesieve_max_compile_errors = 5
525 #managesieve_max_line_length = 65536
526 #managesieve_notify_capability = mailto
527 #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
529 protocols = imap lmtp pop3 sieve
531 #executable = lmtp -L
532 process_min_avail = 2
533 unix_listener /var/lib/postfix/queue/private/dovecot-lmtp {
534 user = ${postfix.user}
535 group = ${postfix.group}
542 # FIXME: may be user=dovecot-auth with LDAP?
543 unix_listener auth-userdb {
544 user = ${dovecot2.user}
545 group = ${dovecot2.group}
548 unix_listener /var/lib/postfix/queue/private/auth {
549 user = ${postfix.user}
550 group = ${postfix.group}
555 # Most of the memory goes to mmap()ing files.
556 # You may need to increase this limit if you have huge mailboxes.
561 #inet_listener imap {
562 # address = 127.0.0.1
566 inet_listener imaps {
575 inet_listener pop3s {
581 ssl_dh = <${x509.dir}/dh.pem
582 ssl_cipher_list = HIGH:!LOW:!SSLv2:!EXP:!aNULL
583 ssl_cert = <${x509.cert}
584 ssl_key = <${x509.key}
585 #ssl_ca = <''${caPath}
586 #ssl_verify_client_cert = yes
588 #${lib.concatMapStringsSep "\n"
590 # local_name mail.${dom} {
591 # #ssl_ca = <''${caPath}
592 # ssl_cert = <${x509.cert dom}
593 # ssl_key = <${x509.key dom}