| 1 |
package smtp |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
"net/smtp" |
| 6 |
"os" |
| 7 |
"strings" |
| 8 |
|
| 9 |
"github.com/nicholas-fedor/shoutrrr/internal/failures" |
| 10 |
) |
| 11 |
|
| 12 |
// session is one SMTP conversation after a client has been dialed. |
| 13 |
type session struct { |
| 14 |
// client is the connected SMTP client for this conversation. |
| 15 |
client *smtp.Client |
| 16 |
// config is the send-time configuration clone. |
| 17 |
config *Config |
| 18 |
// svc provides logging and message templates. |
| 19 |
svc *Service |
| 20 |
// closed is true after the connection has been closed by Quit or Close. |
| 21 |
closed bool |
| 22 |
} |
| 23 |
|
| 24 |
const ( |
| 25 |
// shortResponseErrorSubstring matches textproto short-response errors sometimes seen on QUIT. |
| 26 |
shortResponseErrorSubstring = "short response" |
| 27 |
) |
| 28 |
|
| 29 |
// auth authenticates the SMTP client using the configured mechanism. |
| 30 |
// |
| 31 |
// Returns: |
| 32 |
// - An error if authentication cannot be configured or the server rejects it. |
| 33 |
func (s *session) auth() error { |
| 34 |
mechanism, err := newAuth(s.config) |
| 35 |
if err != nil { |
| 36 |
return err |
| 37 |
} |
| 38 |
|
| 39 |
if mechanism != nil { |
| 40 |
if err := s.client.Auth(mechanism); err != nil { |
| 41 |
return fail(FailAuthenticating, err) |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
return nil |
| 46 |
} |
| 47 |
|
| 48 |
// closeClient closes the SMTP client and logs a warning if Close fails. |
| 49 |
func (s *session) closeClient() { |
| 50 |
if closeErr := s.client.Close(); closeErr != nil { |
| 51 |
s.svc.Logf("Warning: Failed to close SMTP client connection: %v", closeErr) |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
// closeIfOpen closes the client when [session.quit] has not already done so. |
| 56 |
func (s *session) closeIfOpen() { |
| 57 |
if s.closed { |
| 58 |
return |
| 59 |
} |
| 60 |
|
| 61 |
s.closeClient() |
| 62 |
s.closed = true |
| 63 |
} |
| 64 |
|
| 65 |
// deliver sends the message to each configured recipient. |
| 66 |
// |
| 67 |
// The SMTP session is reset between recipients. A failed reset stops remaining |
| 68 |
// deliveries. |
| 69 |
// |
| 70 |
// Parameters: |
| 71 |
// - message: The notification body. |
| 72 |
// - boundary: Multipart boundary used when HTML mail is enabled. |
| 73 |
// |
| 74 |
// Returns: |
| 75 |
// - Failures encountered while sending to recipients or resetting the session. |
| 76 |
func (s *session) deliver(message, boundary string) []error { |
| 77 |
var errs []error |
| 78 |
|
| 79 |
for i, toAddress := range s.config.ToAddresses { |
| 80 |
if err := s.sendMessage(toAddress, message, boundary); err != nil { |
| 81 |
errs = append(errs, fail(FailSendRecipient, err, toAddress)) |
| 82 |
s.svc.Logf("Failed to send to %q: %v", toAddress, err) |
| 83 |
} else { |
| 84 |
s.svc.Logf("Mail successfully sent to %q!", toAddress) |
| 85 |
} |
| 86 |
|
| 87 |
if i < len(s.config.ToAddresses)-1 { |
| 88 |
if err := s.client.Reset(); err != nil { |
| 89 |
errs = append(errs, fail(FailResetSession, err)) |
| 90 |
|
| 91 |
break |
| 92 |
} |
| 93 |
} |
| 94 |
} |
| 95 |
|
| 96 |
return errs |
| 97 |
} |
| 98 |
|
| 99 |
// ehloName returns the hostname sent in the SMTP EHLO/HELO command. |
| 100 |
// |
| 101 |
// When [Config.ClientHost] is "auto", the local hostname is used, falling back to |
| 102 |
// localhost if it cannot be determined. |
| 103 |
func (s *session) ehloName() string { |
| 104 |
if s.config.ClientHost != "auto" { |
| 105 |
return s.config.ClientHost |
| 106 |
} |
| 107 |
|
| 108 |
hostname, err := os.Hostname() |
| 109 |
if err != nil { |
| 110 |
s.svc.Logf("Failed to get hostname, falling back to localhost: %v", err) |
| 111 |
|
| 112 |
return "localhost" |
| 113 |
} |
| 114 |
|
| 115 |
return hostname |
| 116 |
} |
| 117 |
|
| 118 |
// quit ends the SMTP session with QUIT. |
| 119 |
// |
| 120 |
// A successful [smtp.Client.Quit] already closes the connection, so Close is |
| 121 |
// not called again. When QUIT fails, the client is closed explicitly. |
| 122 |
// Errors matching [shortResponseErrorSubstring] are logged and ignored because |
| 123 |
// they do not affect delivery. Other QUIT errors are appended to errs. |
| 124 |
// |
| 125 |
// Parameters: |
| 126 |
// - errs: Accumulated delivery errors to extend if QUIT fails. |
| 127 |
// |
| 128 |
// Returns: |
| 129 |
// - The original error slice, possibly with a session-closure failure appended. |
| 130 |
func (s *session) quit(errs []error) []error { |
| 131 |
err := s.client.Quit() |
| 132 |
if err == nil { |
| 133 |
s.closed = true |
| 134 |
|
| 135 |
return errs |
| 136 |
} |
| 137 |
|
| 138 |
if strings.Contains(err.Error(), shortResponseErrorSubstring) { |
| 139 |
s.svc.Logf("Warning: Ignoring session closure error (delivery succeeded): %v", err) |
| 140 |
} else { |
| 141 |
errs = append(errs, fail(FailClosingSession, err)) |
| 142 |
} |
| 143 |
|
| 144 |
s.closeClient() |
| 145 |
s.closed = true |
| 146 |
|
| 147 |
return errs |
| 148 |
} |
| 149 |
|
| 150 |
// run conducts the SMTP session: handshake, optional STARTTLS, authentication, |
| 151 |
// delivery, and QUIT. Pre-delivery failures close the client without sending QUIT. |
| 152 |
// An empty recipient list fails before the handshake. |
| 153 |
// |
| 154 |
// Parameters: |
| 155 |
// - message: The notification body. |
| 156 |
// |
| 157 |
// Returns: |
| 158 |
// - An error if there are no recipients, or if handshake, STARTTLS, authentication, or delivery fails. |
| 159 |
func (s *session) run(message string) error { |
| 160 |
s.config.restorePlusAddresses() |
| 161 |
|
| 162 |
defer s.closeIfOpen() |
| 163 |
|
| 164 |
if len(s.config.ToAddresses) == 0 { |
| 165 |
return fail(FailSendRecipient, ErrToAddressMissing, "") |
| 166 |
} |
| 167 |
|
| 168 |
if err := s.client.Hello(s.ehloName()); err != nil { |
| 169 |
return fail(FailHandshake, err) |
| 170 |
} |
| 171 |
|
| 172 |
var boundary string |
| 173 |
|
| 174 |
if s.config.UseHTML { |
| 175 |
generated, err := generateBoundary() |
| 176 |
if err != nil { |
| 177 |
return fail(FailUnknown, err) |
| 178 |
} |
| 179 |
|
| 180 |
boundary = generated |
| 181 |
} |
| 182 |
|
| 183 |
if err := s.startTLS(); err != nil { |
| 184 |
return err |
| 185 |
} |
| 186 |
|
| 187 |
if err := s.auth(); err != nil { |
| 188 |
return err |
| 189 |
} |
| 190 |
|
| 191 |
errs := s.deliver(message, boundary) |
| 192 |
errs = s.quit(errs) |
| 193 |
|
| 194 |
if len(errs) > 0 { |
| 195 |
return failures.Wrap( |
| 196 |
"failed to send to some recipients", |
| 197 |
FailSendRecipient, |
| 198 |
errors.Join(errs...), |
| 199 |
) |
| 200 |
} |
| 201 |
|
| 202 |
return nil |
| 203 |
} |
| 204 |
|
| 205 |
// sendMessage sends an email to a single recipient using MAIL, RCPT, and DATA. |
| 206 |
// |
| 207 |
// Sender and recipient addresses that contain CR or LF are rejected before any |
| 208 |
// SMTP command is issued. |
| 209 |
// |
| 210 |
// Parameters: |
| 211 |
// - toAddress: The recipient address. |
| 212 |
// - message: The notification body. |
| 213 |
// - boundary: Multipart boundary used when HTML mail is enabled. |
| 214 |
// |
| 215 |
// Returns: |
| 216 |
// - An error if an address is unsafe or any SMTP command or message write fails. |
| 217 |
func (s *session) sendMessage(toAddress, message, boundary string) error { |
| 218 |
if strings.ContainsAny(s.config.FromAddress, "\r\n") { |
| 219 |
return fail(FailSetSender, errHeaderBreak) |
| 220 |
} |
| 221 |
|
| 222 |
if strings.ContainsAny(toAddress, "\r\n") { |
| 223 |
return fail(FailSetRecipient, errHeaderBreak) |
| 224 |
} |
| 225 |
|
| 226 |
if err := s.client.Mail(s.config.FromAddress); err != nil { |
| 227 |
return fail(FailSetSender, err) |
| 228 |
} |
| 229 |
|
| 230 |
if err := s.client.Rcpt(toAddress); err != nil { |
| 231 |
return fail(FailSetRecipient, err) |
| 232 |
} |
| 233 |
|
| 234 |
writeCloser, err := s.client.Data() |
| 235 |
if err != nil { |
| 236 |
return fail(FailOpenDataStream, err) |
| 237 |
} |
| 238 |
|
| 239 |
if err := writeHeaders(writeCloser, headers(s.config, toAddress, boundary)); err != nil { |
| 240 |
return err |
| 241 |
} |
| 242 |
|
| 243 |
var writeErr error |
| 244 |
if s.config.UseHTML { |
| 245 |
writeErr = writeAlternative(writeCloser, message, boundary, s.svc) |
| 246 |
} else { |
| 247 |
writeErr = writePart(writeCloser, message, templatePlain, s.svc) |
| 248 |
} |
| 249 |
|
| 250 |
if writeErr != nil { |
| 251 |
return writeErr |
| 252 |
} |
| 253 |
|
| 254 |
if err = writeCloser.Close(); err != nil { |
| 255 |
return fail(FailCloseDataStream, err) |
| 256 |
} |
| 257 |
|
| 258 |
return nil |
| 259 |
} |
| 260 |
|
| 261 |
// startTLS upgrades the connection with STARTTLS when configured. |
| 262 |
// |
| 263 |
// Implicit TLS sessions skip this step. If STARTTLS is unsupported and |
| 264 |
// [Config.RequireStartTLS] is false, a warning is logged and the session continues |
| 265 |
// unencrypted. |
| 266 |
// |
| 267 |
// Returns: |
| 268 |
// - An error if STARTTLS is required but unsupported or the upgrade fails. |
| 269 |
func (s *session) startTLS() error { |
| 270 |
if !s.config.UseStartTLS || useImplicitTLS(s.config.Encryption, s.config.Port) { |
| 271 |
return nil |
| 272 |
} |
| 273 |
|
| 274 |
if supported, _ := s.client.Extension("StartTLS"); !supported { |
| 275 |
if s.config.RequireStartTLS { |
| 276 |
return fail(FailEnableStartTLS, ErrServerNoStartTLS) |
| 277 |
} |
| 278 |
|
| 279 |
s.svc.Logf( |
| 280 |
"Warning: StartTLS enabled, but server does not support it. Connection is unencrypted", |
| 281 |
) |
| 282 |
|
| 283 |
return nil |
| 284 |
} |
| 285 |
|
| 286 |
if err := s.client.StartTLS(newTLSConfig(s.config)); err != nil { |
| 287 |
return fail(FailEnableStartTLS, err) |
| 288 |
} |
| 289 |
|
| 290 |
return nil |
| 291 |
} |