-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_tools.go
414 lines (299 loc) · 7.61 KB
/
api_tools.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
// API Tools
package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"math"
"net"
"net/http"
"os"
"regexp"
"strconv"
"strings"
encrypted_storage "github.com/AgustinSRG/encrypted-storage"
)
const (
JSON_BODY_MAX_LENGTH = 5 * 1024 * 1024 // Max length of body for JSON APIs
AUTH_API_BODY_MAX_LENGTH = 16 * 1024 // Max length of body for authentication requests
)
// Finds session from request headers
// request - HTTP request
// Returns the reference to the session, or nil if unauthorized
func GetSessionFromRequest(request *http.Request) *ActiveSession {
sessionToken := request.Header.Get("x-session-token")
return GetVault().sessions.FindSession(sessionToken)
}
// Finds session from request headers
// Uses cookie if header not set
// Use only for GET requests, to avoid CSRF
// request - HTTP request
// Returns the reference to the session, or nil if unauthorized
func GetSessionFromRequestCookie(request *http.Request) *ActiveSession {
sessionToken := request.Header.Get("x-session-token")
if sessionToken != "" {
return GetVault().sessions.FindSession(sessionToken)
}
sessionToken = request.URL.Query().Get("session_token")
if sessionToken != "" {
return GetVault().sessions.FindSession(sessionToken)
}
sessionCookieName := "st-" + GetVault().credentials.GetFingerprint()
cookie, err := request.Cookie(sessionCookieName)
if err != nil || cookie == nil {
return nil
}
return GetVault().sessions.FindSession(cookie.Value)
}
// Parses range header from request
// request - HTTP request
// Returns:
//
// 1 - Start index
// 2 - Ending index
//
// Note: -1 in the index means not set
func ParseRangeHeader(request *http.Request) (int64, int64) {
rangeHeader := request.Header.Get("Range")
m, _ := regexp.MatchString("bytes=([0-9]*)-([0-9]*)", rangeHeader)
if !m {
return 0, 0
}
rangeVal := strings.Split(rangeHeader, "=")[1]
parts := strings.Split(rangeVal, "-")
var err error
start := int64(-1)
end := int64(-1)
if parts[0] != "" {
start, err = strconv.ParseInt(parts[0], 10, 64)
if err != nil {
start = -1
}
}
if parts[1] != "" {
end, err = strconv.ParseInt(parts[1], 10, 64)
if err != nil {
end = -1
}
}
return start, end
}
// Returns API standard JSON response
// response - HTTP response handler
// request - HTTP request handler
// result - JSON result
func ReturnAPI_JSON(response http.ResponseWriter, request *http.Request, result []byte) {
hasher := sha256.New()
hasher.Write(result)
hash := hasher.Sum(nil)
etag := hex.EncodeToString(hash)
response.Header().Set("ETag", etag)
response.Header().Set("Cache-Control", "no-cache")
if request.Header.Get("If-None-Match") == etag {
response.WriteHeader(304)
} else {
response.Header().Set("Content-Type", "application/json")
response.WriteHeader(200)
response.Write(result) //nolint:errcheck
}
}
// API standard error response
type APIErrorResponse struct {
Code string `json:"code"` // Error code
Message string `json:"message"` // Error message
}
// Returns API standard error message
// response - HTTP response handler
// request - HTTP request handler
// status - HTTP status
// code - Error code
// message - Error message
func ReturnAPIError(response http.ResponseWriter, status int, code string, message string) {
var m APIErrorResponse
m.Code = code
m.Message = message
jsonRes, err := json.Marshal(m)
if err != nil {
LogError(err)
response.Header().Set("Cache-Control", "no-cache")
response.WriteHeader(500)
return
}
response.Header().Set("Content-Type", "application/json")
response.Header().Set("Cache-Control", "no-cache")
response.WriteHeader(status)
response.Write(jsonRes) //nolint:errcheck
}
// Gets client IP address
// request - HTTP request
func GetClientIP(request *http.Request) string {
ip, _, _ := net.SplitHostPort(request.RemoteAddr)
if os.Getenv("USING_PROXY") == "YES" {
forwardedFor := request.Header.Get("X-Forwarded-For")
if forwardedFor != "" {
return forwardedFor
} else {
return ip
}
} else {
return ip
}
}
// Encrypts original asset file (when uploaded)
// mid - Media ID
// file - Unencrypted file path
// key - Encryption key
// Returns a temporal file with the encrypted contents
// This method also sets the progress in the media assets manager
func EncryptOriginalAssetFile(mid uint64, file string, key []byte) (string, error) {
encrypted_file := GetTemporalFileName("pma", true)
f, err := os.OpenFile(file, os.O_RDONLY, FILE_PERMISSION)
if err != nil {
return "", err
}
f_info, err := f.Stat()
if err != nil {
f.Close()
return "", err
}
ws, err := encrypted_storage.CreateFileBlockEncryptWriteStream(encrypted_file, FILE_PERMISSION)
if err != nil {
f.Close()
return "", err
}
err = ws.Initialize(f_info.Size(), ENCRYPTED_BLOCK_MAX_SIZE, key)
if err != nil {
ws.Close()
f.Close()
os.Remove(encrypted_file)
return "", err
}
finished := false
buf := make([]byte, 1024*1024)
bytesEncrypted := float64(0)
bytesTotal := float64(f_info.Size())
if bytesTotal == 0 {
bytesTotal = 1
}
for !finished {
c, err := f.Read(buf)
if err != nil && err != io.EOF {
ws.Close()
f.Close()
os.Remove(encrypted_file)
GetVault().media.EndProgress(mid)
return "", err
}
if err == io.EOF {
finished = true
}
if c == 0 {
continue
}
err = ws.Write(buf[:c])
if err != nil {
LogError(err)
ws.Close()
f.Close()
GetVault().media.EndProgress(mid)
os.Remove(encrypted_file)
return "", err
}
bytesEncrypted += float64(c)
progress_enc := math.Round(bytesEncrypted * 100 / bytesTotal)
p := int32(progress_enc)
GetVault().media.SetProgress(mid, p)
}
ws.Close()
f.Close()
GetVault().media.EndProgress(mid)
return encrypted_file, nil
}
// Encrypts media asset file
// file - File to encrypt
// key - Encryption key
// Returns a temporal file with the encrypted contents
func EncryptAssetFile(file string, key []byte) (string, error) {
encrypted_file := GetTemporalFileName("pma", true)
f, err := os.OpenFile(file, os.O_RDONLY, FILE_PERMISSION)
if err != nil {
return "", err
}
f_info, err := f.Stat()
if err != nil {
f.Close()
return "", err
}
ws, err := encrypted_storage.CreateFileBlockEncryptWriteStream(encrypted_file, FILE_PERMISSION)
if err != nil {
f.Close()
return "", err
}
err = ws.Initialize(f_info.Size(), ENCRYPTED_BLOCK_MAX_SIZE, key)
if err != nil {
ws.Close()
f.Close()
os.Remove(encrypted_file)
return "", err
}
finished := false
buf := make([]byte, 1024*1024)
for !finished {
c, err := f.Read(buf)
if err != nil && err != io.EOF {
ws.Close()
f.Close()
os.Remove(encrypted_file)
return "", err
}
if err == io.EOF {
finished = true
}
if c == 0 {
continue
}
err = ws.Write(buf[:c])
if err != nil {
LogError(err)
ws.Close()
f.Close()
os.Remove(encrypted_file)
return "", err
}
}
ws.Close()
f.Close()
return encrypted_file, nil
}
func EncryptAssetData(data []byte, key []byte) (string, error) {
encrypted_file := GetTemporalFileName("pma", true)
ws, err := encrypted_storage.CreateFileBlockEncryptWriteStream(encrypted_file, FILE_PERMISSION)
if err != nil {
return "", err
}
err = ws.Initialize(int64(len(data)), ENCRYPTED_BLOCK_MAX_SIZE, key)
if err != nil {
ws.Close()
os.Remove(encrypted_file)
return "", err
}
err = ws.Write(data)
if err != nil {
LogError(err)
ws.Close()
os.Remove(encrypted_file)
return "", err
}
ws.Close()
return encrypted_file, nil
}
func LimitStringSize(str string, size int) string {
if len(str) <= size {
return str
} else if size > 0 {
return str[:size]
} else {
return ""
}
}