This repository has been archived by the owner on Feb 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
send.go
executable file
·282 lines (248 loc) · 8.94 KB
/
send.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
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
package main
import (
"bufio"
"database/sql"
"fmt"
"github.com/google/uuid"
"github.com/logrusorgru/aurora/v3"
"log"
"net/http"
"net/smtp"
"regexp"
"strings"
)
func initSendDB() {
var err error
mailInsertStmt, err = db.Prepare("INSERT INTO `mails` (`sender_wiiID`,`mail`, `recipient_id`, `mail_id`, `message_id`) VALUES (?, ?, ?, ?, ?)")
if err != nil {
LogError("Error preparing mail insertion statement", err)
panic(err)
}
accountExistsStmt, err = db.Prepare("SELECT EXISTS(SELECT 1 FROM `accounts` WHERE `mlid` = ?)")
if err != nil {
LogError("Error preparing account existence statement", err)
panic(err)
}
}
var mailInsertStmt *sql.Stmt
var accountExistsStmt *sql.Stmt
var mailFormName = regexp.MustCompile(`m\d+`)
var mailFrom = regexp.MustCompile(`^MAIL FROM:\s(.*)@(?:.*)$`)
var mailFrom2 = regexp.MustCompile(`^From:\s(.*)@(?:.*)$`)
var rcptFrom = regexp.MustCompile(`^RCPT TO:\s(.*)@(.*)$`)
// Send takes POSTed mail by the Wii and stores it in the database for future usage.
func Send(w http.ResponseWriter, r *http.Request, db *sql.DB, config Config) {
w.Header().Add("Content-Type", "text/plain;charset=utf-8")
// Create maps for storage of mail.
mailPart := make(map[string]string)
// Parse form in preparation for finding mail.
err := r.ParseMultipartForm(-1)
if err != nil {
fmt.Fprint(w, GenNormalErrorCode(350, "Failed to parse mail."))
LogError("Failed to parse mail", err)
return
}
if global.Debug {
// We won't print file contents within the multipart form.
for name, values := range r.MultipartForm.Value {
log.Println(aurora.Green(name + ":"))
for value := range values {
log.Println(aurora.Cyan("->"), value)
}
}
}
// This may be empty if mlid is not present.
// We expect this, however - our authentication function will determine.
mlid, passwd := parseSendAuth(r.Form.Get("mlid"))
err = checkPasswdValidity(mlid, passwd)
if err == ErrInvalidCredentials {
fmt.Fprintf(w, GenNormalErrorCode(250, "An authentication error occurred."))
return
} else if err != nil {
fmt.Fprintf(w, GenNormalErrorCode(551, "Something weird happened."))
LogError("Error querying authentication database", err)
return
}
for name, contents := range r.MultipartForm.Value {
if mailFormName.MatchString(name) {
mailPart[name] = contents[0]
}
}
eventualOutput := GenSuccessResponse()
eventualOutput += fmt.Sprint("mlnum=", len(mailPart), "\n")
// Handle all the mail! \o/
for mailNumber, contents := range mailPart {
var linesToRemove string
// I'm making this a string for similar reasons as below.
// Plus it beats repeated `strconv.Itoa`s
var wiiRecipientIDs []string
var pcRecipientIDs []string
// Yes, senderID is a string. >.<
// The database contains `w<16 digit ID>` due to previous PHP scripts.
// POTENTIAL TODO: remove w from database?
var senderID string
var data string
// For every new line, handle as needed.
scanner := bufio.NewScanner(strings.NewReader(contents))
for scanner.Scan() {
line := scanner.Text()
// Add it to this mail's overall data.
data += fmt.Sprintln(line)
if line == "DATA" {
// We don't actually need to do anything here,
// just carry on.
linesToRemove += fmt.Sprintln(line)
continue
}
potentialMailFromWrapper := mailFrom.FindStringSubmatch(line)
if potentialMailFromWrapper != nil {
potentialMailFrom := potentialMailFromWrapper[1]
// Ensure MAIL FROM matches the authed mlid (#29)
if potentialMailFrom != mlid {
eventualOutput += GenMailErrorCode(mailNumber, 351, "Attempt to impersonate another user.")
break
} else if potentialMailFrom == "w9999999900000000" {
eventualOutput += GenMailErrorCode(mailNumber, 351, "w9999999900000000 tried to send mail.")
break
}
senderID = potentialMailFrom
linesToRemove += fmt.Sprintln(line)
continue
}
potentialMailFromWrapper2 := mailFrom2.FindStringSubmatch(line)
if potentialMailFromWrapper2 != nil {
potentialMailFrom2 := potentialMailFromWrapper2[1]
// Ensure From matches the authed mlid (#29)
if potentialMailFrom2 != mlid {
eventualOutput += GenMailErrorCode(mailNumber, 351, "Attempt to impersonate another user.")
return
} else if potentialMailFrom2 == "w9999999900000000" {
eventualOutput += GenMailErrorCode(mailNumber, 351, "w9999999900000000 tried to send mail.")
return
}
}
// -1 signifies all matches
potentialRecipientWrapper := rcptFrom.FindAllStringSubmatch(line, -1)
if potentialRecipientWrapper != nil {
// We only need to work with the first match, which should be all we need.
potentialRecipient := potentialRecipientWrapper[0]
// layout:
// potentialRecipient[0] = original matched string w/o groups
// potentialRecipient[1] = w<16 digit ID>
// potentialRecipient[2] = domain being sent to
if potentialRecipient[2] == "wii.com" {
// We're not gonna allow you to send to a defunct domain. ;P
} else if potentialRecipient[2] == config.SendGridDomain {
// Wii <-> Wii mail. We can handle this.
wiiRecipientIDs = append(wiiRecipientIDs, potentialRecipient[1])
} else {
// PC <-> Wii mail. We can't handle this, but SendGrid can.
email := fmt.Sprintf("%s@%s", potentialRecipient[1], potentialRecipient[2])
pcRecipientIDs = append(pcRecipientIDs, email)
}
linesToRemove += fmt.Sprintln(line)
}
}
if err := scanner.Err(); err != nil {
eventualOutput += GenMailErrorCode(mailNumber, 551, "Issue iterating over strings.")
LogError("Error reading from scanner", err)
return
}
mailContents := strings.Replace(data, linesToRemove, "", -1)
// Replace all @wii.com references in the
// friend request email with our own domain.
// Format: w9004342343324713@wii.com <mailto:w9004342343324713@wii.com>
mailContents = strings.Replace(mailContents,
fmt.Sprintf("%s@wii.com <mailto:%s@wii.com>", senderID, senderID),
fmt.Sprintf("%s@%s <mailto:%s@%s>", senderID, global.SendGridDomain, senderID, global.SendGridDomain),
-1)
// We're done figuring out the mail, now it's time to act as needed.
// For Wii recipients, we can just insert into the database.
i := 0
for _, wiiRecipient := range wiiRecipientIDs {
if i > 10 {
continue
}
// Check that the account actually exists (#15)
var exists bool
existsErr := accountExistsStmt.QueryRow(wiiRecipient).Scan(&exists)
if existsErr != nil && existsErr != sql.ErrNoRows {
eventualOutput += GenMailErrorCode(mailNumber, 551, "Issue verifying recipients.")
LogError("Error verifying recipient account existence", err)
return
} else if !exists {
// Account doesn't exist, ignore
continue
}
// Splice wiiRecipient to drop w from 16 digit ID.
_, err := mailInsertStmt.Exec(senderID, mailContents, wiiRecipient[1:], uuid.New().String(), uuid.New().String())
if err != nil {
eventualOutput += GenMailErrorCode(mailNumber, 450, "Database error.")
LogError("Error inserting mail", err)
return
}
i += 1
}
i = 0
for _, pcRecipient := range pcRecipientIDs {
if i > 10 {
continue
}
err := handlePCmail(config, senderID, pcRecipient, mailContents)
if err != nil {
LogError("Error sending mail via SendGrid", err)
eventualOutput += GenMailErrorCode(mailNumber, 551, "Issue sending mail via SendGrid.")
return
}
if pcRecipient == "trigger@applet.ifttt.com" {
// Send dummy confirmation mail for IFTTT.
var iftttMail string
iftttMail = "From: trigger@applet.ifttt.com\n"
iftttMail += "Subject: Trigger\n"
iftttMail += "To: " + senderID + "@rc24.xyz\n"
iftttMail += "MIME-Version: 1.0\n"
iftttMail += "Content-Type: MULTIPART/mixed; BOUNDARY=\"ifttt\"\n"
iftttMail += "--ifttt\n"
iftttMail += "Content-Type: TEXT/plain; CHARSET=utf-8\n"
iftttMail += "Content-Description: wiimail\n\n"
iftttMail += "Trigger has been ran!\n\n"
// iftttMail += "--ifttt--"
_, err := mailInsertStmt.Exec("trigger@applet.ifttt.com", iftttMail, senderID[1:], uuid.New().String(), uuid.New().String())
if err != nil {
eventualOutput += GenMailErrorCode(mailNumber, 450, "Database error.")
LogError("Error inserting mail", err)
return
}
}
i += 1
}
eventualOutput += GenMailErrorCode(mailNumber, 100, "Success.")
if global.Datadog {
err := dataDogClient.Incr("mail.sent_mail", nil, 1.0)
if err != nil {
LogError("Unable to update sent_mail.", err)
}
}
}
// We're completely done now.
fmt.Fprint(w, eventualOutput)
}
func handlePCmail(config Config, senderID string, pcRecipient string, mailContents string) error {
// Connect to the remote SMTP server.
host := "smtp.sendgrid.net"
auth := smtp.PlainAuth(
"",
"apikey",
config.SendGridKey,
host,
)
// The only reason we can get away with the following is
// because the Wii POSTs valid SMTP syntax.
return smtp.SendMail(
fmt.Sprint(host, ":587"),
auth,
fmt.Sprintf("%s@%s", senderID, config.SendGridDomain),
[]string{pcRecipient},
[]byte(mailContents),
)
}