Repository navigation
Expand file tree
/
Copy pathrun
More file actions
executable file
·633 lines (569 loc) · 27.4 KB
/
Copy pathrun
File metadata and controls
executable file
·633 lines (569 loc) · 27.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
#!/bin/bash
# Every daemon this configuration needs, filled in as each one is started and
# watched by the supervision loop at the end. Kept here rather than derived
# from the environment a second time: what was started is what has to stay up.
supervised=""
# "service ... start" returns as soon as start-stop-daemon has forked and
# saslauthd daemonises itself, so a daemon that dies on its configuration does
# so after a successful start. Wait for it to be there, rather than relaying
# mail without the signing or the rewriting the container was asked for.
awaitProcess()
{
local process="$1" try
for try in 1 2 3 4 5 ; do
if pgrep -x "$process" > /dev/null ; then
supervised="$supervised $process"
return 0
fi
sleep 0.2
done
return 1
}
# The first smtpd port master.cf serves on every interface, which is the one
# the image exposes. A service bound to a single address is left alone: it may
# be there for something that does not answer this container.
smtpdPort()
{
local service port
# $8 is master.cf's command column. The last field is not it: an entry
# carries its "-o" options after the command, which is what
# POSTFIXMASTER_ variables are for, and reading $NF there matches nothing.
service=$(postconf -M | awk '$2 == "inet" && $8 == "smtpd" && $1 !~ /:/ { print $1 ; exit }')
[ -n "$service" ] || return 1
port=$(getent services "$service" | awk '{ sub("/.*", "", $2) ; print $2 }')
echo "${port:-$service}"
}
# The address to greet on. Loopback answers unless inet_interfaces was
# narrowed to addresses that do not include it, in which case the first one it
# names does: a relay is free to serve only the address its clients reach it
# on, and greeting loopback there would refuse to start a relay that works.
# Read with "-x" so that main.cf macros are expanded: "inet_interfaces =
# $myhostname" is an ordinary way to write this, and "-h" alone hands back the
# literal "$myhostname" to dial.
smtpdAddress()
{
local interfaces entry first
interfaces=$(postconf -hx inet_interfaces)
for entry in ${interfaces//,/ } ; do
case "$entry" in
all|loopback-only|127.0.0.1|localhost) echo 127.0.0.1 ; return ;;
esac
[ -n "$first" ] || first="$entry"
done
echo "${first:-127.0.0.1}"
}
# Whether an smtpd survives long enough to greet a client.
awaitGreeting()
{
local address="$1" port="$2" try greeting
for try in 1 2 3 4 5 ; do
# The connection is opened inside a subshell, and the redirection that
# silences a refused one is on a group *inside* the substitution. Not on
# "exec": "exec ... 2> /dev/null" has no command to apply to, so it would
# send this script's own stderr to /dev/null for the rest of the
# container's life, taking every message below with it. And not on the
# substitution, which is what "greeting=$( ... ) 2> /dev/null" reads as
# and is not -- bash applies that to the assignment, which writes
# nothing, so it silences nothing.
greeting=$(
{
exec 3<>"/dev/tcp/$address/$port" || exit
# Short: master accepts at once when an smtpd can run, and holds
# the connection open with nothing behind it when one cannot -- it
# keeps the socket while it throttles the service it could not
# start. Five tries of this is the whole cost of refusing a broken
# relay.
read -t 2 -r line <&3
# QUIT rather than dropping the connection, so the one line this
# leaves in the log is a disconnect and not a lost connection.
printf 'QUIT\r\n' >&3
echo "$line"
} 2> /dev/null
)
case "$greeting" in 220*) return 0 ;; esac
sleep 0.2
done
return 1
}
startService()
{
local name="$1" process="$2"
service "$name" start
awaitProcess "$process" && return
echo "$name did not start, refusing to relay without it." >&2
exit 1
}
# <name>_FILE env -> read <name> from the file it points at
#
# Relaying usually means holding a credential for the upstream server, and the
# environment is a poor place to keep one: it shows up in "docker inspect", in
# the compose file and in /proc for every process in the container. Reading the
# value from a file instead allows using docker secrets or a mounted file.
secretsFromFiles()
{
local file var
for file in ${!POSTFIX_*} ${!POSTFIXMASTER_*} ${!POSTMAP_*} ${!OPENDKIM_*} ${!POSTSRSD_*} ; do
if [[ "$file" != *_FILE ]] ; then
continue
fi
var="${file%_FILE}"
# The image ships defaults for several of these variables, POSTFIX_myhostname
# and the OPENDKIM_ ones among them, so finding one already set is normal
# rather than a mistake. The file is what was asked for last, and wins.
if [ -n "${!var+set}" ] ; then
echo "$var is also set: using the value from $file."
fi
if [ ! -r "${!file}" ] ; then
echo "$file points at '${!file}', which cannot be read." >&2
exit 1
fi
# "test -r" is true of a directory, and "$(< some/dir)" is the empty
# string with a status of 0 and nothing on stderr. So a path naming the
# secrets directory rather than the secret inside it -- the likeliest way
# to get this wrong -- would pass the check above and resolve to nothing.
if [ ! -f "${!file}" ] ; then
echo "$file points at '${!file}', which is not a file." >&2
exit 1
fi
# $(< file) drops trailing newlines, which a secret file is likely to
# end with and a password is unlikely to contain.
printf -v "$var" '%s' "$(< "${!file}")"
# The same failure arriving by the last door left open: a file that is
# there, readable and empty. Nothing downstream would object -- an empty
# value is how a POSTFIX_ variable clears a Dockerfile default on purpose
# -- so the relay would come up healthy with the credential, domain or
# key it was told to read set to nothing. Clearing a default deliberately
# is what the plain variable is for and is untouched by this.
if [ -z "${!var}" ] ; then
echo "$file points at '${!file}', which is empty." >&2
exit 1
fi
export "${var?}"
# Unset so that the loops below don't also configure "<name>_FILE".
unset "$file"
done
}
# DKIM config
dkimConfig()
{
if [ -z "$POSTFIX_milter_default_action" ] ; then
postconf -e milter_default_action=accept
fi
if [ -z "$POSTFIX_smtpd_milters" ] ; then
postconf -e smtpd_milters=inet:localhost:12301
fi
rm -f /etc/opendkim/KeyTable
rm -f /etc/opendkim/SigningTable
# opendkim walks the whole path down to a key and refuses one that any
# other user could read or write, naming the directory it stopped at
# rather than the key. /etc/opendkim/keys is where a volume gets mounted,
# so its mode is whatever the volume driver left behind and not something
# the image ever set: secure it here, along with the per-domain
# directories below, or opendkim declines to sign with a key whose own
# permissions are perfectly fine.
chown opendkim:opendkim /etc/opendkim/keys
chmod a=,u=rwx /etc/opendkim/keys
echo "DNS records:"
for d in $OPENDKIM_DOMAINS ; do
# A comma is an ordinary character in a domain name to this parsing,
# which splits OPENDKIM_DOMAINS on whitespace and nothing else. Every
# other comma-separated variable this image reads -- POSTFIX_mynetworks,
# POSTSRSD_SRS_EXCLUDE_DOMAINS -- makes a comma here a plausible typo
# rather than a plausible domain, and the loop below has no way to tell
# the two apart: it would generate a key, print a record nobody can
# publish, and write a signing rule no sender matches, all while opendkim
# starts and the health check calls the relay healthy. Refusing it here
# is the same choice run already makes for a daemon that did not start,
# a POSTSRSD_SRS_DOMAIN this build cannot honour, or a secret it cannot
# read: loud now, rather than a relay that signs nothing and says
# nothing about it.
if [[ "$d" == *,* ]] ; then
echo "OPENDKIM_DOMAINS entry '$d' contains a comma, which" \
"OPENDKIM_DOMAINS does not use as a separator -- it is" \
"whitespace-separated. Refusing to relay with a domain list" \
"that would silently sign for the wrong name." >&2
exit 1
fi
domain=$(echo "$d"| cut -f1 -d '=')
selector=$(expr match "$d" '.*\=\(.*\)')
if [ -z "$selector" ] ; then
selector="mail"
fi
domainDir="/etc/opendkim/keys/$domain"
privateFile="$domainDir/$selector.private"
txtFile="$domainDir/$selector.txt"
if [ ! -f "$privateFile" ] ; then
echo "No DKIM private key found for selector '$selector' in domain '$domain'. Generating one now..."
# A key that could not be written is worse than no DKIM at all: the
# tables below would name it, opendkim would start without being able
# to load it, and the milter would answer every message with a
# tempfail -- a relay that accepts nothing while it reports healthy.
if ! mkdir -p "$domainDir" \
|| ! opendkim-genkey -D "$domainDir" --selector="$selector" \
--domain="$domain" --append-domain \
|| [ ! -f "$privateFile" ] ; then
echo "Could not generate a DKIM key for selector '$selector' in" \
"domain '$domain': /etc/opendkim/keys has to be writable, or" \
"hold the keys already. Refusing to relay without the signing" \
"that was asked for." >&2
exit 1
fi
fi
# A key that is there but cannot be read is the same failure arriving by
# another door, and the guard above never sees it: a <selector>.private
# that is empty, truncated or restored from a backup that was taken
# mid-write skips the generation entirely because the file exists. Then
# the tables below name it, opendkim starts having loaded nothing, and
# every message goes out unsigned while the container reports healthy --
# the signing that was asked for silently not happening, which is the
# thing the refusal above exists to prevent.
#
# "openssl pkey" rather than "openssl rsa": opendkim also takes ed25519
# keys, and the generic form parses both. It only has to answer whether
# this is a private key at all, which is what opendkim will fail on.
if ! openssl pkey -in "$privateFile" -noout > /dev/null 2>&1 ; then
echo "The DKIM private key for selector '$selector' in domain" \
"'$domain' cannot be read as a private key: $privateFile." \
"Refusing to relay without the signing that was asked for." >&2
exit 1
fi
# Ensure strict permissions required by opendkim
chown opendkim:opendkim "$domainDir" "$privateFile"
chmod a=,u=rwx "$domainDir"
chmod a=,u=rw "$privateFile"
echo "$selector._domainkey.$domain $domain:$selector:$privateFile" >> /etc/opendkim/KeyTable
echo "*@$domain $selector._domainkey.$domain" >> /etc/opendkim/SigningTable
# opendkim-genkey writes the record beside the key, but only the key is
# needed to sign. So a keys volume restored from a backup that kept the
# .private and not the .txt comes up signing perfectly and answers "DNS
# records:" with a cat error -- at the one moment someone is looking for
# the record, which is when they have just restored the key. It is
# derivable from the key, so derive it rather than say nothing.
#
# Printed, not written back: the volume is the user's, and the record is
# not state this needs to keep.
if [ -f "$txtFile" ] ; then
cat "$txtFile"
else
# Only RSA. opendkim also takes ed25519, whose record carries the raw
# public key where this carries the SubjectPublicKeyInfo openssl
# prints, so one derivation does not serve both. The flags either side
# of "p=" are the ones opendkim-genkey writes in this image rather than
# anything read out of the key; tests/test_dkim.py pins that by
# comparing the two records.
publicKey=$(openssl rsa -in "$privateFile" -pubout -outform DER 2> /dev/null | base64 -w0)
if [ -n "$publicKey" ] ; then
printf '%s._domainkey.%s.\tIN\tTXT\t( "v=DKIM1; h=sha256; k=rsa; "\n' \
"$selector" "$domain"
printf '\t "p=%s" ) ; ----- DKIM key %s for %s, rebuilt from the private key\n' \
"$publicKey" "$selector" "$domain"
else
echo "There is no $txtFile beside the key and the record cannot be" \
"rebuilt from it, which only works for an RSA key. Signing is" \
"unaffected; what is missing is the record to publish." >&2
fi
fi
done
}
# SRS config
srsMarker="# Generated by postfix-relay from POSTSRSD_ environment variables"
srsConfig()
{
if [ ! -s /etc/postsrsd.secret ] ; then
echo "No SRS secret found. Generating one now..."
echo "Mount /etc/postsrsd.secret to keep SRS return addresses valid across container recreations."
head -c 24 /dev/urandom | base64 > /etc/postsrsd.secret
fi
chmod a=,u=rw /etc/postsrsd.secret
# POSTSRSD_var env -> put "var='value'" line in /etc/default/postsrsd.
# The file is sourced by the init script, so appending overrides the
# packaged defaults. The block is regenerated to stay idempotent when a
# container is restarted.
#
# The value is single quoted because that init script is /bin/sh with
# "set -e": unquoted, a value with a space in it is read as an assignment
# followed by a command, and the command not being found takes the init
# script down with it (issue #177). Embedded single quotes are closed,
# escaped and reopened, which is what the replacement below does. Only the
# assignment is quoted: the init script still splits the value into words
# when it builds the daemon arguments, so SRS_EXTRA_OPTIONS='-A -t60'
# still reaches postsrsd as two options.
sed -i "/$srsMarker/,\$d" /etc/default/postsrsd
echo "$srsMarker" >> /etc/default/postsrsd
for e in ${!POSTSRSD_*} ; do
printf "%s='%s'\n" "${e:9}" "${!e//\'/\'\\\'\'}" >> /etc/default/postsrsd
done
# Point postfix at postsrsd, unless the user configured the maps
# themselves. The sender side is envelope only, so the visible From is
# left alone -- rewriting it would change who the message says it is
# from.
#
# The recipient side names header_recipient as well, which buys less than
# it reads as: postfix rewrites headers only for clients matching
# local_header_rewrite_clients, and that defaults to this container's own
# addresses. Mail from the containers this relays for arrives over the
# docker network instead, so it keeps the SRS address in its To and only
# its envelope is decoded -- which is the half that makes a bounce
# deliverable, so the behaviour is right either way. Anything that is not
# an SRS address postsrsd returns unchanged, and it is left as it was.
if [ -z "$POSTFIX_sender_canonical_maps" ] ; then
postconf -e "sender_canonical_maps=tcp:127.0.0.1:${POSTSRSD_SRS_FORWARD_PORT:-10001}"
fi
if [ -z "$POSTFIX_sender_canonical_classes" ] ; then
postconf -e sender_canonical_classes=envelope_sender
fi
if [ -z "$POSTFIX_recipient_canonical_maps" ] ; then
postconf -e "recipient_canonical_maps=tcp:127.0.0.1:${POSTSRSD_SRS_REVERSE_PORT:-10002}"
fi
if [ -z "$POSTFIX_recipient_canonical_classes" ] ; then
postconf -e recipient_canonical_classes=envelope_recipient,header_recipient
fi
}
# Unclean container stop might leave pid files around and rsyslogd seems
# sometimes falsely think it's already running if some other process
# happens to have its old pid when starting.
rm -f \
/run/opendkim/opendkim.pid \
/run/postsrsd.pid \
/run/rsyslogd.pid \
/var/spool/postfix/pid/master.pid
# local(8) dot-locks a mailbox for the append (mailbox_delivery_lock defaults
# to "fcntl, dotlock"), and a container killed mid-delivery leaves that lock
# on disk with nothing left running to hold it. Postfix's own retries never
# clear it -- the lock is per mailbox, not per message, so every later
# delivery to that recipient fails with "unable to create lock file ... File
# exists" and stays deferred, for ever. This runs before postfix starts, so
# nothing can be holding one legitimately yet.
rm -f /var/mail/*.lock
# A queue mounted from a host directory hides /var/spool/postfix/dev, which
# ships in the image, empty, and is where rsyslog opens the log socket the
# chrooted postfix daemons write to. Nothing else recreates it: it has no entry
# in postfix-files, so "postfix check" does not, and Debian's chroot resync
# only fills etc/, lib/ and usr/lib/sasl2. Without it rsyslogd reports it
# cannot create the socket and everything that connects to syslog after
# chrooting is logged nowhere (issue #180).
mkdir -p /var/spool/postfix/dev
secretsFromFiles
# POSTMASTER_ADDRESS env -> route postfix's own notifications (notify_classes)
# to a mailbox someone reads. They are addressed to the unqualified
# "postmaster", which append_at_myorigin turns into postmaster@$myorigin, the
# relay's own name. A relay accepts no mail for itself, so the notices are
# deferred until they time out and are then dropped. Set before the POSTFIX_
# loop below so that an explicit POSTFIX_<class>_notice_recipient overrides it.
# notify_classes is left alone: setting bounce/2bounce/delay recipients is
# inert until someone widens it, it just means they are already correct then.
if [ ! -z "$POSTMASTER_ADDRESS" ] ; then
for c in error bounce 2bounce delay ; do
postconf -e "${c}_notice_recipient=$POSTMASTER_ADDRESS"
done
fi
# POSTFIX_var env -> postconf -e var=$POSTFIX_var
for e in ${!POSTFIX_*} ; do postconf -e "${e:8}=${!e}" ; done
# POSTFIXMASTER_var env -> postconf -Me var=$POSTFIXMASTER_var + replace __ with /
for e in ${!POSTFIXMASTER_*} ; do v="${e:14}" && postconf -Me "${v//__/\/}=${!e}"; done
# POSTMAP_var env value -> /etc/postfix/var
shopt -s nullglob
for e in ${!POSTMAP_*} ; do
f="/etc/postfix/${e:8}"
echo "${!e}" > "$f" && postmap "$f"
# A lookup table is a likely place for a password (smtp_sasl_password_maps),
# so keep the table and the database postmap generated from it readable by
# root only instead of by everyone in the container. Postfix opens its lookup
# tables in the pre-jail initialisation of each daemon, while that daemon is
# still root, so nothing has to read them once privileges are dropped -- the
# mode SASL_README asks for on this exact file.
chown root:root "$f" "$f".*
chmod a=,u=rw "$f" "$f".*
done
shopt -u nullglob
chown -R postfix:postfix /var/lib/postfix /var/spool/postfix
# OPENDKIM_var env -> put "key value" line in /etc/opendkim.conf
echo -n > /etc/opendkim.conf
for e in ${!OPENDKIM_*} ; do
if [ "$e" == "OPENDKIM_DOMAINS" ] ; then
continue
fi
echo "${e:9} ${!e}" >> /etc/opendkim.conf
done
# Stop everything this script started, on either way out: the container being
# stopped, or this script giving up on a daemon that is gone. rsyslogd is
# signalled last and waited for, so that what the others write on their way out
# still reaches the container log.
stopDaemons()
{
[ -n "$stopped" ] && return
stopped=1
# postfix stops through its own script, which finds master by pid file.
# The other two init scripts cannot find anything: both identify the
# process with start-stop-daemon's --exec, which resolves /proc/<pid>/exe,
# and reading that link across a uid boundary needs CAP_SYS_PTRACE, which
# docker does not grant. So opendkim's script says "none killed" and
# postsrsd's, which passes --oknodo, reports a success it did not have --
# neither daemon is signalled at all, and the log says otherwise.
#
# Signalling them directly reaches postsrsd everywhere: the process that
# holds its pid stays root, and only its chrooted worker drops privileges.
# opendkim drops its own, so this reaches it under docker's default
# capabilities and not under the smaller set the README recommends, which
# leaves out CAP_KILL. Nothing can there -- see invariant 9 -- and what it
# then does is what the init script already left it doing: waiting for
# docker to kill the container. Both are silenced because both have a pid
# they may not signal there: postsrsd matches two, and the chrooted worker
# that dropped privileges is refused even though the root process holding
# it is signalled and takes the worker with it.
service postfix stop
pkill -x -TERM opendkim 2> /dev/null
pkill -x -TERM postsrsd 2> /dev/null
pkill -TERM saslauthd
pkill -TERM rsyslogd
wait "$rsyslogPid" 2> /dev/null
}
# Exits from the handler rather than only flagging the stop: during start-up
# the script would otherwise carry on from where the signal interrupted it and
# report the daemons it had just stopped as daemons that would not start.
trap 'stopping=1 ; stopDaemons ; exit 0' SIGTERM SIGINT
if [ ! -z "$OPENDKIM_DOMAINS" ] ; then
dkimConfig
startService opendkim opendkim
fi
if [ ! -z "$POSTSRSD_SRS_DOMAIN" ] ; then
if ! command -v postsrsd > /dev/null ; then
echo "POSTSRSD_SRS_DOMAIN is set but postsrsd is not part of this image: Debian does not build it for $(dpkg --print-architecture)." >&2
exit 1
fi
srsConfig
startService postsrsd postsrsd
fi
# Checking for user specified passwd file
if [ ! -z "$SASL_Passwds" ] ; then
# Creating auth settings file
#
# Only the mechanisms that hand saslauthd a password to check are offered:
# it verifies a password, and CRAM-MD5 and DIGEST-MD5 prove knowledge of one
# without sending it, which needs the secret this check never has. Offering
# them means a client that picks the strongest mechanism on the list -- what
# msmtp and others do -- fails against a relay that is configured correctly.
if [ ! -e /etc/postfix/sasl/smtpd.conf ] ; then
cat <<'EOF' > /etc/postfix/sasl/smtpd.conf
pwcheck_method: saslauthd
mech_list: LOGIN PLAIN
EOF
fi
# Giving postfix permission to use saslauthd
adduser postfix sasl
# Creating PAM authentication profile
if [ ! -e "/etc/pam.d/smtp" ] ; then
cat <<EOF > /etc/pam.d/smtp
auth required pam_pwdfile.so pwdfile=$SASL_Passwds
account required pam_permit.so
session required pam_permit.so
password required pam_deny.so
EOF
fi
# saslauthd makes its mux world writable itself, so the directory holding it
# is the access control: root:sasl 710 lets the sasl group in and nobody
# else. Postfix drops privileges with initgroups(), so a chrooted smtpd
# running as postfix carries the group added just above and can traverse the
# directory to reach the socket.
#
# Set here rather than through dpkg-statoverride, which only records what a
# future dpkg unpack should apply -- nothing a container ever runs -- so the
# mode never reached the directory at all and re-adding the override was an
# error on every restart (issue #179). This has to stay below the
# "chown -R postfix:postfix /var/spool/postfix" above, which would take the
# directory back.
install -d -o root -g sasl -m 710 /var/spool/postfix/var/run/saslauthd
saslauthd -c -r -a pam -m /var/spool/postfix/var/run/saslauthd &
awaitProcess saslauthd || {
echo "saslauthd did not start, refusing to relay without it." >&2
exit 1
}
fi
startService postfix master
# Don't fiddle with existing config file (e.g. mounted from filesystem)
if [ -e /etc/rsyslog.conf ]; then
echo "Skipping /etc/rsyslog.conf generating - file already exists"
else
# Rsyslog base
cat <<'EOF' > /etc/rsyslog.conf
$ModLoad imuxsock
$WorkDirectory /var/spool/rsyslog
include(file="/etc/rsyslog.d/*.conf")
EOF
# $ActionFileDefaultTemplate only applies to the actions written after it,
# so it has to come before the ones below.
if [ "${RSYSLOG_TIMESTAMP}" == 'no' ] ; then
echo '$template noTimestampFormat,"%syslogtag%%msg%\n"' >> /etc/rsyslog.conf
echo '$ActionFileDefaultTemplate noTimestampFormat' >> /etc/rsyslog.conf
fi
echo '*.*;auth,authpriv.none /dev/stdout' >> /etc/rsyslog.conf
if [ "${RSYSLOG_LOG_TO_FILE}" == 'yes' ] ; then
echo 'mail.* -/var/log/mail.log' >> /etc/rsyslog.conf
fi
if [ -z ${RSYSLOG_REMOTE_PORT} ] ; then
RSYSLOG_REMOTE_PORT=514
fi
if [ -z ${RSYSLOG_REMOTE_TEMPLATE} ] ; then
RSYSLOG_REMOTE_TEMPLATE=RSYSLOG_ForwardFormat
fi
if [ ! -z ${RSYSLOG_REMOTE_HOST} ] ; then
echo "*.* action(type=\"omfwd\" target=\"${RSYSLOG_REMOTE_HOST}\" port=\"${RSYSLOG_REMOTE_PORT}\" template=\"${RSYSLOG_REMOTE_TEMPLATE}\")" >> /etc/rsyslog.conf
fi
fi
rsyslogd -n &
rsyslogPid=$!
supervised="$supervised rsyslogd"
# A running master is not the same as a postfix that can serve. Master binds
# the port and forks an smtpd per connection, so a setting smtpd rejects when
# it reads it leaves a relay that listens, accepts, and then kills every
# session. Nothing else notices: "postconf -e" takes the value without a word,
# "postfix check" passes, the socket is in /proc and master is running, so the
# health check reports the container healthy while it relays nothing at all
# (issue #206).
#
# One greeting is what separates the two. It is done here rather than in the
# health check because it costs a connect in the log: once per container here,
# every interval there. After rsyslogd so that postfix's own reason -- the
# "fatal:" line naming the setting -- is in the container log above this.
smtpdPort=$(smtpdPort)
smtpdAddress=$(smtpdAddress)
if [ -n "$smtpdPort" ] && ! awaitGreeting "$smtpdAddress" "$smtpdPort" ; then
echo "No smtpd survived a connection on $smtpdAddress:$smtpdPort, which a setting postfix" \
"rejects when smtpd reads it will do; refusing to relay. The line above" \
"starting \"fatal:\" names it." >&2
stopDaemons
exit 1
fi
# rsyslogd is the only one of them that is a job of this script -- the other
# four daemonise, so their starter exits and they reparent to pid 1, which is
# this script, and bash has no job to wait on. The bare "wait" this replaces
# was therefore watching one daemon out of five and the container went on
# relaying when any of the other four died (issue #176). Polling
# "pgrep -x", the way the health check does, watches all of them and needs
# nothing beyond reading /proc -- signalling a daemon that dropped to its own
# user would need a capability the README asks deployments to drop.
while [ -z "$stopping" ] ; do
# The sleep runs in the background and is waited for: "wait" is interrupted
# by a trapped signal, while a foreground "sleep" would postpone the stop by
# a whole interval. "-n" returns on whichever finishes first, so rsyslogd --
# the one daemon that is still a job of this shell -- is noticed the moment
# it dies rather than at the end of the interval.
sleep 2 &
wait -n
[ -n "$stopping" ] && break
for daemon in $supervised ; do
pgrep -x "$daemon" > /dev/null && continue
# A daemon takes a moment to actually go away, and a relay that is fine is
# not worth stopping over a single missed reading.
sleep 1 &
wait $!
[ -n "$stopping" ] && break 2
pgrep -x "$daemon" > /dev/null && continue
# Exiting 0 would look like a clean stop and leave an on-failure restart
# policy with nothing to act on.
echo "A daemon exited on its own, stopping the relay: $daemon is gone." >&2
stopDaemons
exit 1
done
done
exit 0