This repository has been archived by the owner on Feb 26, 2019. It is now read-only.
/
send.go
181 lines (158 loc) · 6.05 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
package main
import (
"bufio"
"fmt"
"net/http"
"net/smtp"
"regexp"
"strings"
"github.com/Disconnect24/Mail-GO/utilities"
"github.com/google/uuid"
)
var mailFormName = regexp.MustCompile(`m\d+`)
var mailFrom = regexp.MustCompile(`^MAIL FROM:\s(w[0-9]*)@(?:.*)$`)
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) {
w.Header().Add("Content-Type", "text/plain;charset=utf-8")
// Go ahead and prepare the insert statement, for later usage.
stmt, err := db.Prepare("INSERT INTO `mails` (`sender_wiiID`,`mail`, `recipient_id`, `mail_id`, `message_id`) VALUES (?, ?, ?, ?, ?)")
if err != nil {
// Welp, that went downhill fast.
fmt.Fprint(w, utilities.GenNormalErrorCode(450, "Database error."))
utilities.LogError(ravenClient, "Prepared send statement error", err)
return
}
// 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, utilities.GenNormalErrorCode(350, "Failed to parse mail."))
utilities.LogError(ravenClient, "Failed to parse mail", err)
return
}
// Now check if it can be verified
isVerified, err := Auth(r.Form)
if err != nil {
fmt.Fprintf(w, utilities.GenNormalErrorCode(666, "Something weird happened."))
utilities.LogError(ravenClient, "Error changing from authentication database.", err)
return
} else if !isVerified {
fmt.Fprintf(w, utilities.GenNormalErrorCode(240, "An authentication error occurred."))
return
}
for name, contents := range r.MultipartForm.Value {
if mailFormName.MatchString(name) {
mailPart[name] = contents[0]
}
}
eventualOutput := utilities.GenSuccessResponse()
eventualOutput += fmt.Sprint("mlnum=", len(mailPart), "\n")
// Handle all the mail! \o/
for mailNumber, contents := range mailPart {
var wiiRecipientIDs []string
var pcRecipientIDs []string
// senderID must be a string.
// The database contains `w<16 digit ID>` due to previous PHP scripts.
// POTENTIAL TODO: remove w from database?
var senderID string
var mailContents string
// For every new line, handle as needed.
scanner := bufio.NewScanner(strings.NewReader(contents))
for scanner.Scan() {
line := scanner.Text()
if line == "DATA" {
// This line just tells the server beyond here to stop processing
// We shouldn't send that to the client, so we're done.
return
}
potentialMailFromWrapper := mailFrom.FindStringSubmatch(line)
if potentialMailFromWrapper != nil {
potentialMailFrom := potentialMailFromWrapper[1]
// "Special" number from Nintendo, used to send to allusers@wii.com.
// While not necessarily hardcoded anywhere, no need to confuse.
if potentialMailFrom == "w9999999900000000" {
eventualOutput += utilities.GenMailErrorCode(mailNumber, 351, "w9999999900000000 tried to send mail.")
return
}
senderID = potentialMailFrom
continue
}
// -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[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] == global.SendGridDomain {
// Wii <-> Wii mail. We can handle this.
wiiRecipientIDs = append(wiiRecipientIDs, potentialRecipient[1])
} else {
// PC <-> Wii mail. An actual mail server will handle this.
email := fmt.Sprintf("%s@%s", potentialRecipient[1], potentialRecipient[2])
pcRecipientIDs = append(pcRecipientIDs, email)
}
}
// This line doesn't need to be processed and can be added.
mailContents += line
}
if err := scanner.Err(); err != nil {
eventualOutput += utilities.GenMailErrorCode(mailNumber, 551, "Issue iterating over strings.")
utilities.LogError(ravenClient, "Error reading from scanner", err)
return
}
// 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.
for _, wiiRecipient := range wiiRecipientIDs {
// Splice wiiRecipient to drop w from 16 digit ID.
_, err := stmt.Exec(senderID, mailContents, wiiRecipient[1:], uuid.New().String(), uuid.New().String())
if err != nil {
eventualOutput += utilities.GenMailErrorCode(mailNumber, 450, "Database error.")
utilities.LogError(ravenClient, "Error inserting mail", err)
return
}
}
for _, pcRecipient := range pcRecipientIDs {
err := handlePCmail(senderID, pcRecipient, mailContents)
if err != nil {
utilities.LogError(ravenClient, "Error sending mail via SMTP", err)
eventualOutput += utilities.GenMailErrorCode(mailNumber, 551, "Issue sending mail via SMTP.")
return
}
}
eventualOutput += utilities.GenMailErrorCode(mailNumber, 100, "Success.")
}
// We're completely done now.
fmt.Fprint(w, eventualOutput)
}
func handlePCmail(senderID string, pcRecipient string, mailContents string) error {
// Connect to the remote SMTP server.
host := "smtp.sendgrid.net"
auth := smtp.PlainAuth(
"",
"apikey",
global.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, global.SendGridDomain),
[]string{pcRecipient},
[]byte(mailContents),
)
}