/
db.go
executable file
·271 lines (253 loc) · 6.86 KB
/
db.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
package main
import (
"crypto/md5"
"encoding/base64"
"fmt"
"log"
"net"
"net/http"
"strings"
"time"
"github.com/gomodule/redigo/redis"
"github.com/stefanovazzocell/R3/shared"
)
var pool *redis.Pool
func newPool(redisUri string) *redis.Pool {
log.Println("[DB] Creating new Redis Pool")
return &redis.Pool{
MaxIdle: 20,
MaxActive: 1000,
Dial: func() (redis.Conn, error) {
c, err := redis.DialURL(redisUri)
if err != nil {
panic(err)
}
return c, err
},
}
}
func redisGetShare(httpReq *http.Request, req shared.ViewRequest) (shared.APIResponseData, error) {
var (
manage bool = (len(req.Password) == 88)
response shared.APIResponseData = shared.APIResponseData{}
)
// Get a Connection
conn := pool.Get()
defer conn.Close()
// Rate Limit
err := redisHit(conn, httpReq, 0)
if err != nil {
return response, err
}
// Try to get data
conn.Send("MULTI")
if manage {
conn.Send("GET", DatabasePrefix+":spass:"+req.ID)
conn.Send("TTL", DatabasePrefix+":sdata:"+req.ID)
conn.Send("GET", DatabasePrefix+":shits:"+req.ID)
rrv, err := redis.Values(conn.Do("EXEC"))
if err != nil && err != redis.ErrNil {
log.Printf("Error while retriving share data: %v\n", err)
return response, ErrorGeneric
}
if err == redis.ErrNil {
return response, ErrorShareExpOrPass
}
// Check Password
pass, err := redis.String(rrv[0], err)
if err != nil && err != redis.ErrNil {
log.Printf("Error while retriving share data password: %v\n", err)
return response, ErrorGeneric
}
if pass != req.Password {
return response, ErrorSharePassword
}
// Get Metadata
ttl, err := redis.Int(rrv[1], err)
if err != nil && err != redis.ErrNil {
log.Printf("Error while retriving share data ttl: %v\n", err)
return response, ErrorGeneric
}
hits, err := redis.Int(rrv[2], err)
if err != nil && err != redis.ErrNil {
log.Printf("Error while retriving share data hits: %v\n", err)
return response, ErrorGeneric
}
response.Success = true
response.Err = ""
response.TTL = ttl
response.Hits = hits
return response, nil
} else {
conn.Send("INCRBY", DatabasePrefix+":shits:"+req.ID, -1)
conn.Send("GET", DatabasePrefix+":sdata:"+req.ID)
rrv, err := redis.Values(conn.Do("EXEC"))
if err != nil && err != redis.ErrNil {
log.Printf("Error while retriving share data: %v\n", err)
return response, ErrorGeneric
}
if err == redis.ErrNil {
return response, ErrorShareExpired
}
// Check hits
hits, err := redis.Int(rrv[0], err)
if err != nil && err != redis.ErrNil {
log.Printf("Error while checking share data hits: %v\n", err)
return response, ErrorGeneric
}
if hits < 0 {
return response, ErrorShareExpired
}
// Get data
data, err := redis.Bytes(rrv[1], err)
if err != nil && err != redis.ErrNil {
log.Printf("Error while parsing share data: %v\n", err)
return response, ErrorGeneric
}
response.Success = true
response.Err = ""
response.Data = base64.StdEncoding.EncodeToString(data)
// Expire share
if hits <= 0 {
conn.Send("MULTI")
conn.Send("DEL", DatabasePrefix+":sdata:"+req.ID)
conn.Send("DEL", DatabasePrefix+":spass:"+req.ID)
conn.Send("DEL", DatabasePrefix+":shits:"+req.ID)
conn.Do("EXEC")
}
return response, nil
}
}
func redisEditShare(httpReq *http.Request, req shared.EditRequest, dataDecoded []byte) error {
editing := (req.Password != "")
// Get a Connection
conn := pool.Get()
defer conn.Close()
// Check if share exists
data, err := redis.Bytes(conn.Do("GET", DatabasePrefix+":sdata:"+req.ID))
if err != nil && err != redis.ErrNil {
log.Printf("Error while checking if share exists: %v\n", err)
return ErrorGeneric
}
shareExists := (len(data) > 0)
// If editing/deleting it must exist, otherwise it shouldn't
if editing && !shareExists {
return ErrorShareExpired
}
if len(req.Password) == 0 && shareExists {
return ErrorShareExists
}
// Rate limit check
if editing && !req.Delete || editing {
cost := len(dataDecoded) / 1000
if cost < 1 {
cost = 1
}
err := redisHit(conn, httpReq, cost)
if err != nil {
return err
}
}
// If editing, check that the password matches
if editing {
data, err := redis.String(conn.Do("GET", DatabasePrefix+":spass:"+req.ID))
if err != nil && err != redis.ErrNil {
log.Printf("Error while checking password match: %v\n", err)
return ErrorGeneric
}
if err == redis.ErrNil || data == "" {
return ErrorShareNotEditable
} else if data != req.Password {
return ErrorSharePassword
}
}
// Either delete or save
if editing && req.Delete {
conn.Send("MULTI")
conn.Send("DEL", DatabasePrefix+":sdata:"+req.ID)
conn.Send("DEL", DatabasePrefix+":spass:"+req.ID)
conn.Send("DEL", DatabasePrefix+":shits:"+req.ID)
_, err := conn.Do("EXEC")
if err != nil && err != redis.ErrNil {
log.Printf("Error while deleting: %v\n", err)
return ErrorGeneric
}
} else {
conn.Send("MULTI")
// Set Data
conn.Send("SETEX", DatabasePrefix+":sdata:"+req.ID, req.Payload.TTL, dataDecoded)
// Either set or clear edit password
if len(req.Payload.Edit) == 88 {
conn.Send("SETEX", DatabasePrefix+":spass:"+req.ID, req.Payload.TTL, req.Payload.Edit)
} else {
conn.Send("DEL", DatabasePrefix+":spass:"+req.ID)
}
// Set hits limit
conn.Send("SETEX", DatabasePrefix+":shits:"+req.ID, req.Payload.TTL, req.Payload.Hits)
_, err := conn.Do("EXEC")
if err != nil {
log.Printf("Error while creating/editing: %v\n", err)
return ErrorGeneric
}
}
return nil
}
func redisHit(conn redis.Conn, r *http.Request, data int) error {
// Note: if data == 0, it will consider this a request
var (
ip string = ""
id string
err error
count int
isData bool = (data != 0)
)
// Get IP
if HasProxy {
ip = r.Header.Get("CF-Connecting-IP")
if ip == "" {
ip = strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0]
}
}
if !HasProxy || ip == "" {
ip, _, _ = net.SplitHostPort(r.RemoteAddr)
}
hash := md5.Sum([]byte(fmt.Sprintf("%s%d", ip, time.Now().Hour())))
id = base64.URLEncoding.EncodeToString(hash[0:2])
// Count
if isData {
count, err = redis.Int(conn.Do("INCRBY", DatabasePrefix+":datacap:"+id, data))
conn.Do("EXPIRE", DatabasePrefix+":datacap:"+id, 3600)
} else {
count, err = redis.Int(conn.Do("INCRBY", DatabasePrefix+":queriescap:"+id, 1))
conn.Do("EXPIRE", DatabasePrefix+":queriescap:"+id, 3600)
}
if err != nil {
log.Printf("Error while setting ratelimit: %v\n", err)
return ErrorGeneric
}
// Check
if isData {
if count > DataCap {
return ErrorRateLimit
}
} else {
if count > QueriesCap {
return ErrorRateLimit
}
}
return nil
}
func redisPing() error {
// Get a Connection
conn := pool.Get()
defer conn.Close()
// Attempt to ping
output, err := redis.String(conn.Do("PING"))
if err == nil && output != "PONG" {
err = ErrorPing
}
if err == nil && output == "PONG" {
log.Println("[DB] Received PONG")
}
return err
}