-
Notifications
You must be signed in to change notification settings - Fork 4
/
utils.go
388 lines (352 loc) · 9.58 KB
/
utils.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
/*===----------- utils.go - tracking utility written in go -------------===
*
*
* This file is licensed under the Apache 2 License. See LICENSE for details.
*
* Copyright (c) 2018 Andrew Grosser. All Rights Reserved.
*
* `...
* yNMMh`
* dMMMh`
* dMMMh`
* dMMMh`
* dMMMd`
* dMMMm.
* dMMMm.
* dMMMm. /hdy.
* ohs+` yMMMd. yMMM-
* .mMMm. yMMMm. oMMM/
* :MMMd` sMMMN. oMMMo
* +MMMd` oMMMN. oMMMy
* sMMMd` /MMMN. oMMMh
* sMMMd` /MMMN- oMMMd
* oMMMd` :NMMM- oMMMd
* /MMMd` -NMMM- oMMMm
* :MMMd` .mMMM- oMMMm`
* -NMMm. `mMMM: oMMMm`
* .mMMm. dMMM/ +MMMm`
* `hMMm. hMMM/ /MMMm`
* yMMm. yMMM/ /MMMm`
* oMMm. oMMMo -MMMN.
* +MMm. +MMMo .MMMN-
* +MMm. /MMMo .NMMN-
* ` +MMm. -MMMs .mMMN: `.-.
* /hys:` +MMN- -NMMy `hMMN: .yNNy
* :NMMMy` sMMM/ .NMMy yMMM+-dMMMo
* +NMMMh-hMMMo .mMMy +MMMmNMMMh`
* /dMMMNNMMMs .dMMd -MMMMMNm+`
* .+mMMMMMN: .mMMd `NMNmh/`
* `/yhhy: `dMMd /+:`
* `hMMm`
* `hMMm.
* .mMMm:
* :MMMd-
* -NMMh.
* ./:.
*
*===----------------------------------------------------------------------===
*/
package main
import (
"archive/zip"
"crypto/sha1"
"crypto/sha256"
"encoding/base64"
"fmt"
"hash/fnv"
"io"
"net"
"net/http"
"os"
"os/user"
"path/filepath"
"strings"
"time"
"github.com/gocql/gocql"
"github.com/google/uuid"
)
// //////////////////////////////////////
// hash
// //////////////////////////////////////
func hash(s string) uint32 {
h := fnv.New32a()
h.Write([]byte(s))
return h.Sum32()
}
func sha(s string) string {
hasher := sha1.New()
hasher.Write([]byte(s))
return base64.URLEncoding.EncodeToString(hasher.Sum(nil))
}
func shasum256(s string) string {
hasher := sha256.New()
hasher.Write([]byte(s))
return fmt.Sprintf("%x", hasher.Sum(nil))
}
// //////////////////////////////////////
// filterUrl
// matchGroup is a 1 indexed array (0 is default last)
// returns last match if no group, or group
// //////////////////////////////////////
func filterUrl(c *Configuration, s *string, matchGroup *int) error {
matches := regexFilterUrl.FindStringSubmatch(*s)
mi := len(matches)
if matchGroup == nil || *matchGroup == 0 {
//Take the last one by default
if mi > 0 {
*s = matches[mi-1]
return nil
}
} else {
if mi > *matchGroup {
*s = matches[*matchGroup]
return nil
}
}
//Fallback
filterUrlAppendix(s)
return fmt.Errorf("Mismatch Regex (Url Filter)")
}
func filterUrlAppendix(s *string) error {
if s != nil {
i := strings.Index(*s, "?")
if i > -1 {
*s = (*s)[:i]
}
}
return nil
}
func filterUrlPrefix(s *string) error {
if s != nil {
*s = strings.ToLower(*s)
i := strings.Index(*s, "https://")
if i > -1 {
*s = (*s)[i+6:]
return nil
}
i = strings.Index(*s, "http://")
if i > -1 {
*s = (*s)[i+5:]
}
}
return nil
}
func cleanInterfaceString(i interface{}) error {
s := &i
if temp, ok := (*s).(string); ok {
*s = strings.ToLower(strings.TrimSpace(temp))
}
return nil
}
func ensureInterfaceString(i interface{}) error {
s := &i
if _, ok := (*s).(string); !ok {
if s != nil {
*s = fmt.Sprintf("%v", *s)
}
}
return nil
}
func cleanString(s *string) error {
if s != nil && *s != "" {
*s = strings.ToLower(strings.TrimSpace(*s))
}
return nil
}
func upperString(s *string) error {
if s != nil && *s != "" {
*s = strings.ToUpper(strings.TrimSpace(*s))
}
return nil
}
func FixedLengthNumberString(length int, str string) string {
verb := fmt.Sprintf("%%%d.%ds", length, length)
return strings.Replace(fmt.Sprintf(verb, str), " ", "0", -1)
}
// //////////////////////////////////////
// cacheDir in /tmp for SSL
// //////////////////////////////////////
func cacheDir() (dir string) {
if u, _ := user.Current(); u != nil {
dir = filepath.Join(os.TempDir(), "cache-golang-autocert-"+u.Username)
//dir = filepath.Join(".", "cache-golang-autocert-"+u.Username)
fmt.Println("Saving cache-go-lang-autocert-u.username to: ", dir)
if err := os.MkdirAll(dir, 0700); err == nil {
return dir
}
}
return ""
}
func getIP(r *http.Request) string {
ip := r.Header.Get("X-Forwarded-For")
if ip == "" {
var err error
if ip, _, err = net.SplitHostPort(r.RemoteAddr); err != nil {
ip = r.RemoteAddr
}
}
return cleanIP(ip)
}
func cleanIP(ip string) string {
ipa := strings.Split(ip, ",")
for i := len(ipa) - 1; i > -1; i-- {
ipa[i] = strings.TrimSpace(ipa[i])
if ipp := net.ParseIP(ipa[i]); ipp != nil {
return ipp.String()
}
}
return ""
}
func getHost(r *http.Request) string {
if addr, _, err := net.SplitHostPort(r.Host); err != nil {
return r.Host
} else {
return addr
}
}
func Unzip(src, dest string) error {
r, err := zip.OpenReader(src)
if err != nil {
return err
}
defer func() {
if err := r.Close(); err != nil {
panic(err)
}
}()
os.MkdirAll(dest, 0755)
// Closure to address file descriptors issue with all the deferred .Close() methods
extractAndWriteFile := func(f *zip.File) error {
rc, err := f.Open()
if err != nil {
return err
}
defer func() {
if err := rc.Close(); err != nil {
panic(err)
}
}()
path := filepath.Join(dest, f.Name)
if f.FileInfo().IsDir() {
os.MkdirAll(path, f.Mode())
} else {
os.MkdirAll(filepath.Dir(path), f.Mode())
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
defer func() {
if err := f.Close(); err != nil {
panic(err)
}
}()
_, err = io.Copy(f, rc)
if err != nil {
return err
}
}
return nil
}
for _, f := range r.File {
err := extractAndWriteFile(f)
if err != nil {
return err
}
}
return nil
}
func checkRowExpired(row map[string]interface{}, meta *gocql.TableMetadata, p Prune, pruneSkipToTimestamp int64) (bool, *time.Time) {
var created *time.Time
expired := false
if ctemp1, ok := row["created"]; ok {
if ctemp2, okp := ctemp1.(time.Time); okp {
created = &ctemp2
}
}
if meta != nil && len(meta.PartitionKey) == 1 {
if tuuid, tok := row[meta.PartitionKey[0].Name]; tok {
if uuid, ok := tuuid.(gocql.UUID); ok {
if uuid.Version() == 1 {
c := uuid.Time()
if c.Before(*created) {
created = &c
}
}
}
}
}
if created != nil {
if created.Before(time.Unix(pruneSkipToTimestamp, 0)) {
return false, created
}
expired = (*created).Add(time.Second * time.Duration(p.TTL)).Before(time.Now().UTC())
} else {
expired = true
}
// if fmt.Sprintf("%T", row["cflags"]) != "int64" {
// err = fmt.Errorf("Table %s not supported for pruning (bad cflags type)", p.Table)
// goto tablefailed
// }
var ignore int64
for _, icflag := range p.CFlagsIgnore {
ignore += icflag
}
if cftemp1, ok := row["cflags"]; ok {
if cftemp2, okp := cftemp1.(int64); okp {
if cftemp2&ignore > 0 {
expired = false
}
}
}
return expired, created
}
func checkIdExpired(uuid *gocql.UUID, ttl int) bool {
//If the id is incorrectly formatted expire it
if uuid == nil || uuid.Version() != 1 {
return true
}
created := uuid.Time()
return created.Add(time.Second * time.Duration(ttl)).Before(time.Now().UTC())
}
func checkUUIDExpired(uuid *uuid.UUID, ttl int) bool {
//If the id is incorrectly formatted expire it
if uuid == nil || uuid.Version() != 1 {
return true
}
// Convert UUID timestamp to time.Time
// UUID v1 timestamp is 100-nanosecond intervals since UUID epoch (15 Oct 1582)
uuidTime := time.Unix(0, int64((uuid.Time()-0x01B21DD213814000)*100))
return uuidTime.Add(time.Second * time.Duration(ttl)).Before(time.Now().UTC())
}
func SetValueInJSON(iface interface{}, path string, value interface{}) interface{} {
m := iface.(map[string]interface{})
split := strings.Split(path, ".")
for k, v := range m {
if strings.EqualFold(k, split[0]) {
if len(split) == 1 {
m[k] = value
return m
}
switch v.(type) {
case map[string]interface{}:
return SetValueInJSON(v, strings.Join(split[1:], "."), value)
default:
return m
}
}
}
// path not found -> create
if len(split) == 1 {
m[split[0]] = value
} else {
newMap := make(map[string]interface{})
newMap[split[len(split)-1]] = value
for i := len(split) - 2; i > 0; i-- {
mTmp := make(map[string]interface{})
mTmp[split[i]] = newMap
newMap = mTmp
}
m[split[0]] = newMap
}
return m
}