245 lines
6.4 KiB
Go
245 lines
6.4 KiB
Go
package notify
|
|
|
|
import (
|
|
"bufio"
|
|
"context"
|
|
"crypto/tls"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"mime"
|
|
"net"
|
|
"net/mail"
|
|
"net/smtp"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"sea-vhost/internal/secrets"
|
|
"sea-vhost/internal/store"
|
|
)
|
|
|
|
type smtpConfig struct {
|
|
Host string `json:"host"`
|
|
Port int `json:"port"`
|
|
Username string `json:"username"`
|
|
Secret string `json:"secret"`
|
|
From string `json:"from"`
|
|
AdminRecipients string `json:"adminRecipients"`
|
|
StartTLS bool `json:"startTls"`
|
|
Enabled bool `json:"enabled"`
|
|
}
|
|
|
|
type Dispatcher struct {
|
|
store *store.Store
|
|
box *secrets.Box
|
|
}
|
|
|
|
func New(database *store.Store, secret string) *Dispatcher {
|
|
return &Dispatcher{store: database, box: secrets.New(secret)}
|
|
}
|
|
|
|
func (d *Dispatcher) Run(ctx context.Context, interval time.Duration) {
|
|
if interval <= 0 {
|
|
interval = time.Minute
|
|
}
|
|
d.dispatch(ctx)
|
|
ticker := time.NewTicker(interval)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
d.dispatch(ctx)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (d *Dispatcher) dispatch(ctx context.Context) {
|
|
cfg, err := d.config(ctx)
|
|
if err != nil || !cfg.Enabled {
|
|
return
|
|
}
|
|
items, err := d.store.PendingAdminNotifications(ctx, time.Now(), 25)
|
|
if err != nil {
|
|
return
|
|
}
|
|
for _, item := range items {
|
|
operation, cancel := context.WithTimeout(ctx, 30*time.Second)
|
|
err = send(operation, cfg, item)
|
|
cancel()
|
|
if err == nil {
|
|
_ = d.store.CompleteAdminNotification(context.WithoutCancel(ctx), item.ID)
|
|
continue
|
|
}
|
|
delay := time.Duration(1<<min(item.Attempts, 6)) * 5 * time.Minute
|
|
_ = d.store.FailAdminNotification(context.WithoutCancel(ctx), item.ID, err.Error(), time.Now().Add(delay))
|
|
}
|
|
}
|
|
|
|
func (d *Dispatcher) config(ctx context.Context) (smtpConfig, error) {
|
|
raw := d.store.Setting(ctx, "smtp_config", "{}")
|
|
var cfg smtpConfig
|
|
if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
|
|
return cfg, err
|
|
}
|
|
if cfg.Secret != "" {
|
|
ciphertext, err := base64.RawStdEncoding.DecodeString(cfg.Secret)
|
|
if err != nil {
|
|
return cfg, err
|
|
}
|
|
cfg.Secret, err = d.box.Open("system/smtp_config", ciphertext)
|
|
if err != nil {
|
|
return cfg, err
|
|
}
|
|
}
|
|
return cfg, validateConfig(cfg)
|
|
}
|
|
|
|
func validateConfig(cfg smtpConfig) error {
|
|
if !cfg.Enabled {
|
|
return nil
|
|
}
|
|
if net.ParseIP(cfg.Host) == nil && !validDNSName(cfg.Host) {
|
|
return errors.New("invalid SMTP host")
|
|
}
|
|
if cfg.Port < 1 || cfg.Port > 65535 {
|
|
return errors.New("invalid SMTP port")
|
|
}
|
|
from, err := mail.ParseAddress(cfg.From)
|
|
if err != nil || from.Address != cfg.From {
|
|
return errors.New("invalid SMTP sender")
|
|
}
|
|
if len(recipients(cfg.AdminRecipients)) == 0 {
|
|
return errors.New("SMTP recipients are empty")
|
|
}
|
|
if cfg.Username != "" && cfg.Secret == "" {
|
|
return errors.New("SMTP password is empty")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func send(ctx context.Context, cfg smtpConfig, item store.AdminNotification) error {
|
|
address := net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port))
|
|
dialer := &net.Dialer{Timeout: 10 * time.Second}
|
|
var connection net.Conn
|
|
var err error
|
|
implicitTLS := cfg.Port == 465
|
|
if implicitTLS {
|
|
connection, err = tls.DialWithDialer(dialer, "tcp", address, &tls.Config{MinVersion: tls.VersionTLS12, ServerName: cfg.Host})
|
|
} else {
|
|
connection, err = dialer.DialContext(ctx, "tcp", address)
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("connect SMTP: %w", err)
|
|
}
|
|
defer connection.Close()
|
|
_ = connection.SetDeadline(time.Now().Add(25 * time.Second))
|
|
client, err := smtp.NewClient(connection, cfg.Host)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer client.Close()
|
|
secure := implicitTLS
|
|
if !implicitTLS && cfg.StartTLS {
|
|
if ok, _ := client.Extension("STARTTLS"); !ok {
|
|
return errors.New("SMTP server does not support STARTTLS")
|
|
}
|
|
if err = client.StartTLS(&tls.Config{MinVersion: tls.VersionTLS12, ServerName: cfg.Host}); err != nil {
|
|
return err
|
|
}
|
|
secure = true
|
|
}
|
|
if cfg.Username != "" {
|
|
if !secure {
|
|
return errors.New("SMTP authentication requires TLS")
|
|
}
|
|
if err = client.Auth(smtp.PlainAuth("", cfg.Username, cfg.Secret, cfg.Host)); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if err = client.Mail(cfg.From); err != nil {
|
|
return err
|
|
}
|
|
to := recipients(cfg.AdminRecipients)
|
|
for _, recipient := range to {
|
|
if err = client.Rcpt(recipient); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
writer, err := client.Data()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
buffer := bufio.NewWriter(writer)
|
|
subject := "[Sea vHost][" + strings.ToUpper(item.Severity) + "] " + sanitizeHeader(item.Title)
|
|
headers := []string{
|
|
"From: " + cfg.From,
|
|
"To: " + strings.Join(to, ", "),
|
|
"Subject: " + mime.QEncoding.Encode("UTF-8", subject),
|
|
"Date: " + time.Now().Format(time.RFC1123Z),
|
|
"MIME-Version: 1.0",
|
|
"Content-Type: text/plain; charset=UTF-8",
|
|
"Content-Transfer-Encoding: base64",
|
|
"",
|
|
}
|
|
for _, header := range headers {
|
|
if _, err = buffer.WriteString(header + "\r\n"); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
body := fmt.Sprintf("类型:%s\n级别:%s\n时间:%s\n\n%s\n", item.Category, item.Severity, time.Now().Format(time.RFC3339), item.Detail)
|
|
encoded := base64.StdEncoding.EncodeToString([]byte(body))
|
|
for len(encoded) > 76 {
|
|
_, _ = buffer.WriteString(encoded[:76] + "\r\n")
|
|
encoded = encoded[76:]
|
|
}
|
|
_, _ = buffer.WriteString(encoded + "\r\n")
|
|
if err = buffer.Flush(); err != nil {
|
|
return err
|
|
}
|
|
if err = writer.Close(); err != nil {
|
|
return err
|
|
}
|
|
return client.Quit()
|
|
}
|
|
|
|
func recipients(value string) []string {
|
|
fields := strings.FieldsFunc(value, func(r rune) bool { return r == ',' || r == ';' || r == '\n' })
|
|
result := make([]string, 0, len(fields))
|
|
seen := map[string]bool{}
|
|
for _, field := range fields {
|
|
address := strings.TrimSpace(field)
|
|
parsed, err := mail.ParseAddress(address)
|
|
if err == nil && parsed.Address == address && !seen[strings.ToLower(address)] {
|
|
seen[strings.ToLower(address)] = true
|
|
result = append(result, address)
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
func sanitizeHeader(value string) string {
|
|
return strings.ReplaceAll(strings.ReplaceAll(value, "\r", " "), "\n", " ")
|
|
}
|
|
|
|
func validDNSName(value string) bool {
|
|
value = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(value), "."))
|
|
if value == "" || len(value) > 253 {
|
|
return false
|
|
}
|
|
for _, label := range strings.Split(value, ".") {
|
|
if label == "" || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {
|
|
return false
|
|
}
|
|
for _, character := range label {
|
|
if !(character >= 'a' && character <= 'z' || character >= '0' && character <= '9' || character == '-') {
|
|
return false
|
|
}
|
|
}
|
|
}
|
|
return true
|
|
}
|