-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathserver.go
More file actions
101 lines (81 loc) · 2.14 KB
/
server.go
File metadata and controls
101 lines (81 loc) · 2.14 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
package main
import (
"bytes"
"fmt"
"github.com/chrj/smtpd"
"net/http"
)
type Server struct {
*smtpd.Server
hooks Hooks
}
func NewServer(srv *smtpd.Server, hooks Hooks) *Server {
s := &Server{srv, hooks}
s.Server.Handler = s.ServeSMTP
s.Server.RecipientChecker = s.CheckRecipient
return s
}
func (s *Server) CheckRecipient(_ smtpd.Peer, addr string) error {
if _, ok := s.hooks.Find(addr); ok {
return nil
}
fmt.Println("denied unknown recipient address:", addr)
return smtpd.Error{
Code: 550,
Message: "address rejected: user unknown in local recipient table",
}
}
func (s *Server) ServeSMTP(_ smtpd.Peer, env smtpd.Envelope) error {
msg, err := NewMessage(bytes.NewBuffer(env.Data))
if err != nil {
fmt.Println("could not parse mail:", err)
return smtpd.Error{
Code: 554,
Message: "mail rejected: invalid format",
}
}
for _, addr := range env.Recipients {
hook, ok := s.hooks.Find(addr)
if !ok {
fmt.Println("could not find hook for address:", addr)
return smtpd.Error{
Code: 451,
Message: "internal server error",
}
}
buf := bytes.NewBuffer(nil)
enc := NewMultipartEncoder(buf)
if err := enc.Encode("mail", NewMail(env.Sender, addr, msg)); err != nil {
fmt.Println("could not encode request body:", err)
return smtpd.Error{
Code: 451,
Message: "internal server error",
}
}
enc.Close()
resp, err := http.Post(hook.Hook, enc.FormDataContentType(), buf)
if err != nil {
fmt.Println("could not dispatch message:", err)
return smtpd.Error{
Code: 451,
Message: "unable to reach destination system",
}
}
if 400 <= resp.StatusCode && resp.StatusCode <= 499 {
fmt.Println("could not dispatch message: server responded with:", resp.Status)
return smtpd.Error{
Code: 554,
Message: "destination system does not accept message",
}
}
if resp.StatusCode < 200 || 299 < resp.StatusCode {
fmt.Println("could not dispatch message: server responded with:", resp.Status)
return smtpd.Error{
Code: 451,
Message: "internal server error",
}
}
fmt.Println("relayed mail for", addr, "to", hook.Hook)
}
return nil
}