-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrest.go
211 lines (187 loc) · 5.12 KB
/
rest.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
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"io"
"net"
"net/http"
"strings"
"time"
)
type MangoHttpServer struct {
config *ServiceConfiguration
store FileStore
identifiers map[string]string
}
func listenRequests(port string, store FileStore, config *ServiceConfiguration) error {
server := &MangoHttpServer{store: store, config: config, identifiers: map[string]string{}}
router := mux.NewRouter()
router.HandleFunc("/upload", server.upload).Methods("POST")
router.HandleFunc("/get/{id}", server.get)
return http.ListenAndServe(":"+port, router)
}
//#region Download
type FileResponse struct {
Status string `json:"status"` // "ok" or "error"
Error string `json:"error,omitempty"`
Present bool `json:"present"`
File string `json:"file,omitempty"`
}
// Handles the download of previously stored files,
// must have an "id" parameter
func (server *MangoHttpServer) get(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
file, err := server.store.Read(id)
var response *FileResponse
if err != nil {
// failed to read file from store
response = &FileResponse{
Status: "error",
Present: false,
Error: err.Error(),
}
fmt.Printf("[info] requested file '%s', but can't be get: %v\n", id, err)
} else {
data, err := io.ReadAll(file)
if err != nil {
// failed to read file bytes
response = &FileResponse{
Status: "ok",
Present: false,
Error: err.Error(),
}
fmt.Printf("[info] requested file '%s', but bytes can't be read: %v\n", id, err)
} else {
// Success!
_ = file.Close()
response = &FileResponse{
Status: "ok",
Present: true,
File: base64.StdEncoding.EncodeToString(data),
}
// don't forget to remove file
_, _ = server.store.Delete(id)
fmt.Printf("[info] requested file '%s', downloaded\n", id)
}
}
_ = json.NewEncoder(w).Encode(response)
}
// #endregion
// #region Upload
type FileUploadResponse struct {
Ok bool `json:"ok"`
Code int `json:"code"`
Error string `json:"error,omitempty"`
Id string `json:"id,omitempty"`
}
func (server *MangoHttpServer) GetRemoteAddr(r *http.Request) string {
if server.config.TrustProxy {
forwardedFor := r.Header.Get("X-Forwarded-For")
if forwardedFor != "" {
ips := strings.Split(forwardedFor, ", ")
if len(ips) > 1 {
// use the first address if we got an array
return ips[0]
}
// otherwise just return the full string
return forwardedFor
}
}
// only use host
host, _, _ := net.SplitHostPort(r.RemoteAddr)
return host
}
func (server *MangoHttpServer) RemoteAddrToIdentifier(remoteAddr string) string {
id, ok := server.identifiers[remoteAddr]
if !ok {
// generate id, note that ip cannot be
// obtained from the id
millis := time.Now().UnixMilli()
id = fmt.Sprintf("%x", millis)
server.identifiers[remoteAddr] = id
}
return id
}
func fail(w http.ResponseWriter, code int, error string) {
fmt.Printf("[info] failed to upload file: %s (code %d)\n", error, code)
response := &FileUploadResponse{
Ok: false,
Code: code,
Error: error,
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
err := json.NewEncoder(w).Encode(response)
if err != nil {
fmt.Printf("[error] failed to write JSON error response: %v\n", err)
}
}
func (server *MangoHttpServer) upload(w http.ResponseWriter, r *http.Request) {
remoteAddr := server.GetRemoteAddr(r)
id, hasId := server.identifiers[remoteAddr]
if hasId {
fail(w, 400, "Only one file per IP address")
return
}
err := r.ParseMultipartForm(32 << 20)
if err != nil {
fmt.Printf("[error] failed to parse multipart form data: %v\n", err)
}
files, ok := r.MultipartForm.File["file"]
if !ok || files == nil {
fail(w, 400, "No file specified")
return
}
if len(files) != 1 {
fail(w, 400, "Please specify a file (not more)")
return
}
file := files[0]
if file.Size > server.config.SizeLimit {
fail(w, 413, fmt.Sprintf("File is too large (%d bytes), limit is %d", file.Size, server.config.SizeLimit))
return
}
f, err := file.Open()
if err != nil {
fail(w, 400, fmt.Sprintf("Failed to open uploaded file: %v", err))
return
}
defer f.Close()
data, err := io.ReadAll(f)
if err != nil {
fail(w, 400, fmt.Sprintf("Failed to read file data: %v", err))
return
}
if int64(len(data)) > server.config.SizeLimit {
// did they just try to hack us ??
fail(w, 413, fmt.Sprintf("File is too large (%d bytes), limit is %d (?)", len(data), server.config.SizeLimit))
return
}
id = server.RemoteAddrToIdentifier(remoteAddr)
err = server.store.Create(id, bytes.NewReader(data))
if err != nil {
fail(w, 400, fmt.Sprintf("Failed to save file: %v", err))
return
}
response := &FileUploadResponse{
Ok: true,
Code: 200,
Id: id,
}
json.NewEncoder(w).Encode(response)
fmt.Printf("[info] uploaded file '%s'\n", id)
// schedule deletion of file
go func() {
<-time.After(time.Duration(server.config.Lifetime) * time.Millisecond)
delete(server.identifiers, remoteAddr)
existed, _ := server.store.Delete(id)
if existed {
fmt.Printf("[info] expired file '%s'\n", id)
}
}()
}
//#endregion