-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
99 lines (87 loc) · 2.62 KB
/
main.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
// Binary slendmail - see README.md
package main
import (
"bytes"
"fmt"
"io"
"log"
"log/syslog"
"net/mail"
"os"
"github.com/pelletier/go-toml/v2"
"github.com/slack-go/slack"
)
// Config - toml config struct
type Config struct {
SlackToken string `toml:"slack_token"`
Channel string
SyslogTag string `toml:"syslog_tag"`
}
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)
}
api := slack.New(config.SlackToken)
// 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)
}
// setup slack message
attach := new(slack.Attachment)
attach.Text = string(body)
hostname, _ := os.Hostname()
subjText := slack.NewTextBlockObject("mrkdwn", "*Subject:* "+msg.Header.Get("Subject"), false, false)
hostText := slack.NewTextBlockObject("mrkdwn", "*Hostname:* "+hostname, false, false)
hdrBlock := make([]*slack.TextBlockObject, 0)
hdrBlock = append(hdrBlock, subjText)
hdrBlock = append(hdrBlock, hostText)
smsg := slack.MsgOptionBlocks(
slack.NewSectionBlock(
nil,
hdrBlock,
nil,
),
)
msgchan, msgts, err := api.PostMessage(
config.Channel,
smsg,
slack.MsgOptionAttachments(*attach),
)
if err != nil {
_ = sl.Err(fmt.Sprintln("failed to post message ", err))
log.Println("body", string(body))
log.Fatal("failed to post message ", err)
}
_ = sl.Debug(fmt.Sprintf("channel: %s - ts: %s - argv: %v", msgchan, msgts, os.Args)) //nolint:errcheck
}