-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathfcgi.go
226 lines (194 loc) · 6.35 KB
/
fcgi.go
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
package fcgi_processor
import (
"fmt"
"net/url"
"strings"
"github.com/flashmob/go-guerrilla/backends"
"github.com/flashmob/go-guerrilla/mail"
"github.com/flashmob/go-guerrilla/response"
"github.com/tomasen/fcgi_client"
"io/ioutil"
"strconv"
)
type fcgiConfig struct {
// full path to script for the save mail task
// eg. /home/user/scripts/save.php
ScriptFileNameNameSave string `json:"fcgi_script_filename_save"`
// full path to script for recipient validation
// eg /home/user/scripts/val_rcpt.php
ScriptFileNameNameValidate string `json:"fcgi_script_filename_validate"`
// "tcp" or "unix"
ConnectionType string `json:"fcgi_connection_type"`
// where to Dial, eg "/tmp/php-fpm.sock" for unix-socket or "127.0.0.1:9000" for tcp
ConnectionAddress string `json:"fcgi_connection_address"`
}
type FastCGIProcessor struct {
config *fcgiConfig
client *fcgiclient.FCGIClient
}
func newFastCGIProcessor(config *fcgiConfig) (*FastCGIProcessor, error) {
p := &FastCGIProcessor{}
p.config = config
err := p.connect()
if err != nil {
backends.Log().Debug("FastCgi error", err)
return p, err
}
return p, err
}
func (f *FastCGIProcessor) connect() (err error) {
backends.Log().Debug("connecting to fcgi:", f.config.ConnectionType, f.config.ConnectionAddress)
f.client, err = fcgiclient.Dial(f.config.ConnectionType, f.config.ConnectionAddress)
return err
}
// get sends a get query to script with q query values
func (f *FastCGIProcessor) get(script string, q url.Values) (result []byte, err error) {
if err := f.connect(); err != nil {
return result, err
}
defer f.client.Close()
env := make(map[string]string)
env["SCRIPT_FILENAME"] = script
env["SERVER_SOFTWARE"] = "Go-guerrilla fastcgi"
env["REMOTE_ADDR"] = "127.0.0.1"
env["QUERY_STRING"] = q.Encode()
env["SERVER_PROTOCOL"] = "HTTP/1.1"
resp, err := f.client.Get(env)
if err != nil {
backends.Log().Debug("FastCgi Get failed", err)
return result, err
}
result, err = ioutil.ReadAll(resp.Body)
if err != nil {
backends.Log().Debug("FastCgi read body failed", err)
return result, err
}
return result, nil
}
func (f *FastCGIProcessor) postSave(e *mail.Envelope) (result []byte, err error) {
if err := f.connect(); err != nil {
return result, err
}
defer f.client.Close()
env := make(map[string]string)
env["SCRIPT_FILENAME"] = f.config.ScriptFileNameNameSave
env["SERVER_SOFTWARE"] = "Go-guerrilla fastcgi"
env["REMOTE_ADDR"] = "127.0.0.1"
data := url.Values{}
for i := range e.RcptTo {
data.Set(fmt.Sprintf("rcpt_to_%d", i), e.RcptTo[i].String())
}
data.Set("remote_ip", e.RemoteIP)
data.Set("subject", e.Subject)
data.Set("tls_on", strconv.FormatBool(e.TLS))
data.Set("helo", e.Helo)
data.Set("mail_from", e.MailFrom.String())
data.Set("body", e.String())
resp, err := f.client.PostForm(env, data)
if err != nil {
return result, err
}
result, err = ioutil.ReadAll(resp.Body)
if err != nil {
backends.Log().Debug("FastCgi Read Body failed", err)
return result, err
}
return
/*
todo: figure out how we can call directly and use a reader for efficiency, PRs welcome. eg.
r := io.MultiReader(
bytes.NewReader([]byte("---------------------------974767299852498929531610575\r\n")),
// ..url encoded data here
// ..a boundary here
e.NewReader(),
/*
f.client.Post(env, "multipart/form-data; boundary=---------------------------974767299852498929531610575", e.NewReader(), e.Len())
*/
}
var Processor = func() backends.Decorator {
// The following initialization is run when the program first starts
// config will be populated by the initFunc
var (
p *FastCGIProcessor
)
// initFunc is an initializer function which is called when our processor gets created.
// It gets called for every worker
initializer := backends.InitializeWith(func(backendConfig backends.BackendConfig) error {
configType := backends.BaseConfig(&fcgiConfig{})
bcfg, err := backends.Svc.ExtractConfig(backendConfig, configType)
if err != nil {
return err
}
c := bcfg.(*fcgiConfig)
p, err = newFastCGIProcessor(c)
if err != nil {
return err
}
p.config = c
// test the settings
v := url.Values{}
v.Set("rcpt_to", "test@example.com")
backends.Log().Info("testing script:", p.config.ScriptFileNameNameValidate)
result, err := p.get(p.config.ScriptFileNameNameValidate, v)
if err != nil {
backends.Log().WithError(err).Error("could get fcgi to work")
return nil
} else {
backends.Log().Debug(result)
}
return nil
})
// register our initializer
backends.Svc.AddInitializer(initializer)
return func(c backends.Processor) backends.Processor {
// The function will be called on each email transaction.
// On success, it forwards to the next step in the processor call-stack,
// or returns with an error if failed
return backends.ProcessWith(func(e *mail.Envelope, task backends.SelectTask) (backends.Result, error) {
if task == backends.TaskValidateRcpt {
// Check the recipients for each RCPT command.
// This is called each time a recipient is added,
// validate only the _last_ recipient that was appended
if size := len(e.RcptTo); size > 0 {
v := url.Values{}
v.Set("rcpt_to", e.RcptTo[len(e.RcptTo)-1].String())
result, err := p.get(p.config.ScriptFileNameNameValidate, v)
if err != nil {
backends.Log().Debug("FastCgi error", err)
return backends.NewResult(
response.Canned.FailNoSenderDataCmd),
backends.StorageNotAvailable
}
if string(result[0:6]) == "PASSED" {
// validation passed
return c.Process(e, task)
} else {
// validation failed
backends.Log().Debug("FastCgi Read Body failed", err)
return backends.NewResult(
response.Canned.FailNoSenderDataCmd),
backends.StorageNotAvailable
}
return c.Process(e, task)
}
return c.Process(e, task)
} else if task == backends.TaskSaveMail {
for i := range e.RcptTo {
// POST to FCGI
resp, err := p.postSave(e)
if err != nil {
} else if strings.Index(string(resp), "SAVED") == 0 {
return c.Process(e, task)
} else {
backends.Log().WithError(err).Error("Could not save email")
return backends.NewResult(fmt.Sprintf("554 Error: could not save email for [%s]", e.RcptTo[i])), err
}
}
// continue to the next Processor in the decorator chain
return c.Process(e, task)
} else {
return c.Process(e, task)
}
})
}
}