]> Git — Sourcephile - sourcephile-nix.git/blob - install/logical/friot/dovecot.nix
update
[sourcephile-nix.git] / install / logical / friot / dovecot.nix
1 {pkgs, lib, config, system, ...}:
2 let inherit (builtins) toString toFile attrNames;
3 inherit (lib) types;
4 inherit (config.services) dovecot2 postfix x509;
5 unlines = lib.concatStringsSep "\n";
6 when = x: y: if x == null then "" else y;
7 extSep = postfix.recipientDelimiter;
8 dirSep = extSep;
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"
16 || "0"<=c && c<="9"
17 || c=="-"
18 then c else "_");
19 in
20 {
21 config = {
22 #environment.etc."nginx/site.d/autoconfig.conf".source =
23 # let servers = lib.concatMapStringsSep " "
24 # (dom: "autoconfig.${dom}")
25 # (attrNames dovecot2.domains);
26 # autoconfigSite = pkgs.writeTextFile {
27 # name = "autoconfig";
28 # destination = "/mail/config-v1.1.xml";
29 # text = ''
30 # <?xml version="1.0"?>
31 # <clientConfig version="1.1">
32 # <emailProvider id="%EMAILDOMAIN%">
33 # <!-- <displayName></displayName> -->
34 # <!-- <displayShortName></displayShortName> -->
35 # <domain>%EMAILDOMAIN%</domain>
36 # <incomingServer type="imap">
37 # <hostname>imap.%EMAILDOMAIN%</hostname>
38 # <port>993</port>
39 # <socketType>SSL</socketType>
40 # <username>%EMAILADDRESS%</username>
41 # <authentication>password-cleartext</authentication>
42 # </incomingServer>
43 # <incomingServer type="pop3">
44 # <hostname>pop.%EMAILDOMAIN%</hostname>
45 # <port>995</port>
46 # <socketType>SSL</socketType>
47 # <username>%EMAILADDRESS%</username>
48 # <authentication>password-cleartext</authentication>
49 # <pop3>
50 # <leaveMessagesOnServer>false</leaveMessagesOnServer>
51 # <downloadOnBiff>true</downloadOnBiff>
52 # </pop3>
53 # </incomingServer>
54 # <outgoingServer type="smtp">
55 # <hostname>smtp.%EMAILDOMAIN%</hostname>
56 # <port>465</port>
57 # <socketType>SSL</socketType> <!-- see above -->
58 # <username>%EMAILADDRESS%</username> <!-- if smtp-auth -->
59 # <authentication>password-cleartext</authentication>
60 # <!-- <restriction>client-IP-address</restriction> -->
61 # <addThisServer>true</addThisServer>
62 # <useGlobalPreferredServer>false</useGlobalPreferredServer>
63 # </outgoingServer>
64 # </emailProvider>
65 # <!-- <clientConfigUpdate url="https://www.example.com/config/mozilla.xml" /> -->
66 # </clientConfig>
67 # '';
68 # };
69 # in
70 # pkgs.writeText "autoconfig.conf" ''
71 # server {
72 # listen 80;
73 # server_name ${servers};
74 # root ${autoconfigSite};
75 # access_log off;
76 # log_not_found off;
77 # }
78 # server {
79 # listen 443 ssl http2;
80 # ssl on;
81 # server_name ${servers};
82 # root ${autoconfigSite};
83 # access_log off;
84 # log_not_found off;
85 # }
86 # '';
87 #services.postfix.mapFiles."transport-dovecot" =
88 # toFile "transport-dovecot"
89 # (unlines
90 # (lib.mapAttrsToList
91 # (dom: {...}: "${transportSubDomain}.${dom} lmtp:unix:private/dovecot-lmtp")
92 # dovecot2.domains));
93 systemd.services.dovecot2.after = [ "postfix.service" ];
94 #users.extraUsers = [
95 # { name = "dovecot";
96 # uid = config.ids.uids.dovecot2;
97 # description = "Dovecot user";
98 # group = dovecot2.group;
99 # }
100 #];
101 users.extraGroups = lib.mapAttrs
102 (domain: {...}:
103 { name = escapeGroup "${dovecot2.mailGroup}-${domain}";
104 })
105 dovecot2.domains;
106 systemd.services.dovecot2.preStart =
107 let sieveList =
108 pkgs.writeText "list.sieve" ''
109 require
110 [ "date"
111 , "fileinto"
112 , "mailbox"
113 , "variables"
114 ];
115
116 if currentdate :matches "year" "*" { set "year" "''${1}"; }
117 if currentdate :matches "month" "*" { set "month" "''${1}"; }
118
119 if exists "List-ID" {
120 if header :matches "List-ID" "*<*.*.*.*>*" {
121 set "list" "''${2}";
122 set "domain" "''${4}";
123 }
124 elsif header :matches "List-ID" "*<*.*.*>*" {
125 set "list" "''${2}";
126 set "domain" "''${3}";
127 }
128 fileinto :create "Listes+''${domain}+''${list}+''${year}+''${month}";
129 stop;
130 }
131 '';
132 sieveSpam =
133 pkgs.writeText "spam.sieve" ''
134 require
135 [ "imap4flags"
136 ];
137
138 if header :contains "X-Spam-Level" "***" {
139 addflag "Junk";
140 }
141 '';
142 sieveExtension =
143 pkgs.writeText "extension.sieve" ''
144 require
145 [ "envelope"
146 , "fileinto"
147 , "mailbox"
148 , "subaddress"
149 , "variables"
150 ];
151 if envelope :matches :detail "TO" "*" {
152 set "extension" "''${1}";
153 }
154 if not string :is "''${extension}" "" {
155 fileinto :create "Plus+''${extension}";
156 stop;
157 }
158 '';
159 dovecot-virtual =
160 pkgs.writeText "dovecot-virtual" ''
161 all
162 all+*
163 all
164 '';
165 in ''
166 # SEE: http://wiki2.dovecot.org/SharedMailboxes/Permissions
167 # The sticky bit is to allow the acl.db{.lock,} done by dovecot
168 install -D -d -m 2771 \
169 -o ${dovecot2.mailUser} \
170 -g ${dovecot2.mailGroup} \
171 ${mailDir}
172
173 # Install global sieves
174 install -D -d -m 0755 \
175 -o root \
176 -g root \
177 ${sieveDir} \
178 ${sieveDir}/after.d \
179 ${sieveDir}/before.d \
180 ${sieveDir}/global.d
181 ln -fns ${sieveList} ${sieveDir}/global.d/list.sieve
182 ln -fns ${sieveExtension} ${sieveDir}/global.d/extension.sieve
183 ln -fns ${sieveSpam} ${sieveDir}/global.d/spam.sieve
184 for f in ${sieveDir}/*/*.sieve
185 do ${pkgs.dovecot_pigeonhole}/bin/sievec $f
186 done
187
188 # Install pop3 Inbox
189 install -D -m 0644 \
190 -o root \
191 -g root \
192 ${dovecot-virtual} \
193 ${libDir}/pop3/INBOX/dovecot-virtual
194 ''
195 + ''
196 # Install domains
197 new_uid=5000
198 ''
199 + unlines (lib.mapAttrsToList (domain: {accounts, ...}:
200 let domainGroup = escapeGroup "${dovecot2.mailGroup}-${domain}"; in
201 ''
202 install -D -d -m 1770 \
203 -o ${dovecot2.mailUser} \
204 -g ${domainGroup} \
205 ${mailDir}/${domain} \
206 ${libDir}/control/${domain} \
207 ${libDir}/index/${domain}
208 install -D -d -m 1770 \
209 -o ${dovecot2.mailUser} \
210 -g ${authGroup} \
211 ${libDir}/auth \
212 ${libDir}/auth/${domain}
213 dir_passwd=${libDir}/auth/${domain}
214 old_passwd=$dir_passwd/passwd
215 new_passwd=$(TMPDIR= mktemp --tmpdir=$dir_passwd -t passwd.XXXXXXXX.tmp)
216
217 # Install users
218 ''
219 + unlines (lib.mapAttrsToList (user: acct: ''
220 (
221 home=${mailDir}/${domain}/${user}
222 gecos=
223 shell=/run/current-system/sw/bin/nologin
224 if test -e $home
225 then
226 uid=$(stat -c %u $home)
227 gid=$(stat -c %g $home)
228 fi
229 [ "''${uid:+set}" ] || {
230 while test exists = "$(find $(dirname $home) -mindepth 1 -maxdepth 1 -uid $new_uid -printf exists -quit)"
231 do new_uid=$((new_uid + 1))
232 done
233 uid=$new_uid
234 gid=$new_uid
235 }
236 install -D -d -o $uid -g $gid -m 2770 $home $home/Maildir
237 install -d -o $uid -g $gid -m 0700 $home/sieve
238 ''
239 + unlines (lib.mapAttrsToList
240 (n: v: ''
241 install -D -m 640 -o $uid -g $gid \
242 ${pkgs.writeText "${n}.sieve" v} \
243 $home/sieve/${n}.sieve
244 ${pkgs.dovecot_pigeonhole}/bin/sievec \
245 $home/sieve/${n}.sieve
246 '')
247 acct.sieves)
248 + ''
249 mail_access_groups=${lib.concatStringsSep "," ([domainGroup] ++ acct.groups)}
250 quota=${if lib.isString acct.quota
251 then ''"userdb_quota_rule=*:storage=${acct.quota}"''
252 else ""}
253 extra_fields="userdb_uid=$uid userdb_gid=$gid userdb_mail_access_groups=$mail_access_groups $quota"
254 #test ! -e $old_passwd || {
255 # # Preserve password changed by another mechanism, eg. roundcube.
256 # # But this also does not overwrite any old password set by this config.
257 # pass="$(sed -ne "s/^${user}:\([^:]*\):.*/\1/p" $old_passwd)"
258 #}
259 [ "''${pass:+set}" ] || {
260 pass=${lib.escapeShellArg acct.password}
261 }
262 printf '%s\n' >>$new_passwd \
263 "${user}:$pass:$uid:$gid:$gecos:$home:$shell:$extra_fields"
264 )
265 '') accounts)
266 + ''
267 install -o ${authUser} -g ${authGroup} -m 0640 $new_passwd $old_passwd
268 rm $new_passwd
269 ''
270 ) dovecot2.domains);
271 services.dovecot2 = {
272 enable = true;
273 mailUser = "dovemail";
274 mailGroup = "dovemail";
275 modules = [
276 #pkgs.dovecot_antispam
277 pkgs.dovecot_pigeonhole
278 ];
279 # ${lib.concatMapStringsSep "\n"
280 # (dom: ''
281 # local_name imap.${dom} {
282 # #ssl_ca = <''${caPath}
283 # ssl_cert = <${x509.cert dom}
284 # ssl_key = <${x509.key dom}
285 # }
286 # local_name pop.${dom} {
287 # #ssl_ca = <''${caPath}
288 # ssl_cert = <${x509.cert dom}
289 # ssl_key = <${x509.key dom}
290 # }
291 # '')
292 # dovecot2.domains
293 # }
294
295 configFile = toString (pkgs.writeText "dovecot.conf" ''
296 passdb {
297 driver = passwd-file
298 args = scheme=crypt username_format=%n ${authDir}/%d/passwd
299 }
300 userdb {
301 driver = prefetch
302 }
303 userdb {
304 # NOTE: this userdb is only used by lda.
305 driver = passwd-file
306 args = username_format=%n ${authDir}/%d/passwd
307 #default_fields = home=${mailDir}/%d/%n
308 }
309 mail_home = ${mailDir}/%d/%n
310 auth_mechanisms = plain login
311 # postfix does not supply a client cert.
312 auth_ssl_require_client_cert = no
313 auth_ssl_username_from_cert = yes
314 auth_verbose = yes
315 ${lib.optionalString dovecot2.debug ''
316 auth_debug = yes
317 mail_debug = yes
318 verbose_ssl = yes
319 ''}
320 default_internal_user = ${dovecot2.user}
321 default_internal_group = ${dovecot2.group}
322 disable_plaintext_auth = yes
323 first_valid_uid = 1000
324 lda_mailbox_autocreate = yes
325 lda_mailbox_autosubscribe = yes
326 listen = *
327 log_timestamp = "%Y-%m-%d %H:%M:%S "
328 # NOTE: INDEX and CONTROL are on a partition without quota, as explain in the doc.
329 # SEE: http://wiki2.dovecot.org/Quota/FS
330 mail_location = maildir:${mailDir}/%d/%n/Maildir:LAYOUT=fs:INDEX=${libDir}/index/%d/%n:CONTROL=${libDir}/control/%d/%n
331 namespace inbox {
332 # NOTE: here because protocol sieve {namespace inbox{}} does not seem to work.
333 inbox = yes
334 location =
335 list = yes
336 prefix =
337 separator = ${dirSep}
338 }
339 namespace {
340 #list = children
341 list = yes
342 location = maildir:${mailDir}/%%d/%%n/Maildir:LAYOUT=fs:INDEX=${libDir}/index/%d/%n/Shared/%%n:CONTROL=${libDir}/control/%d/%n/Shared/%%n
343 prefix = Partages+%%n+
344 separator = ${dirSep}
345 subscriptions = yes
346 type = shared
347 }
348 mail_plugins = $mail_plugins acl quota virtual
349 #mail_uid = ${dovecot2.mailUser}
350 #mail_gid = ${dovecot2.mailGroup}
351 #mail_privileged_group = mail
352 #mail_access_groups =
353 plugin {
354 acl = vfile:/etc/dovecot/acl/global.d
355 acl_anyone = allow
356 acl_shared_dict = file:${mailDir}/%d/acl.db
357 ##antispam_allow_append_to_spam = yes
358 # # NOTE: pour offlineimap
359 #antispam_backend = pipe
360 ##antispam_crm_args = -u;${mailDir}/%d/.crm114;/usr/share/crm114/mailfilter.crm
361 #antispam_crm_args = -u;${mailDir}/crm114;/usr/share/crm114/mailfilter.crm
362 #antispam_crm_binary = /usr/bin/crm
363 #antispam_debug_target = syslog
364 ##antispam_crm_env = HOME=%h;USER=%u
365 #antispam_ham_keywords = NonJunk
366 #antispam_pipe_program = /usr/bin/crm
367 #antispam_pipe_program_args = -u;${mailDir}/crm114;/usr/share/crm114/mailfilter.crm;--stats_only;--force
368 #antispam_pipe_program_notspam_arg = --learnnonspam
369 #antispam_pipe_program_spam_arg = --learnspam
370 #antispam_pipe_program_unlearn_spam_args = --unlearn;--learnspam
371 #antispam_pipe_program_unlearn_notspam_args = --unlearn;--learnnonspam
372 #antispam_pipe_tmpdir = ${mailDir}/crm114/tmp
373 #antispam_signature = X-CRM114-CacheID
374 #antispam_signature_missing = move
375 #antispam_spam = Junk
376 #antispam_spam_keywords = Junk
377 #antispam_trash = Trash
378 #antispam_unsure = Unsure
379 #antispam_verbose_debug = 0
380 quota = maildir:User quota
381 quota_rule = *:storage=256M
382 quota_rule2 = Trash:storage=+64M
383 recipient_delimiter = ${extSep}
384 sieve = file:${mailDir}/%d/%n/sieve;active=${mailDir}/%d/%n/sieve/main.sieve
385 #sieve_default = file:${mailDir}/%u/default.sieve
386 #sieve_default_name = default
387 sieve_after = ${sieveDir}/after.d/
388 sieve_before = ${sieveDir}/before.d/
389 sieve_dir = ${mailDir}/%d/%n/sieve/
390 #sieve_extensions = +spamtest +spamtestplus
391 sieve_global_dir = ${sieveDir}/global.d/
392 sieve_max_script_size = 1M
393 sieve_quota_max_scripts = 0
394 sieve_quota_max_storage = 10M
395 sieve_spamtest_max_value = 10
396 sieve_spamtest_status_header = X-Spam-Score
397 sieve_spamtest_status_type = strlen
398 sieve_user_log = /var/log/dovecot/%d/sieve.%n.log
399 }
400 protocol imap {
401 #mail_max_userip_connections = 10
402 mail_plugins = $mail_plugins imap_acl imap_quota # antispam
403 namespace inbox {
404 inbox = yes
405 location =
406 list = yes
407 mailbox Drafts {
408 special_use = \Drafts
409 }
410 mailbox Junk {
411 special_use = \Junk
412 }
413 mailbox Sent {
414 special_use = \Sent
415 }
416 mailbox "Sent Messages" {
417 special_use = \Sent
418 }
419 mailbox Trash {
420 special_use = \Trash
421 }
422 prefix =
423 separator = ${dirSep}
424 }
425 }
426 protocol lda {
427 auth_socket_path = /var/run/dovecot/auth-userdb
428 hostname = ${config.networking.domain}
429 info_log_path =
430 log_path =
431 mail_plugins = $mail_plugins sieve
432 namespace inbox {
433 inbox = yes
434 location =
435 list = yes
436 prefix =
437 separator = ${dirSep}
438 }
439 postmaster_address = postmaster${extSep}dovecot${extSep}lda@${config.networking.domain}
440 syslog_facility = mail
441 }
442 protocol lmtp {
443 #info_log_path = /tmp/dovecot-lmtp.log
444 mail_plugins = $mail_plugins sieve
445 namespace inbox {
446 inbox = yes
447 location =
448 list = yes
449 prefix =
450 separator = ${dirSep}
451 }
452 postmaster_address = postmaster${extSep}dovecot${extSep}lmtp@${config.networking.domain}
453 }
454 protocol pop3 {
455 #mail_max_userip_connections = 10
456 # Used by ${libDir}/pop3/INBOX/dovecot-virtual
457 namespace all {
458 hidden = yes
459 list = no
460 location =
461 prefix = all+
462 separator = ${dirSep}
463 }
464 # Virtual namespace for the virtual INBOX.
465 # Use a global directory for dovecot-virtual files.
466 namespace inbox {
467 inbox = yes
468 hidden = yes
469 list = no
470 location = virtual:${libDir}/pop3:INDEX=${libDir}/index/%d/%n/POP3:LAYOUT=fs
471 prefix = pop3+
472 separator = ${dirSep}
473 }
474 pop3_client_workarounds =
475 pop3_fast_size_lookups = yes
476 pop3_lock_session = yes
477 pop3_no_flag_updates = yes
478 # Use GUIDs to avoid accidental POP3 UIDL changes instead of IMAP UIDs.
479 pop3_uidl_format = %g
480 }
481 protocol sieve {
482 #mail_max_userip_connections = 10
483 #managesieve_implementation_string = Dovecot Pigeonhole
484 managesieve_max_compile_errors = 5
485 #managesieve_max_line_length = 65536
486 #managesieve_notify_capability = mailto
487 #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
488 }
489 protocols = imap lmtp pop3 sieve
490 service lmtp {
491 #executable = lmtp -L
492 process_min_avail = 2
493 unix_listener /var/lib/postfix/queue/private/dovecot-lmtp {
494 user = ${postfix.user}
495 group = ${postfix.group}
496 mode = 0600
497 }
498 #user = mail
499 }
500 service auth {
501 user = root
502 unix_listener auth-userdb {
503 user = ${dovecot2.user}
504 group = ${dovecot2.group}
505 mode = 0660
506 }
507 unix_listener /var/lib/postfix/queue/private/auth {
508 user = ${postfix.user}
509 group = ${postfix.group}
510 mode = 0660
511 }
512 }
513 service imap {
514 # Most of the memory goes to mmap()ing files.
515 # You may need to increase this limit if you have huge mailboxes.
516 #vsz_limit =
517 process_limit = 1024
518 }
519 service imap-login {
520 #inet_listener imap {
521 # address = 127.0.0.1
522 # port = 143
523 # ssl = no
524 # }
525 inet_listener imaps {
526 port = 993
527 ssl = yes
528 }
529 }
530 service pop3 {
531 process_limit = 1024
532 }
533 service pop3-login {
534 inet_listener pop3s {
535 port = 995
536 ssl = yes
537 }
538 }
539 ssl = required
540 #ssl_ca = <''${caPath}
541 ssl_cert = <${x509.cert}
542 ssl_dh = <${x509.dir}/dh.pem
543 # gOTE: only with dovecot >= 2.3
544 ssl_cipher_list = ALL:!LOW:!SSLv2:!EXP:!aNULL
545 ssl_key = <${x509.key}
546 #ssl_verify_client_cert = yes
547 '');
548 };
549 };
550 }