-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
298 lines (251 loc) · 7.37 KB
/
main.go
File metadata and controls
298 lines (251 loc) · 7.37 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
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
// Binary slendmail - see README.md
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"log/syslog"
"net/http"
"net/mail"
"os"
"strings"
"github.com/pelletier/go-toml/v2"
"github.com/slack-go/slack"
)
// EmailMessage represents a parsed email
type EmailMessage struct {
Subject string
Body string
Hostname string
}
// Backend interface for notification backends
type Backend interface {
Send(msg *EmailMessage) error
Name() string
}
// Config - toml config struct
type Config struct {
SyslogTag string `toml:"syslog_tag"`
Backends BackendsConfig `toml:"backends"`
}
// BackendsConfig contains configuration for all backends
type BackendsConfig struct {
Slack []SlackConfig `toml:"slack"`
Webhook []WebhookConfig `toml:"webhook"`
}
// SlackConfig configuration for Slack backend
type SlackConfig struct {
Token string `toml:"token"`
Channel string `toml:"channel"`
Name string `toml:"name,omitempty"`
}
// WebhookConfig configuration for generic webhook backend
type WebhookConfig struct {
URL string `toml:"url"`
Name string `toml:"name,omitempty"`
Headers map[string]string `toml:"headers,omitempty"`
Username string `toml:"username,omitempty"`
Channel string `toml:"channel,omitempty"`
Format string `toml:"format,omitempty"` // "mattermost", "slack", "generic"
}
// SlackBackend implements Backend for Slack notifications
type SlackBackend struct {
config SlackConfig
api *slack.Client
}
// NewSlackBackend creates a new Slack backend
func NewSlackBackend(config SlackConfig) *SlackBackend {
return &SlackBackend{
config: config,
api: slack.New(config.Token),
}
}
// Name returns the backend name
func (s *SlackBackend) Name() string {
if s.config.Name != "" {
return fmt.Sprintf("Slack (%s)", s.config.Name)
}
return "Slack"
}
// Send sends the email message to Slack
func (s *SlackBackend) Send(msg *EmailMessage) error {
// setup slack message
attach := &slack.Attachment{
Text: msg.Body,
}
subjText := slack.NewTextBlockObject("mrkdwn", "*Subject:* "+msg.Subject, false, false)
hostText := slack.NewTextBlockObject("mrkdwn", "*Hostname:* "+msg.Hostname, false, false)
hdrBlock := []*slack.TextBlockObject{subjText, hostText}
smsg := slack.MsgOptionBlocks(
slack.NewSectionBlock(
nil,
hdrBlock,
nil,
),
)
_, _, err := s.api.PostMessage(
s.config.Channel,
smsg,
slack.MsgOptionAttachments(*attach),
)
return err
}
// WebhookBackend implements Backend for generic webhook notifications
type WebhookBackend struct {
config WebhookConfig
client *http.Client
}
// NewWebhookBackend creates a new webhook backend
func NewWebhookBackend(config WebhookConfig) *WebhookBackend {
// Set default format if not specified
if config.Format == "" {
config.Format = "mattermost"
}
return &WebhookBackend{
config: config,
client: &http.Client{},
}
}
// Name returns the backend name
func (w *WebhookBackend) Name() string {
if w.config.Name != "" {
return fmt.Sprintf("Webhook (%s)", w.config.Name)
}
return "Webhook"
}
// Send sends the email message to the webhook endpoint
func (w *WebhookBackend) Send(msg *EmailMessage) error {
var payload interface{}
switch w.config.Format {
case "mattermost", "slack":
// Mattermost/Slack compatible format
text := fmt.Sprintf("**Subject:** %s\n**Hostname:** %s\n\n%s",
msg.Subject, msg.Hostname, msg.Body)
payload = map[string]interface{}{
"text": text,
}
// Add optional fields
if w.config.Username != "" {
payload.(map[string]interface{})["username"] = w.config.Username
}
if w.config.Channel != "" {
payload.(map[string]interface{})["channel"] = w.config.Channel
}
case "generic":
// Generic format with separate fields
payload = map[string]interface{}{
"subject": msg.Subject,
"body": msg.Body,
"hostname": msg.Hostname,
}
default:
return fmt.Errorf("unsupported webhook format: %s", w.config.Format)
}
jsonPayload, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("failed to marshal webhook payload: %w", err)
}
req, err := http.NewRequest("POST", w.config.URL, bytes.NewBuffer(jsonPayload))
if err != nil {
return fmt.Errorf("failed to create webhook request: %w", err)
}
// Set default content type
req.Header.Set("Content-Type", "application/json")
// Add custom headers
for key, value := range w.config.Headers {
req.Header.Set(key, value)
}
resp, err := w.client.Do(req)
if err != nil {
return fmt.Errorf("failed to send webhook request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("webhook request failed with status %d: %s",
resp.StatusCode, string(body))
}
return nil
}
func main() {
var config Config
// set a default for syslogtag
config.SyslogTag = "slendmail"
// read config
cfgFile, err := os.ReadFile("/etc/slendmail.conf")
if err != nil {
log.Fatal("failed to read config file ", err)
}
err = toml.Unmarshal(cfgFile, &config)
if err != nil {
log.Fatal("failed to unmarshal config file ", err)
}
// setup syslogger, we use this instead of regular output so we can see the output in the
// case of being called from crond
sl, err := syslog.New(syslog.LOG_WARNING|syslog.LOG_MAIL, config.SyslogTag)
if err != nil {
_ = sl.Err(fmt.Sprintln("failed to setup syslog connection ", err))
log.Fatal("failed to setup syslog connection ", err)
}
// parse stdin, check RFC5321 for specifics of the format
// this probably needs to be beefed up a bit to handle other
// callers. So far only tested with busybox/Alpine crond
stdin, err := io.ReadAll(os.Stdin)
if err != nil {
// this really shouldn't fail
log.Fatal("failed to read stdin", err)
}
_ = sl.Debug(string(stdin))
msg, err := mail.ReadMessage(bytes.NewReader(stdin))
if err != nil {
_ = sl.Err(fmt.Sprintln("failed to read stdin email format ", err))
log.Fatal("failed to read stdin email format", err)
}
body, err := io.ReadAll(msg.Body)
if err != nil {
_ = sl.Err(fmt.Sprintln("failed to read email body ", err))
log.Fatal("failed to read email body", err)
}
hostname, _ := os.Hostname()
emailMsg := &EmailMessage{
Subject: msg.Header.Get("Subject"),
Body: strings.TrimSpace(string(body)),
Hostname: hostname,
}
// Initialize backends
var backends []Backend
// Add Slack backends
for _, slackConfig := range config.Backends.Slack {
backends = append(backends, NewSlackBackend(slackConfig))
}
// Add Webhook backends
for _, webhookConfig := range config.Backends.Webhook {
backends = append(backends, NewWebhookBackend(webhookConfig))
}
if len(backends) == 0 {
_ = sl.Err("no backends configured")
log.Fatal("no backends configured")
}
// Send to all backends
var errors []string
for _, backend := range backends {
err := backend.Send(emailMsg)
if err != nil {
errMsg := fmt.Sprintf("failed to send via %s: %v", backend.Name(), err)
errors = append(errors, errMsg)
_ = sl.Err(errMsg)
} else {
_ = sl.Debug(fmt.Sprintf("successfully sent via %s", backend.Name()))
}
}
// If all backends failed, exit with error
if len(errors) == len(backends) {
log.Fatal("all backends failed: ", strings.Join(errors, "; "))
}
// Log summary
successCount := len(backends) - len(errors)
_ = sl.Debug(fmt.Sprintf("sent to %d/%d backends successfully - argv: %v",
successCount, len(backends), os.Args))
}