ygggo/internal/smtpserver/session_local.go

79 lines
1.5 KiB
Go
Raw Normal View History

2021-07-07 18:15:07 +01:00
package smtpserver
import (
"bytes"
2021-07-09 00:26:43 +01:00
"encoding/hex"
2021-07-07 18:15:07 +01:00
"fmt"
"io"
"time"
"github.com/emersion/go-message"
"github.com/emersion/go-smtp"
2021-07-08 23:12:20 +01:00
"github.com/neilalexander/yggmail/internal/utils"
2021-07-07 18:15:07 +01:00
)
type SessionLocal struct {
backend *Backend
state *smtp.ConnectionState
from string
rcpt []string
}
func (s *SessionLocal) Mail(from string, opts smtp.MailOptions) error {
2021-07-09 19:54:15 +01:00
s.rcpt = s.rcpt[:0]
2021-07-09 00:08:26 +01:00
pk, err := utils.ParseAddress(from)
2021-07-07 18:15:07 +01:00
if err != nil {
return fmt.Errorf("parseAddress: %w", err)
}
2021-07-09 00:08:26 +01:00
if !pk.Equal(s.backend.Config.PublicKey) {
2021-07-07 18:15:07 +01:00
return fmt.Errorf("not allowed to send outgoing mail as %s", from)
}
s.from = from
return nil
}
func (s *SessionLocal) Rcpt(to string) error {
s.rcpt = append(s.rcpt, to)
return nil
}
func (s *SessionLocal) Data(r io.Reader) error {
m, err := message.Read(r)
if err != nil {
return fmt.Errorf("message.Read: %w", err)
}
m.Header.Add(
"Received", fmt.Sprintf("from %s by Yggmail %s; %s",
s.state.RemoteAddr.String(),
2021-07-09 00:26:43 +01:00
hex.EncodeToString(s.backend.Config.PublicKey),
2021-07-07 18:15:07 +01:00
time.Now().String(),
),
)
2021-07-09 23:43:09 +01:00
var b bytes.Buffer
if err := m.WriteTo(&b); err != nil {
return fmt.Errorf("m.WriteTo: %w", err)
2021-07-07 18:15:07 +01:00
}
2021-07-09 23:43:09 +01:00
if err := s.backend.Queues.QueueFor(s.from, s.rcpt, b.Bytes()); err != nil {
return fmt.Errorf("s.backend.Queues.QueueFor: %w", err)
}
s.backend.Log.Println("Queued mail for", s.rcpt)
2021-07-07 18:15:07 +01:00
return nil
}
2021-07-09 19:57:56 +01:00
func (s *SessionLocal) Reset() {
s.rcpt = s.rcpt[:0]
s.from = ""
}
2021-07-07 18:15:07 +01:00
func (s *SessionLocal) Logout() error {
return nil
}