-
Notifications
You must be signed in to change notification settings - Fork 43
/
str_utils.go
1413 lines (1251 loc) · 29.4 KB
/
str_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
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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package utils
import (
"bufio"
"bytes"
"context"
"fmt"
"github.com/yaklang/yaklang/common/go-funk"
"github.com/yaklang/yaklang/common/log"
"io"
"io/ioutil"
"math/rand"
"net"
"net/http"
"net/url"
"path"
"reflect"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/ReneKroon/ttlcache"
"github.com/davecgh/go-spew/spew"
"github.com/gobwas/glob"
"github.com/miekg/dns"
"github.com/pkg/errors"
"github.com/projectdiscovery/retryabledns"
"github.com/projectdiscovery/retryabledns/hostsfile"
)
func ExtractStrContextByKeyword(raw []byte, res []string) []string {
rawStrContent := string(raw)
var details []string
for _, keyword := range res {
if index := strings.Index(rawStrContent, keyword); index > 0 {
info := ""
end := index + len(keyword) + 512
if index <= 512 {
info += rawStrContent[:index]
} else {
info += rawStrContent[index-512 : index+len(keyword)]
}
if end >= len(rawStrContent) {
info += rawStrContent[index:]
} else {
info += rawStrContent[index:end]
}
details = RemoveRepeatStringSlice(append(details, EscapeInvalidUTF8Byte([]byte(info))))
}
}
return details
}
func StringBefore(value string, a string) string {
pos := strings.Index(value, a)
if pos == -1 {
return ""
}
return value[0:pos]
}
func StringAfter(value string, a string) string {
pos := strings.Index(value, a)
if pos == -1 {
return ""
}
adjustedPos := pos + len(a)
if adjustedPos >= len(value) {
return ""
}
return value[adjustedPos:]
}
func StringSliceContainsAll(o []string, elements ...string) bool {
for _, e := range elements {
if !StringArrayContains(o, e) {
return false
}
}
return true
}
// 元素去重
func RemoveRepeatStringSlice(slc []string) []string {
if len(slc) < 1024 {
return RemoveRepeatStringSliceByLoop(slc)
} else {
return RemoveRepeatStringSliceByMap(slc)
}
}
// 元素去重
func RemoveRepeatUintSlice(slc []uint) []uint {
if len(slc) < 1024 {
return RemoveRepeatUintSliceByLoop(slc)
} else {
return RemoveRepeatUintSliceByMap(slc)
}
}
func RemoveRepeatStringSliceByLoop(slc []string) []string {
result := []string{}
for i := range slc {
flag := true
for j := range result {
if slc[i] == result[j] {
flag = false
break
}
}
if flag {
result = append(result, slc[i])
}
}
return result
}
func RemoveRepeatStringSliceByMap(slc []string) []string {
result := []string{}
tempMap := map[string]byte{}
for _, e := range slc {
l := len(tempMap)
tempMap[e] = 0
if len(tempMap) != l {
result = append(result, e)
}
}
return result
}
func RemoveRepeatUintSliceByLoop(slc []uint) []uint {
result := []uint{}
for i := range slc {
flag := true
for j := range result {
if slc[i] == result[j] {
flag = false
break
}
}
if flag {
result = append(result, slc[i])
}
}
return result
}
func RemoveRepeatUintSliceByMap(slc []uint) []uint {
result := []uint{}
tempMap := map[uint]byte{}
for _, e := range slc {
l := len(tempMap)
tempMap[e] = 0
if len(tempMap) != l {
result = append(result, e)
}
}
return result
}
func StringArrayContains(array []string, element string) bool {
for _, s := range array {
if element == s {
return true
}
}
return false
}
func HTTPPacketIsLargerThanMaxContentLength(res interface{}, maxLength int) bool {
var length int
switch ret := res.(type) {
case *http.Response:
length, _ = strconv.Atoi(ret.Header.Get("Content-Length"))
case *http.Request:
length, _ = strconv.Atoi(ret.Header.Get("Content-Length"))
}
if length > maxLength && maxLength > 0 {
log.Infof("allow rsp/req: %p's content-length: %v passed for limit content-length", res, length)
return true
}
return false
}
func StringHasPrefix(s string, prefix []string) bool {
for _, x := range prefix {
if strings.HasPrefix(strings.ToLower(s), strings.ToLower(x)) {
return true
}
}
return false
}
func StringGlobArrayContains(array []string, element string) bool {
var globs []glob.Glob
var strList []string
for _, r := range array {
rule, err := glob.Compile(r)
if err != nil {
strList = append(strList, r)
continue
}
globs = append(globs, rule)
}
for _, s := range array {
if element == s {
return true
}
}
for _, g := range globs {
if g.Match(element) {
return true
}
}
return false
}
func StringArrayIndex(array []string, element string) int {
for index, s := range array {
if element == s {
return index
}
}
return -1
}
func StringOr(s ...string) string {
for _, i := range s {
if i != "" {
return i
}
}
return ""
}
func IntLargerZeroOr(s ...int) int {
for _, i := range s {
if i > 0 {
return i
}
}
return 0
}
func StringArrayFilterEmpty(array []string) []string {
var ret []string
for _, a := range array {
if a == "" {
continue
}
ret = append(ret, a)
}
return ret
}
func StringArrayMerge(t ...[]string) []string {
m := map[string]interface{}{}
for _, ta := range t {
for _, i := range ta {
m[i] = false
}
}
var n []string
for k, _ := range m {
n = append(n, k)
}
return n
}
func StringSplitAndStrip(raw string, sep string) []string {
var l = []string{}
for _, v := range strings.Split(raw, sep) {
s := strings.TrimSpace(v)
if s != "" {
l = append(l, s)
}
}
return l
}
func BytesStripUntil(raw []byte, s byte) []byte {
for end := len(raw); end > 0; end-- {
c_index := end - 1
if raw[c_index] == s {
return raw[:c_index]
}
}
return []byte{}
}
func ExtractRawHeadersFromRequest(req *http.Request) string {
header := []string{}
header = append(header, fmt.Sprintf("%s %s %s", req.Method, req.URL.Path, req.Proto))
for headerName, headerValues := range req.Header {
for _, value := range headerValues {
header = append(header, fmt.Sprintf("%s: %s", headerName, value))
}
}
header = append(header, "")
return strings.Join(header, "\r\n")
}
func ExtractRawHeadersFromResponse(rsp *http.Response) string {
header := []string{}
header = append(header, fmt.Sprintf("%s %s", rsp.Proto, rsp.Status))
for headerName, headerValues := range rsp.Header {
for _, value := range headerValues {
header = append(header, fmt.Sprintf("%s: %s", headerName, value))
}
}
header = append(header, "")
return strings.Join(header, "\r\n")
}
func StringToAsciiBytes(s string) []byte {
t := make([]byte, utf8.RuneCountInString(s))
i := 0
for _, r := range s {
t[i] = byte(r)
i++
}
return t
}
func AsciiBytesToRegexpMatchedRunes(in []byte) []rune {
result := make([]rune, len(in))
for i, b := range in {
result[i] = rune(b)
}
return result
}
func AsciiBytesToRegexpMatchedString(in []byte) string {
return string(AsciiBytesToRegexpMatchedRunes(in))
}
func stripPort(hostport string) string {
colon := strings.IndexByte(hostport, ':')
if colon == -1 {
return hostport
}
if i := strings.IndexByte(hostport, ']'); i != -1 {
return strings.TrimPrefix(hostport[:i], "[")
}
return hostport[:colon]
}
func portOnly(hostport string) string {
colon := strings.IndexByte(hostport, ':')
if colon == -1 {
return ""
}
if i := strings.Index(hostport, "]:"); i != -1 {
return hostport[i+len("]:"):]
}
if strings.Contains(hostport, "]") {
return ""
}
return hostport[colon+len(":"):]
}
var (
dnsTtlCache = ttlcache.NewCache()
)
func GetFirstIPByDnsWithCache(domain string, timeout time.Duration, dnsServers ...string) string {
data, ok := dnsTtlCache.Get(domain)
if ok {
if raw, _ := data.(string); raw != "" && !IsLoopback(raw) {
dnsTtlCache.SetWithTTL(domain, raw, 30*time.Second)
return raw
}
}
var count = 0
for {
count++
r, err := GetFirstIPFromHostWithTimeoutE(timeout, domain, dnsServers)
if err != nil {
switch ret := err.(type) {
case *net.DNSError:
if !ret.Temporary() {
// not a temporary error, return
return ""
}
}
log.Errorf("get ip from host %s error: %s", domain, err.Error())
}
if r == "" {
if count >= 5 {
return ""
}
continue
}
dnsTtlCache.SetWithTTL(domain, r, 30*time.Second)
return r
}
}
func InterfaceToBytes(i interface{}) (result []byte) {
var bytes []byte
defer func() {
if err := recover(); err != nil {
result = []byte(fmt.Sprintf("%v", i))
}
}()
if i == nil {
return []byte{}
}
switch s := i.(type) {
case nil:
return []byte{}
case string:
bytes = []byte(s)
case []byte:
bytes = s[0:]
case bool:
bytes = []byte(strconv.FormatBool(s))
case float64:
return []byte(strconv.FormatFloat(s, 'f', -1, 64))
case float32:
return []byte(strconv.FormatFloat(float64(s), 'f', -1, 32))
case int:
return []byte(strconv.Itoa(s))
case int64:
return []byte(strconv.FormatInt(s, 10))
case int32:
return []byte(strconv.Itoa(int(s)))
case int16:
return []byte(strconv.FormatInt(int64(s), 10))
case int8:
return []byte(strconv.FormatInt(int64(s), 10))
case uint:
return []byte(strconv.FormatUint(uint64(s), 10))
case uint64:
return []byte(strconv.FormatUint(s, 10))
case uint32:
return []byte(strconv.FormatUint(uint64(s), 10))
case uint16:
return []byte(strconv.FormatUint(uint64(s), 10))
case uint8:
return []byte(strconv.FormatUint(uint64(s), 10))
case fmt.Stringer:
return []byte(s.String())
case error:
return []byte(s.Error())
//case io.Reader:
// if ret != nil && ret.Read != nil {
// bytes, _ = ioutil.ReadAll(ret)
// return bytes
// }
// return []byte(fmt.Sprintf("%v", i))
default:
bytes = []byte(fmt.Sprintf("%v", i))
}
return bytes
}
func InterfaceToString(i interface{}) string {
return string(InterfaceToBytes(i))
}
// Reverse the string
func StringReverse(s string) string {
n := 0
runeRet := make([]rune, len(s))
for _, r := range s {
runeRet[n] = r
n++
}
runeRet = runeRet[0:n]
for i := 0; i < n/2; i++ {
runeRet[i], runeRet[n-1-i] = runeRet[n-1-i], runeRet[i]
}
return string(runeRet)
}
func InterfaceToQuotedString(i interface{}) string {
packetRawStr := InterfaceToString(i)
if packetRawStr != "" {
if strings.HasPrefix(packetRawStr, `"`) && strings.HasSuffix(packetRawStr, `"`) {
raw, _ := strconv.Unquote(packetRawStr)
if raw != "" {
return packetRawStr
}
}
}
return strconv.Quote(packetRawStr)
}
func Int64SliceToIntSlice(i []int64) []int {
var result = make([]int, len(i))
for _, v := range i {
result = append(result, int(v))
}
return result
}
func IntSliceToInt64Slice(i []int) []int64 {
var result = make([]int64, len(i))
for _, v := range i {
result = append(result, int64(v))
}
return result
}
func InterfaceToStringSlice(i interface{}) []string {
var result []string
defer func() {
if err := recover(); err != nil {
log.Errorf("str.ToStringSlice failed: %s", err)
spew.Dump(i)
PrintCurrentGoroutineRuntimeStack()
}
}()
if i == nil {
return nil
}
va := reflect.ValueOf(i)
switch reflect.TypeOf(i).Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < va.Len(); i++ {
result = append(result, InterfaceToString(va.Index(i).Interface()))
}
default:
result = append(result, InterfaceToString(i))
}
return result
}
func InterfaceToBytesSlice(i interface{}) [][]byte {
var result [][]byte
defer func() {
if err := recover(); err != nil {
log.Errorf("str.ToBytesSlice failed: %s", err)
}
}()
va := reflect.ValueOf(i)
switch reflect.TypeOf(i).Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < va.Len(); i++ {
result = append(result, InterfaceToBytes(va.Index(i).Interface()))
}
default:
result = append(result, InterfaceToBytes(i))
}
return result
}
func InterfaceToMap(i interface{}) map[string][]string {
var finalResult = make(map[string][]string)
var res = make(map[string]interface{})
switch ret := i.(type) {
case map[string]interface{}:
res = ret
case map[string]string:
for k, v := range ret {
res[k] = v
}
case map[string][]string:
for k, v := range ret {
res[k] = v
}
default:
if reflect.TypeOf(ret).Kind() == reflect.Map {
spew.Dump(ret)
value := reflect.ValueOf(ret)
for _, keyValue := range value.MapKeys() {
finalResult[keyValue.String()] = []string{InterfaceToString(value.MapIndex(keyValue).Interface())}
}
return finalResult
}
finalResult["default"] = []string{fmt.Sprintf("%v", i)}
return finalResult
}
funk.ForEach(res, func(k string, v interface{}) {
finalResult[k] = []string{}
switch ret := v.(type) {
case []interface{}:
finalResult[k] = append(finalResult[k], funk.Map(ret, func(i interface{}) string {
return InterfaceToString(i)
}).([]string)...)
case []string:
finalResult[k] = append(finalResult[k], ret...)
default:
finalResult[k] = append(finalResult[k], InterfaceToString(ret))
}
})
return finalResult
}
func ParseStringUrlToWebsiteRootPath(s string) string {
ins, _ := ParseStringUrlToUrlInstance(s)
if ins == nil {
return s
}
ins.Path = "/"
ins.RawPath = "/"
ins.RawQuery = ""
return ins.String()
}
func ParseStringUrlToUrlInstance(s string) (*url.URL, error) {
return url.Parse(s)
}
func ParseStringToHostPort(raw string) (host string, port int, err error) {
if strings.Contains(raw, "://") {
urlObject, _ := url.Parse(raw)
if urlObject != nil {
// 处理 URL
portRaw := urlObject.Port()
portInt64, err := strconv.ParseInt(portRaw, 10, 32)
if err != nil || portInt64 <= 0 {
switch urlObject.Scheme {
case "http", "ws":
port = 80
case "https", "wss":
port = 443
}
} else {
port = int(portInt64)
}
host = urlObject.Hostname()
err = nil
return host, port, err
}
}
host = stripPort(raw)
portStr := portOnly(raw)
if len(portStr) <= 0 {
return "", 0, errors.Errorf("unknown port for [%s]", raw)
}
portStr = strings.TrimSpace(portStr)
portInt64, err := strconv.ParseInt(portStr, 10, 32)
if err != nil {
return "", 0, errors.Errorf("%s parse port(%s) failed: %s", raw, portStr, err)
}
port = int(portInt64)
err = nil
return
}
/*
https://baidu.com/abc a?key=value
https://baidu.com/abc/a?key=value => [X] https://baidu.com/abc/a%xxkey=value
[X] https://baidu.com/a?key=value
*/
func UrlJoin(origin string, paths ...string) (string, error) {
u, err := url.Parse(origin)
if err != nil {
return "", errors.Errorf("origin:[%s] is not a valid url: %s", origin, err)
}
var pathBuf bytes.Buffer
for index, p := range paths {
if index == 0 {
pathBuf.WriteString(p)
continue
}
if strings.HasPrefix(p, "?") {
pathBuf.WriteString(p)
} else {
pathBuf.WriteString("/" + p)
}
}
pathRaw := pathBuf.String()
var uri *url.URL
if strings.HasPrefix(pathRaw, "/") {
uri, err = url.ParseRequestURI(pathRaw)
if err != nil {
u.Path = pathRaw
return u.String(), nil
}
} else {
// 处理 URL 的情况
inputAsUrl, _ := url.Parse(pathRaw)
if inputAsUrl != nil && inputAsUrl.Scheme != "" {
return pathRaw, nil
}
// 不是 URL,并且 pathRaw 开头一定不是 /
// 那么就看 u.Path 结尾是不是 /
// r := path.Join(u.Path, pathRaw)
if !strings.HasSuffix(u.Path, "/") {
u.Path += "/"
}
// 移除 ./
PATHCLEAN:
for {
switch true {
case strings.HasPrefix(pathRaw, "./"):
pathRaw = pathRaw[2:]
continue
case strings.HasPrefix(pathRaw, "../"):
pathRaw = pathRaw[3:]
u.Path = path.Join(u.Path, "..")
if !strings.HasSuffix(u.Path, "/") {
u.Path += "/"
}
continue
default:
break PATHCLEAN
}
}
reqUri := u.Path + pathRaw
uri, err = url.ParseRequestURI(reqUri)
if err != nil {
u.Path = reqUri
return u.String(), nil
}
}
u.RawPath = uri.RawPath
u.Path = uri.Path
u.RawQuery = uri.RawQuery
return u.String(), nil
}
func ParseLines(raw string) chan string {
outC := make(chan string)
go func() {
defer close(outC)
for _, l := range strings.Split(raw, "\n") {
hl := strings.TrimSpace(l)
if hl == "" {
continue
}
outC <- hl
}
}()
return outC
}
func Atoi(i string) int {
raw, _ := strconv.Atoi(i)
return raw
}
func Atof(i string) float64 {
raw, _ := strconv.ParseFloat(i, 64)
return raw
}
func Atob(i string) bool {
raw, _ := strconv.ParseBool(i)
return raw
}
func CopyBytes(rsp []byte) []byte {
b := make([]byte, len(rsp))
copy(b, rsp)
return b
}
func CopyMapInterface(i map[string]interface{}) map[string]interface{} {
if i == nil {
return make(map[string]interface{})
}
m := make(map[string]interface{})
for k, v := range i {
m[k] = v
}
return m
}
func ByteCountDecimal(b int64) string {
const unit = 1000
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f%cB", float64(b)/float64(div), "kMGTPE"[exp])
}
func ByteCountBinary(b int64) string {
const unit = 1024
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f%ciB", float64(b)/float64(div), "KMGTPE"[exp])
}
// 每个单词首字母大写
func InitialCapitalizationEachWords(str string) string {
if len(str) < 1 {
return ""
}
words := strings.Split(str, " ")
result := []string{}
for _, w := range words {
w = strings.ToUpper(w)[:1] + w[1:]
result = append(result, w)
}
return strings.Join(result, " ")
}
func SliceGroup(origin []string, groupSize int) [][]string {
var (
result [][]string
)
var count int
var buffer []string
for _, i := range origin {
count++
buffer = append(buffer, i)
if count >= groupSize {
count = 0
result = append(result, buffer)
buffer = nil
}
}
if len(buffer) > 0 {
result = append(result, buffer)
}
return result
}
func DomainToIP(domain string, timeout time.Duration) []string {
if net.ParseIP(FixForParseIP(domain)) == nil {
// 不是 IP 尝试 dns 查询下
ctx, _ := context.WithTimeout(context.Background(), timeout)
rets, err := net.DefaultResolver.LookupIPAddr(ctx, domain)
if err != nil {
return nil
}
var addrs []string
for _, i := range rets {
addrs = append(addrs, i.String())
}
return addrs
} else {
return []string{domain}
}
}
var (
DefaultDNSClient = dns.Client{
Timeout: 5 * time.Second,
DialTimeout: 5 * time.Second,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
}
RetryableDNSClient = &retryabledns.Client{
TCPFallback: true,
}
DefaultDNSConn = dns.Dial
DefaultDNSServer = []string{
"223.5.5.5", // ali
"119.29.29.29", // tencent
"180.76.76.76", // baidu
"114.114.114.114", // dianxin
"1.1.1.1", // cf
"8.8.8.8",
}
)
func ToNsServer(server string) string {
// 如果 server 只是一个 IP 则需要把端口加上
ip := net.ParseIP(server)
if ip != nil {
server = ip.String() + ":53"
return server
}
// 这里肯定不是 IP/IP6
// 所以我们检测是否包含端口,如果不包含端口,则添加端口
if strings.Contains(server, ":") {
return server
}
for strings.HasSuffix(server, ".") {
server = server[:len(server)-1]
}
server += ":53"
return server
}
var hostsRecords map[string][]string
func init() {
raw, _ := hostsfile.ParseDefault()
if raw != nil {
hostsRecords = raw
}
}
func GetIPFromHostWithContextAndDNSServers(
timeout time.Duration, domain string, DNSServers []string, cb func(domain string) bool,
) error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
DNSClient := DefaultDNSClient
DNSClient.Timeout = timeout
DNSClient.DialTimeout = timeout
DNSClient.ReadTimeout = timeout
DNSClient.WriteTimeout = timeout
if strings.TrimSpace(domain) == "" {
return Error("empty domain input")
}
//ctx, cancel := context.WithCancel(ctx)
//defer cancel()
if cb == nil {
return Errorf("callback cannot be empty")
}
if records, ok := hostsRecords[domain]; ok {
for _, r := range records {
if cb(r) {
continue
} else {
return nil
}
}
}
var finalError error
nativeDNS := func() bool {
defer func() {
if err := recover(); err != nil {
log.Error(err)
}
}()
if domain == "" {
return false
}
ips, err := net.DefaultResolver.LookupIPAddr(ctx, strings.TrimRight(domain, "."))
if err != nil {
switch retErr := err.(type) {
case *net.DNSError:
if retErr.IsNotFound {
finalError = retErr
return false
}
default:
log.Errorf("default resolver parse failed: %s", err)
}
return false
}
for _, i := range ips {
if cb(i.String()) {
continue
} else {
return true
}
}
if len(ips) <= 0 {
return false
}
return true
}