-
Notifications
You must be signed in to change notification settings - Fork 1
/
inbound.go
243 lines (203 loc) · 6.13 KB
/
inbound.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
package main
import (
"bufio"
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/gin-gonic/gin"
"golang.org/x/image/draw"
"image"
"image/jpeg"
"io"
"net/http"
"net/mail"
"strings"
"unicode/utf8"
// Importing as a side effect allows for the image library to check for these formats
_ "image/gif"
_ "image/png"
_ "golang.org/x/image/bmp"
_ "golang.org/x/image/tiff"
_ "golang.org/x/image/webp"
)
const (
PlaceholderMessage = "No Content."
MaxImageDimension = 8192
// MaxMailSize is the largest possible size mail can be, as per KD.
MaxMailSize = 1578040
)
func inbound(c *gin.Context) {
if c.PostForm("from") == "" || c.PostForm("to") == "" {
c.String(http.StatusBadRequest, "")
return
}
message := c.PostForm("text")
if message == "" {
message = PlaceholderMessage
}
// Sanitize the message
message = removeNonUTF8Characters(message)
fromRaw := c.PostForm("from")
from, err := mail.ParseAddress(fromRaw)
if err != nil {
ReportError(err)
c.String(http.StatusBadRequest, "")
return
}
toRaw := c.PostForm("to")
to, err := mail.ParseAddress(toRaw)
if err != nil {
ReportError(err)
c.String(http.StatusBadRequest, "")
return
}
subject := c.PostForm("subject")
type File struct {
Filename string `go:"filename"`
Charset string `go:"charset"`
Type string `go:"type"`
}
var attachment []byte
attachmentInfo := make(map[string]File)
err = json.Unmarshal([]byte(c.PostForm("attachment-info")), &attachmentInfo)
if err == nil {
hasImage := false
hasAttachedText := false
for name, _attachment := range attachmentInfo {
attachmentHeader, err := c.FormFile(name)
if errors.Is(err, http.ErrMissingFile) {
// We don't care if there's nothing, it'll just stay nil.
} else if err != nil {
ReportError(err)
c.String(http.StatusInternalServerError, "")
return
} else {
if strings.Contains(_attachment.Type, "image") && hasImage == false {
attachmentData, err := attachmentHeader.Open()
if err != nil {
c.String(http.StatusInternalServerError, "")
return
}
attachment, err = io.ReadAll(attachmentData)
if err != nil {
c.String(http.StatusInternalServerError, "")
return
}
hasImage = true
} else if strings.Contains(_attachment.Type, "text") && hasAttachedText == false && message == PlaceholderMessage {
attachmentData, err := attachmentHeader.Open()
if err != nil {
c.String(http.StatusInternalServerError, "")
return
}
attachedText, err := io.ReadAll(attachmentData)
message = string(attachedText)
if err != nil {
c.String(http.StatusInternalServerError, "")
return
}
hasAttachedText = true
}
}
}
}
formulatedMail, err := formulateMessage(from.Address, to.Address, subject, message, attachment)
if err != nil {
c.String(http.StatusInternalServerError, "")
return
}
// We can do pretty much the exact same thing as the Wii send endpoint
parsedWiiNumber := strings.Split(to.Address, "@")[0]
_, err = pool.Exec(c.Copy(), InsertMail, flakeNode.Generate(), formulatedMail, from.Address, parsedWiiNumber[1:])
if err != nil {
c.String(http.StatusInternalServerError, "")
return
}
c.String(http.StatusOK, "")
}
func formulateMessage(from, to, subject, body string, attachment []byte) (string, error) {
boundary := generateBoundary()
header := fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"%s\"\r\n\r\n--%s\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Description: wiimail\r\n\r\n",
from, to, subject, boundary, boundary)
content := fmt.Sprint(header, body, strings.Repeat("\r\n", 3), "--", boundary, "--")
// If there is no attachment, we are done here.
if attachment == nil {
return content, nil
}
decodedImage, _, err := image.Decode(bytes.NewReader(attachment))
if err != nil {
return content, nil
}
// Resize if needed
decodedImage = resize(decodedImage)
var jpegEncoded bytes.Buffer
err = jpeg.Encode(bufio.NewWriter(&jpegEncoded), decodedImage, nil)
if err != nil {
return "", err
}
if jpegEncoded.Len()+len(content) > MaxMailSize {
// If the image and content is too big, we can send just the content.
return content, nil
}
base64Image := base64.StdEncoding.EncodeToString(jpegEncoded.Bytes())
// According to RFC, 79 is the maximum allowed characters in a line.
// Observations from messages sent by a Wii show 64 characters in a line before a line break.
var fixedEncoding string
for {
if len(base64Image) >= 64 {
fixedEncoding += base64Image[:64] + "\r\n"
base64Image = base64Image[64:]
} else {
// To the end.
fixedEncoding += base64Image[:]
break
}
}
return fmt.Sprint(header,
body,
strings.Repeat("\r\n", 3),
"--", boundary, "\r\n",
// Now we can put our image data.
"Content-Type: image/jpeg; name=image.jpeg", "\r\n",
"Content-Transfer-Encoding: base64", "\r\n",
"Content-Disposition: attachment; filename=image.jpeg", "\r\n",
"\r\n",
fixedEncoding, "\r\n",
"\r\n",
"--", boundary, "--",
), nil
}
// resize well resizes the image to what we want.
// Taken from https://stackoverflow.com/questions/22940724/go-resizing-images
func resize(originalImage image.Image) image.Image {
width := originalImage.Bounds().Size().X
height := originalImage.Bounds().Size().Y
if width > MaxImageDimension {
// Allows for proper scaling.
height = height * MaxImageDimension / width
width = MaxImageDimension
}
if height > MaxImageDimension {
width = width * MaxImageDimension / height
height = MaxImageDimension
}
if width != MaxImageDimension && height != MaxImageDimension {
// No resize needs to occur.
return originalImage
}
newImage := image.NewRGBA(image.Rect(0, 0, width, height))
// BiLinear mode is the slowest out of the available but offers highest quality.
draw.BiLinear.Scale(newImage, newImage.Bounds(), originalImage, originalImage.Bounds(), draw.Over, nil)
return newImage
}
func removeNonUTF8Characters(message string) string {
var buffer []byte
for _, r := range message {
if utf8.ValidRune(r) {
buffer = append(buffer, []byte(string(r))...)
}
}
return string(buffer)
}