-
Notifications
You must be signed in to change notification settings - Fork 19
/
util.go
679 lines (612 loc) · 18.2 KB
/
util.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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
package main
import (
"bytes"
"crypto/md5"
"crypto/sha1"
"database/sql"
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"time"
"github.com/nranchev/go-libGeoIP"
"golang.org/x/crypto/bcrypt"
)
var (
nullTime, _ = time.Parse("2006-01-02 15:04:05", "0000-00-00 00:00:00")
errEmptyDurationString = errors.New("Empty Duration string")
errInvalidDurationString = errors.New("Invalid Duration string")
durationRegexp = regexp.MustCompile(`^((\d+)\s?ye?a?r?s?)?\s?((\d+)\s?mon?t?h?s?)?\s?((\d+)\s?we?e?k?s?)?\s?((\d+)\s?da?y?s?)?\s?((\d+)\s?ho?u?r?s?)?\s?((\d+)\s?mi?n?u?t?e?s?)?\s?((\d+)\s?s?e?c?o?n?d?s?)?$`)
)
const (
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 abcdefghijklmnopqrstuvwxyz~!@#$%%^&*()_+{}[]-=:\"\\/?.>,<;:'"
)
func arrToString(arr []string) string {
var out string
for i, val := range arr {
out += val
if i < len(arr)-1 {
out += ","
}
}
return out
}
func benchmarkTimer(name string, givenTime time.Time, starting bool) (returnTime time.Time) {
if starting {
// starting benchmark test
println(2, "Starting benchmark \""+name+"\"")
returnTime = givenTime
} else {
// benchmark is finished, print the duration
// convert nanoseconds to a decimal seconds
printf(2, "benchmark %s completed in %f seconds\n", name, time.Since(givenTime).Seconds())
returnTime = time.Now() // we don't really need this, but we have to return something
}
return
}
func md5Sum(str string) string {
hash := md5.New()
io.WriteString(hash, str)
return fmt.Sprintf("%x", hash.Sum(nil))
}
func sha1Sum(str string) string {
hash := sha1.New()
io.WriteString(hash, str)
return fmt.Sprintf("%x", hash.Sum(nil))
}
func bcryptSum(str string) string {
digest, err := bcrypt.GenerateFromPassword([]byte(str), 4)
if err == nil {
return string(digest)
}
return ""
}
func byteByByteReplace(input, from, to string) string {
if len(from) != len(to) {
return ""
}
for i := 0; i < len(from); i++ {
input = strings.Replace(input, from[i:i+1], to[i:i+1], -1)
}
return input
}
// for easier defer cleaning
func closeFile(file *os.File) {
if file != nil {
_ = file.Close()
}
}
func closeRows(rows *sql.Rows) {
if rows != nil {
_ = rows.Close()
}
}
func closeStatement(stmt *sql.Stmt) {
if stmt != nil {
_ = stmt.Close()
}
}
/*
* Deletes files in a folder (root) that match a given regular expression.
* Returns the number of files that were deleted, and any error encountered.
*/
func deleteMatchingFiles(root, match string) (filesDeleted int, err error) {
files, err := ioutil.ReadDir(root)
if err != nil {
return 0, err
}
for _, f := range files {
match, _ := regexp.MatchString(match, f.Name())
if match {
os.Remove(filepath.Join(root, f.Name()))
filesDeleted++
}
}
return filesDeleted, err
}
// escapeString and escapeQuotes copied from github.com/ziutek/mymysql/native/codecs.go
func escapeString(txt string) string {
var (
esc string
buf bytes.Buffer
)
last := 0
for ii, bb := range txt {
switch bb {
case 0:
esc = `\0`
case '\n':
esc = `\n`
case '\r':
esc = `\r`
case '\\':
esc = `\\`
case '\'':
esc = `\'`
case '"':
esc = `\"`
case '\032':
esc = `\Z`
default:
continue
}
io.WriteString(&buf, txt[last:ii])
io.WriteString(&buf, esc)
last = ii + 1
}
io.WriteString(&buf, txt[last:])
return buf.String()
}
func escapeQuotes(txt string) string {
var buf bytes.Buffer
last := 0
for ii, bb := range txt {
if bb == '\'' {
io.WriteString(&buf, txt[last:ii])
io.WriteString(&buf, `''`)
last = ii + 1
}
}
io.WriteString(&buf, txt[last:])
return buf.String()
}
// getBoardArr performs a query against the database, and returns an array of BoardsTables along with an error value.
// If specified, the string where is added to the query, prefaced by WHERE. An example valid value is where = "id = 1".
func getBoardArr(parameterList map[string]interface{}, extra string) (boards []BoardsTable, err error) {
queryString := "SELECT * FROM `" + config.DBprefix + "boards` "
numKeys := len(parameterList)
var parameterValues []interface{}
if numKeys > 0 {
queryString += "WHERE "
}
for key, value := range parameterList {
queryString += fmt.Sprintf("`%s` = ? AND ", key)
parameterValues = append(parameterValues, value)
}
// Find and remove any trailing instances of "AND "
if numKeys > 0 {
queryString = queryString[:len(queryString)-4]
}
queryString += fmt.Sprintf(" %s ORDER BY `order`", extra)
rows, err := querySQL(queryString, parameterValues...)
defer closeRows(rows)
if err != nil {
handleError(0, "error getting board list: %s", customError(err))
return
}
// For each row in the results from the database, populate a new BoardsTable instance,
// then append it to the boards array we are going to return
for rows.Next() {
board := new(BoardsTable)
if err = rows.Scan(
&board.ID,
&board.Order,
&board.Dir,
&board.Type,
&board.UploadType,
&board.Title,
&board.Subtitle,
&board.Description,
&board.Section,
&board.MaxImageSize,
&board.MaxPages,
&board.Locale,
&board.DefaultStyle,
&board.Locked,
&board.CreatedOn,
&board.Anonymous,
&board.ForcedAnon,
&board.MaxAge,
&board.AutosageAfter,
&board.NoImagesAfter,
&board.MaxMessageLength,
&board.EmbedsAllowed,
&board.RedirectToThread,
&board.RequireFile,
&board.EnableCatalog,
); err != nil {
handleError(0, customError(err))
return
}
boards = append(boards, *board)
}
return
}
func getBoardFromID(id int) (*BoardsTable, error) {
board := new(BoardsTable)
err := queryRowSQL(
"SELECT `order`,`dir`,`type`,`upload_type`,`title`,`subtitle`,`description`,`section`,"+
"`max_image_size`,`max_pages`,`locale`,`default_style`,`locked`,`created_on`,`anonymous`,`forced_anon`,`max_age`,"+
"`autosage_after`,`no_images_after`,`max_message_length`,`embeds_allowed`,`redirect_to_thread`,`require_file`,"+
"`enable_catalog` FROM `"+config.DBprefix+"boards` WHERE `id` = ?",
[]interface{}{id},
[]interface{}{
&board.Order, &board.Dir, &board.Type, &board.UploadType, &board.Title,
&board.Subtitle, &board.Description, &board.Section, &board.MaxImageSize,
&board.MaxPages, &board.Locale, &board.DefaultStyle, &board.Locked, &board.CreatedOn,
&board.Anonymous, &board.ForcedAnon, &board.MaxAge, &board.AutosageAfter,
&board.NoImagesAfter, &board.MaxMessageLength, &board.EmbedsAllowed,
&board.RedirectToThread, &board.RequireFile, &board.EnableCatalog,
},
)
board.ID = id
return board, err
}
// if parameterList is nil, ignore it and treat extra like a whole SQL query
func getPostArr(parameterList map[string]interface{}, extra string) (posts []PostTable, err error) {
queryString := "SELECT * FROM `" + config.DBprefix + "posts` "
numKeys := len(parameterList)
var parameterValues []interface{}
if numKeys > 0 {
queryString += "WHERE "
}
for key, value := range parameterList {
queryString += fmt.Sprintf("`%s` = ? AND ", key)
parameterValues = append(parameterValues, value)
}
// Find and remove any trailing instances of "AND "
if numKeys > 0 {
queryString = queryString[:len(queryString)-4]
}
queryString += " " + extra // " ORDER BY `order`"
rows, err := querySQL(queryString, parameterValues...)
defer closeRows(rows)
if err != nil {
handleError(1, customError(err))
return
}
// For each row in the results from the database, populate a new PostTable instance,
// then append it to the posts array we are going to return
for rows.Next() {
var post PostTable
if err = rows.Scan(&post.ID, &post.BoardID, &post.ParentID, &post.Name, &post.Tripcode,
&post.Email, &post.Subject, &post.MessageHTML, &post.MessageText, &post.Password, &post.Filename,
&post.FilenameOriginal, &post.FileChecksum, &post.Filesize, &post.ImageW,
&post.ImageH, &post.ThumbW, &post.ThumbH, &post.IP, &post.Tag, &post.Timestamp,
&post.Autosage, &post.PosterAuthority, &post.DeletedTimestamp, &post.Bumped,
&post.Stickied, &post.Locked, &post.Reviewed, &post.Sillytag,
); err != nil {
handleError(0, customError(err))
return
}
posts = append(posts, post)
}
return
}
// TODO: replace where with a map[string]interface{} like getBoardsArr()
func getSectionArr(where string) (sections []interface{}, err error) {
if where == "" {
where = "1"
}
rows, err := querySQL("SELECT * FROM `" + config.DBprefix + "sections` WHERE " + where + " ORDER BY `order`")
defer closeRows(rows)
if err != nil {
errorLog.Print(err.Error())
return
}
for rows.Next() {
section := new(BoardSectionsTable)
if err = rows.Scan(§ion.ID, §ion.Order, §ion.Hidden, §ion.Name, §ion.Abbreviation); err != nil {
handleError(1, customError(err))
return
}
sections = append(sections, section)
}
return
}
func getCountryCode(ip string) (string, error) {
if config.EnableGeoIP && config.GeoIPDBlocation != "" {
gi, err := libgeo.Load(config.GeoIPDBlocation)
if err != nil {
return "", err
}
return gi.GetLocationByIP(ip).CountryCode, nil
}
return "", nil
}
func generateSalt() string {
salt := make([]byte, 3)
salt[0] = chars[rand.Intn(86)]
salt[1] = chars[rand.Intn(86)]
salt[2] = chars[rand.Intn(86)]
return string(salt)
}
func getFileExtension(filename string) (extension string) {
if !strings.Contains(filename, ".") {
extension = ""
} else {
extension = filename[strings.LastIndex(filename, ".")+1:]
}
return
}
func getFormattedFilesize(size float64) string {
if size < 1000 {
return fmt.Sprintf("%dB", int(size))
} else if size <= 100000 {
return fmt.Sprintf("%fKB", size/1024)
} else if size <= 100000000 {
return fmt.Sprintf("%fMB", size/1024.0/1024.0)
}
return fmt.Sprintf("%0.2fGB", size/1024.0/1024.0/1024.0)
}
// returns the filename, line number, and function where getMetaInfo() is called
// stackOffset increases/decreases which item on the stack is referenced.
// see documentation for runtime.Caller() for more info
func getMetaInfo(stackOffset int) (string, int, string) {
pc, file, line, _ := runtime.Caller(1 + stackOffset)
return file, line, runtime.FuncForPC(pc).Name()
}
func customError(err error) string {
if err != nil {
file, line, _ := getMetaInfo(1)
return fmt.Sprintf("[ERROR] %s:%d: %s\n", file, line, err.Error())
}
return ""
}
func handleError(verbosity int, format string, a ...interface{}) string {
out := fmt.Sprintf(format, a...)
println(verbosity, out)
errorLog.Print(out)
return out
}
func humanReadableTime(t time.Time) string {
return t.Format(config.DateTimeFormat)
}
func getThumbnailPath(thumbType string, img string) string {
filetype := strings.ToLower(img[strings.LastIndex(img, ".")+1:])
if filetype == "gif" || filetype == "webm" {
filetype = "jpg"
}
index := strings.LastIndex(img, ".")
if index < 0 || index > len(img) {
return ""
}
thumbSuffix := "t." + filetype
if thumbType == "catalog" {
thumbSuffix = "c." + filetype
}
return img[0:index] + thumbSuffix
}
// paginate returns a 2d array of a specified interface from a 1d array passed in,
// with a specified number of values per array in the 2d array.
// interface_length is the number of interfaces per array in the 2d array (e.g, threads per page)
// interf is the array of interfaces to be split up.
func paginate(interfaceLength int, interf []interface{}) [][]interface{} {
// paginated_interfaces = the finished interface array
// num_arrays = the current number of arrays (before remainder overflow)
// interfaces_remaining = if greater than 0, these are the remaining interfaces
// that will be added to the super-interface
var paginatedInterfaces [][]interface{}
numArrays := len(interf) / interfaceLength
interfacesRemaining := len(interf) % interfaceLength
currentInterface := 0
for l := 0; l < numArrays; l++ {
paginatedInterfaces = append(paginatedInterfaces,
interf[currentInterface:currentInterface+interfaceLength])
currentInterface += interfaceLength
}
if interfacesRemaining > 0 {
paginatedInterfaces = append(paginatedInterfaces, interf[len(interf)-interfacesRemaining:])
}
return paginatedInterfaces
}
func printf(v int, format string, a ...interface{}) {
if config.Verbosity >= v {
fmt.Printf(format, a...)
}
}
func println(v int, a ...interface{}) {
if config.Verbosity >= v {
fmt.Println(a...)
}
}
func resetBoardSectionArrays() {
// run when the board list needs to be changed (board/section is added, deleted, etc)
allBoards = nil
allSections = nil
allBoardsArr, _ := getBoardArr(nil, "")
for _, b := range allBoardsArr {
allBoards = append(allBoards, b)
}
allSectionsArr, _ := getSectionArr("")
allSections = append(allSections, allSectionsArr...)
}
func searchStrings(item string, arr []string, permissive bool) int {
for i, str := range arr {
if item == str {
return i
}
}
return -1
}
func bToI(b bool) int {
if b {
return 1
}
return 0
}
func bToA(b bool) string {
if b {
return "1"
}
return "0"
}
// Checks the validity of the Akismet API key given in the config file.
func checkAkismetAPIKey(key string) error {
if key == "" {
return fmt.Errorf("Blank key given, Akismet won't be used.")
}
resp, err := http.PostForm("https://rest.akismet.com/1.1/verify-key", url.Values{"key": {key}, "blog": {"http://" + config.SiteDomain}})
defer func() {
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
}()
if err != nil {
return err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if string(body) == "invalid" {
// This should disable the Akismet checks if the API key is not valid.
errmsg := "Akismet API key is invalid, Akismet spam protection will be disabled."
return fmt.Errorf(errmsg)
}
return nil
}
// Checks a given post for spam with Akismet. Only checks if Akismet API key is set.
func checkPostForSpam(userIP string, userAgent string, referrer string,
author string, email string, postContent string) string {
if config.AkismetAPIKey != "" {
client := &http.Client{}
data := url.Values{"blog": {"http://" + config.SiteDomain}, "user_ip": {userIP}, "user_agent": {userAgent}, "referrer": {referrer},
"comment_type": {"forum-post"}, "comment_author": {author}, "comment_author_email": {email},
"comment_content": {postContent}}
req, err := http.NewRequest("POST", "https://"+config.AkismetAPIKey+".rest.akismet.com/1.1/comment-check",
strings.NewReader(data.Encode()))
if err != nil {
handleError(1, err.Error())
return "other_failure"
}
req.Header.Set("User-Agent", "gochan/1.0 | Akismet/0.1")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
handleError(1, err.Error())
return "other_failure"
}
defer func() {
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
}()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
handleError(1, err.Error())
return "other_failure"
}
errorLog.Print("Response from Akismet: " + string(body))
if string(body) == "true" {
if proTip, ok := resp.Header["X-akismet-pro-tip"]; ok && proTip[0] == "discard" {
return "discard"
}
return "spam"
} else if string(body) == "invalid" {
return "invalid"
} else if string(body) == "false" {
return "ham"
}
}
return "other_failure"
}
func makePostJSON(post PostTable, anonymous string) (postObj PostJSON) {
var filename string
var fileExt string
var origFilename string
// Separate out the extension from the filenames
if post.Filename != "deleted" && post.Filename != "" {
extStart := strings.LastIndex(post.Filename, ".")
fileExt = post.Filename[extStart:]
origExtStart := strings.LastIndex(post.FilenameOriginal, fileExt)
origFilename = post.FilenameOriginal[:origExtStart]
filename = post.Filename[:extStart]
}
postObj = PostJSON{ID: post.ID, ParentID: post.ParentID, Subject: post.Subject, Message: post.MessageHTML,
Name: post.Name, Timestamp: post.Timestamp.Unix(), Bumped: post.Bumped.Unix(),
ThumbWidth: post.ThumbW, ThumbHeight: post.ThumbH, ImageWidth: post.ImageW, ImageHeight: post.ImageH,
FileSize: post.Filesize, OrigFilename: origFilename, Extension: fileExt, Filename: filename, FileChecksum: post.FileChecksum}
// Handle Anonymous
if post.Name == "" {
postObj.Name = anonymous
}
// If we have a Tripcode, prepend a !
if post.Tripcode != "" {
postObj.Tripcode = "!" + post.Tripcode
}
return
}
func limitArraySize(arr []string, maxSize int) []string {
if maxSize > len(arr)-1 || maxSize < 0 {
return arr
}
return arr[:maxSize]
}
func numReplies(boardid, threadid int) int {
var num int
if err := queryRowSQL("SELECT COUNT(*) FROM `"+config.DBprefix+"posts` WHERE `boardid` = ? AND `parentid` = ?",
[]interface{}{boardid, threadid}, []interface{}{&num},
); err != nil {
return 0
}
return num
}
func ipMatch(newIP, existingIP string) bool {
if newIP == existingIP {
// both are single IPs and are the same
return true
}
wildcardIndex := strings.Index(existingIP, "*")
if wildcardIndex < 0 {
// single (or invalid) and they don't match
return false
}
ipRegexStr := existingIP[0:wildcardIndex]
ipRegexStr = strings.Replace(ipRegexStr, ".", "\\.", -1) + ".*"
ipRegex, err := regexp.Compile(ipRegexStr)
if err != nil {
// this shouldn't happen unless you enter an invalid IP in the db
return false
}
return ipRegex.MatchString(newIP)
}
// based on TinyBoard's parse_time function
func parseDurationString(str string) (time.Duration, error) {
if str == "" {
return 0, errEmptyDurationString
}
matches := durationRegexp.FindAllStringSubmatch(str, -1)
if len(matches) == 0 {
return 0, errInvalidDurationString
}
var expire int
if matches[0][2] != "" {
years, _ := strconv.Atoi(matches[0][2])
expire += years * 60 * 60 * 24 * 365
}
if matches[0][4] != "" {
months, _ := strconv.Atoi(matches[0][4])
expire += months * 60 * 60 * 24 * 30
}
if matches[0][6] != "" {
weeks, _ := strconv.Atoi(matches[0][6])
expire += weeks * 60 * 60 * 24 * 7
}
if matches[0][8] != "" {
days, _ := strconv.Atoi(matches[0][8])
expire += days * 60 * 60 * 24
}
if matches[0][10] != "" {
hours, _ := strconv.Atoi(matches[0][10])
expire += hours * 60 * 60
}
if matches[0][12] != "" {
minutes, _ := strconv.Atoi(matches[0][12])
expire += minutes * 60
}
if matches[0][14] != "" {
seconds, _ := strconv.Atoi(matches[0][14])
expire += seconds
}
return time.ParseDuration(strconv.Itoa(expire) + "s")
}