-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidate.go
4372 lines (4208 loc) · 169 KB
/
validate.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 goip
import (
"math"
"math/big"
"strings"
"sync"
"sync/atomic"
"unicode"
"unsafe"
"github.com/pchchv/goip/address_error"
"github.com/pchchv/goip/address_string_param"
)
const (
longSize = 64
longHexDigits = longSize >> 2
longBinaryDigits = longSize
maxWildcards = ipv6Base85SingleSegmentDigitCount - 1 // 20 wildcards is equivalent to a base 85 address
maxHostLength = 253
maxLabelLength = 63
maxHostSegments = 127
macSingleSegmentDigitCount = 12
macDoubleSegmentDigitCount = 6
macExtendedSingleSegmentDigitCount = 16
macExtendedDoubleSegmentDigitCount = 10
ipv6SingleSegmentDigitCount = 32
ipv6BinarySingleSegmentDigitCount = 128
ipv4BinarySingleSegmentDigitCount = 32
ipv6Base85SingleSegmentDigitCount = 20
ipv4SingleSegmentOctalDigitCount = 11
)
var (
lowBitsVal uint64 = 0xffffffffffffffff
lowBitsMask = new(big.Int).SetUint64(lowBitsVal)
chars, extendedChars = createChars()
base85Powers = createBase85Powers()
maskCache = [3][IPv6BitCount + 1]*maskCreator{}
loopbackCache = newEmptyAddrCreator(defaultIPAddrParameters, NoZone)
macMaxTriple uint64 = (MACMaxValuePerSegment << uint64(MACBitsPerSegment*2)) | (MACMaxValuePerSegment << uint64(MACBitsPerSegment)) | MACMaxValuePerSegment
macMaxQuintuple = (macMaxTriple << uint64(MACBitsPerSegment*2)) | uint64(macMaxTriple>>uint64(MACBitsPerSegment))
maxValues = [5]uint64{0, IPv4MaxValuePerSegment, 0xffff, 0xffffff, 0xffffffff}
maxIPv4StringLen = [9][]int{ //indices are [radix / 2][additionalSegments], and we handle radices 8, 10, 16
{3, 6, 8, 11}, //no radix supplied we treat as octal, the longest
{8, 16, 24, 32}, // binary
{}, {},
{3, 6, 8, 11}, //octal: 0377, 0177777, 077777777, 037777777777
{IPv4SegmentMaxChars, 5, 8, 10}, //decimal: 255, 65535, 16777215, 4294967295
{}, {},
{2, 4, 6, 8}, //hex: 0xff, 0xffff, 0xffffff, 0xffffffff
}
// according to rfc 1035 or 952, a label must start with a letter, must end with a letter or digit, and must have in the middle a letter or digit or -
// rfc 1123 relaxed that to allow labels to start with a digit, section 2.1 has a discussion on this. It states that the highest level component name must be alphabetic - referring to .com or .net or whatever.
// furthermore, the underscore has become generally acceptable, as indicated in rfc 2181
// there is actually a distinction between host names and domain names. a host name is a specific type of domain name identifying hosts.
// hosts are not supposed to have the underscore.
//
// en.wikipedia.org/wiki/Domain_Name_System#Domain_name_syntax
// en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names
//
// max length is 63, cannot start or end with hyphen
// strictly speaking, the underscore is not allowed anywhere, but it seems that rule is sometimes broken
// also, underscores seem to be a part of dns names that are not part of host names, so we allow it here to be safe
//
// networkadminkb.com/KB/a156/windows-2003-dns-and-the-underscore.aspx
//
// It's a little confusing. rfc 2181 https://www.ietf.org/rfc/rfc2181.txt in section 11 on name syntax says that any chars are allowed in dns.
// However, it also says internet host names might have restrictions of their own, and this was defined in rfc 1035.
// rfc 1035 defines the restrictions on internet host names, in section 2.3.1 http://www.ietf.org/rfc/rfc1035.txt
//
// So we will follow rfc 1035 and in addition allow the underscore.
ipvFutureUppercase = byte(unicode.ToUpper(rune(IPvFuture)))
defaultEmptyHost = &parsedHost{}
defaultUncOpts = new(address_string_param.IPAddressStringParamsBuilder).
AllowIPv4(false).AllowEmpty(false).AllowMask(false).AllowPrefix(false).ToParams()
reverseDNSIPv4Opts = new(address_string_param.IPAddressStringParamsBuilder).
AllowIPv6(false).AllowEmpty(false).AllowMask(false).AllowPrefix(false).
GetIPv4AddressParamsBuilder().AllowInetAton(false).GetParentBuilder().ToParams()
reverseDNSIPv6Opts = new(address_string_param.IPAddressStringParamsBuilder).
AllowIPv4(false).AllowEmpty(false).AllowMask(false).AllowPrefix(false).
GetIPv6AddressParamsBuilder().AllowMixed(false).AllowZone(false).GetParentBuilder().ToParams()
//
// we need to initialize parsing package variables first before using them, so we put these at the bottom of this file
zeroIPAddressString = NewIPAddressString("")
ipv4MappedPrefix = NewIPAddressString("::ffff:0:0/96")
)
type strValidator struct{}
func (strValidator) validateMACAddressStr(fromString *MACAddressString, validationOptions address_string_param.MACAddressStringParams) (prov macAddressProvider, err address_error.AddressStringError) {
str := fromString.str
pa := parsedMACAddress{
originator: fromString,
macAddressParseData: macAddressParseData{addressParseData: addressParseData{str: str}},
params: validationOptions,
creationLock: &sync.Mutex{},
}
if err = validateMACAddress(validationOptions, str, 0, len(str), pa.getMACAddressParseData()); err == nil {
addressParseData := pa.getAddressParseData()
prov, err = chooseMACAddressProvider(fromString, validationOptions, &pa, addressParseData)
} else {
prov = getInvalidMACProvider(validationOptions)
}
if err != nil && prov == nil {
prov = getInvalidMACProvider(validationOptions)
}
return
}
func (strValidator) validateIPAddressStr(fromString *IPAddressString, validationOptions address_string_param.IPAddressStringParams) (prov ipAddressProvider, err address_error.AddressStringError) {
str := fromString.str
pa := parsedIPAddress{
originator: fromString,
options: validationOptions,
ipAddressParseData: ipAddressParseData{addressParseData: addressParseData{str: str}},
}
if err = validateIPAddress(validationOptions, str, 0, len(str), pa.getIPAddressParseData(), false); err == nil {
if err = parseAddressQualifier(str, validationOptions, nil, pa.getIPAddressParseData(), len(str)); err == nil {
prov, err = chooseIPAddressProvider(fromString, str, validationOptions, &pa)
} else {
prov = getInvalidProvider(validationOptions)
}
} else {
prov = getInvalidProvider(validationOptions)
}
return
}
func (strValidator) validatePrefixLenStr(fullAddr string, version IPVersion) (prefixLen PrefixLen, err address_error.AddressStringError) {
var qualifier parsedHostIdentifierStringQualifier
isPrefix, err := validatePrefix(fullAddr, nil, defaultIPAddrParameters, nil, &qualifier, 0, len(fullAddr), version)
if !isPrefix {
err = &addressStringError{addressError{str: fullAddr, key: "ipaddress.error.invalidCIDRPrefix"}}
} else {
prefixLen = qualifier.getNetworkPrefixLen()
}
return
}
// ValidateZoneStr returns an error if the given zone is invalid.
func ValidateZoneStr(zoneStr string) (zone Zone, err address_error.AddressStringError) {
for i := 0; i < len(zoneStr); i++ {
c := zone[i]
if c == PrefixLenSeparator {
err = &addressStringIndexError{addressStringError{addressError{str: zoneStr, key: "ipaddress.error.invalid.zone"}}, i}
return
}
if c == IPv6SegmentSeparator {
err = &addressStringIndexError{addressStringError{addressError{str: zoneStr, key: "ipaddress.error.invalid.zone"}}, i}
return
}
}
return Zone(zoneStr), nil
}
func (strValidator) validateHostName(fromHost *HostName, validationOptions address_string_param.HostNameParams) (psdHost *parsedHost, err address_error.HostNameError) {
str := fromHost.str
addrLen := len(str)
if addrLen > maxHostLength {
if addrLen > maxHostLength+1 || str[maxHostLength] != LabelSeparator {
err = &hostNameError{addressError{str: str, key: "ipaddress.host.error.invalid.length"}}
return
}
}
var segmentUppercase, isNotNormalized, squareBracketed, tryIPv6, tryIPv4, isPrefixed, hasPortOrService, hostIsEmpty bool
isAllDigits, isPossiblyIPv6, isPossiblyIPv4 := true, true, true
isSpecialOnlyIndex, qualifierIndex, index, lastSeparatorIndex := -1, -1, -1, -1
labelCount := 0
maxLocalLabels := 6 //should be at least 4 to avoid the array for ipv4 addresses
var separatorIndices []int
var normalizedFlags []bool
sep0, sep1, sep2, sep3, sep4, sep5 := -1, -1, -1, -1, -1, -1
var isUpper0, isUpper1, isUpper2, isUpper3, isUpper4, isUpper5 bool
var currentChar byte
for index++; index <= addrLen; index++ {
// grab the character to evaluate
if index == addrLen {
if index == 0 {
hostIsEmpty = true
break
}
segmentCountMatchesIPv4 :=
isPossiblyIPv4 &&
(labelCount+1 == IPv4SegmentCount) ||
(labelCount+1 < IPv4SegmentCount && isSpecialOnlyIndex >= 0) ||
(labelCount+1 < IPv4SegmentCount && validationOptions.GetIPAddressParams().GetIPv4Params().AllowsInetAtonJoinedSegments()) ||
labelCount == 0 && validationOptions.GetIPAddressParams().AllowsSingleSegment()
if isAllDigits {
if isPossiblyIPv4 && segmentCountMatchesIPv4 {
tryIPv4 = true
break
}
isPossiblyIPv4 = false
if hasPortOrService && isPossiblyIPv6 { // isPossiblyIPv6 is already false if labelCount > 0
// since it is all digits, it cannot be host, so we set tryIPv6 rather than just isPossiblyIPv6
tryIPv6 = true
break
}
err = &hostNameError{addressError{str: str, key: "ipaddress.host.error.invalid"}}
return
}
isPossiblyIPv4 = isPossiblyIPv4 && segmentCountMatchesIPv4
currentChar = LabelSeparator
} else {
currentChar = str[index]
}
// check that character
// break out of the loop if we hit '[', '*', '%' (as zone or wildcard), or ':' that is not interpreted as port (and this is ipv6)
// exit the loop prematurely if we hit '/' or ':' interpreted as port
if currentChar >= 'a' && currentChar <= 'z' {
if currentChar > 'f' {
isPossiblyIPv6 = false
isPossiblyIPv4 = isPossiblyIPv4 && (currentChar == 'x' && validationOptions.GetIPAddressParams().GetIPv4Params().AllowsInetAtonHex())
} else if currentChar == 'b' {
isPossiblyIPv4 = isPossiblyIPv4 && validationOptions.GetIPAddressParams().GetIPv4Params().AllowsBinary()
}
isAllDigits = false
} else if currentChar >= '0' && currentChar <= '9' {
//nothing to do
continue
} else if currentChar >= 'A' && currentChar <= 'Z' {
if currentChar > 'F' {
isPossiblyIPv6 = false
isPossiblyIPv4 = isPossiblyIPv4 && (currentChar == 'X' && validationOptions.GetIPAddressParams().GetIPv4Params().AllowsInetAtonHex())
} else if currentChar == 'B' {
isPossiblyIPv4 = isPossiblyIPv4 && validationOptions.GetIPAddressParams().GetIPv4Params().AllowsBinary()
}
segmentUppercase = true
isAllDigits = false
} else if currentChar == LabelSeparator {
length := index - lastSeparatorIndex - 1
if length > maxLabelLength {
err = &hostNameError{addressError{str: str, key: "ipaddress.error.segment.too.long"}}
return
} else if length == 0 {
if index < addrLen {
err = &hostNameError{addressError{str: str, key: "ipaddress.host.error.segment.too.short"}}
return
}
isPossiblyIPv4 = false
isNotNormalized = true
} else {
if labelCount < maxLocalLabels {
if labelCount < 3 {
if labelCount == 0 {
sep0 = index
isUpper0 = segmentUppercase
} else if labelCount == 1 {
sep1 = index
isUpper1 = segmentUppercase
} else {
sep2 = index
isUpper2 = segmentUppercase
}
} else {
if labelCount == 3 {
sep3 = index
isUpper3 = segmentUppercase
} else if labelCount == 4 {
sep4 = index
isUpper4 = segmentUppercase
} else {
sep5 = index
isUpper5 = segmentUppercase
}
}
labelCount++
} else if labelCount == maxLocalLabels {
separatorIndices = make([]int, maxHostSegments+1)
separatorIndices[labelCount] = index
if validationOptions.NormalizesToLowercase() {
normalizedFlags = make([]bool, maxHostSegments+1)
normalizedFlags[labelCount] = !segmentUppercase
isNotNormalized = isNotNormalized || segmentUppercase
}
labelCount++
} else {
separatorIndices[labelCount] = index
if normalizedFlags != nil {
normalizedFlags[labelCount] = !segmentUppercase
isNotNormalized = isNotNormalized || segmentUppercase
}
labelCount++
if labelCount > maxHostSegments {
err = &hostNameError{addressError{str: str, key: "ipaddress.host.error.too.many.segments"}}
return
}
}
segmentUppercase = false // this is per segment so reset it
}
lastSeparatorIndex = index
isPossiblyIPv6 = isPossiblyIPv6 && (index == addrLen) // A '.' means not ipv6 (if we see ':' we jump out of loop so mixed address not possible), but for single segment we end up here even without a '.' character in the string
} else if currentChar == '_' { // this is not supported in host names but is supported in domain names, see discussion in HostName
isAllDigits = false
} else if currentChar == '-' {
// host name segments cannot end with '-'
if index == lastSeparatorIndex+1 || index == addrLen-1 || str[index+1] == LabelSeparator {
err = &hostNameIndexError{hostNameError{addressError{str: str, key: "ipaddress.host.error.invalid.character.at.index"}}, index}
return
}
isAllDigits = false
} else if currentChar == IPv6StartBracket {
if index == 0 && labelCount == 0 && addrLen > 2 {
squareBracketed = true
break
}
err = &hostNameIndexError{hostNameError{addressError{str: str, key: "ipaddress.host.error.invalid.character.at.index"}}, index}
return
} else if currentChar == PrefixLenSeparator {
isPrefixed = true
qualifierIndex = index + 1
addrLen = index
isNotNormalized = true
index--
} else {
a := currentChar == SegmentWildcard
if a || currentChar == SegmentSqlSingleWildcard {
b := !a
addressOptions := validationOptions.GetIPAddressParams()
if b && addressOptions.GetIPv6Params().AllowsZone() { // if we allow zones, we treat '%' as a zone and not as a wildcard
if isPossiblyIPv6 && labelCount < IPv6SegmentCount {
tryIPv6 = true
isPossiblyIPv4 = false
break
}
err = &hostNameIndexError{hostNameError{addressError{str: str, key: "ipaddress.host.error.invalid.character.at.index"}}, index}
return
} else {
if isPossiblyIPv4 {
if addressOptions.GetIPv4Params().GetRangeParams().AllowsWildcard() {
if isSpecialOnlyIndex < 0 {
isSpecialOnlyIndex = index
}
} else {
isPossiblyIPv4 = false
}
}
if isPossiblyIPv6 && addressOptions.GetIPv6Params().GetRangeParams().AllowsWildcard() {
if isSpecialOnlyIndex < 0 {
isSpecialOnlyIndex = index
}
} else {
if !isPossiblyIPv4 {
// needs to be either ipv4 or ipv6
err = &hostNameIndexError{hostNameError{addressError{str: str, key: "ipaddress.host.error.invalid.character.at.index"}}, index}
return
}
isPossiblyIPv6 = false
}
}
isAllDigits = false
} else if currentChar == IPv6SegmentSeparator { //also might denote a port
if validationOptions.AllowsPort() || validationOptions.AllowsService() {
hasPortOrService = true
qualifierIndex = index + 1
addrLen = index // causes loop to terminate, but only after handling the last segment
isNotNormalized = true
index--
} else {
isPossiblyIPv4 = false
if isPossiblyIPv6 {
tryIPv6 = true
break
}
err = &hostNameIndexError{hostNameError{addressError{str: str, key: "ipaddress.host.error.invalid.character.at.index"}}, index}
return
}
} else if currentChar == AlternativeRangeSeparatorStr[0] {
if index+1 == addrLen {
err = &hostNameIndexError{hostNameError{addressError{str: str, key: "ipaddress.host.error.invalid.character.at.index"}}, index}
return
}
currentChar = str[index+1]
if currentChar == AlternativeRangeSeparatorStr[1] {
isAllDigits = false
isPossiblyIPv4 = false
isPossiblyIPv6 = false
if isSpecialOnlyIndex < 0 {
isSpecialOnlyIndex = index
}
index++
} else {
err = &hostNameIndexError{hostNameError{addressError{str: str, key: "ipaddress.host.error.invalid.character.at.index"}}, index}
return
}
} else {
err = &hostNameIndexError{hostNameError{addressError{str: str, key: "ipaddress.host.error.invalid.character.at.index"}}, index}
return
}
}
}
/*
1. squareBracketed: [ addr ]
2. tryIPv4 || tryIPv6: this is a string with characters that invalidate it as a host but it still may in fact be an address
This includes ipv6 strings, ipv4/ipv6 strings with '*', or all dot/digit strings like 1.2.3.4 that are 4 segments
3. isPossiblyIPv4: this is a string with digits, - and _ characters and the number of separators matches ipv4. Such strings can also be valid hosts.
The range options flag (controlling whether we allow '-' or '_' in addresses) for ipv4 can control whether it is treated as host or address.
It also includes "" empty addresses.
isPossiblyIPv6: something like f:: or f:1, the former IPv6 and the latter a host "f" with port 1. Such strings can be valid addresses or hosts.
If it parses as an address, we do not treat as host.
*/
psdHost = &parsedHost{originalStr: str, params: validationOptions}
addressOptions := validationOptions.GetIPAddressParams()
isIPAddress := squareBracketed || tryIPv4 || tryIPv6
if !validationOptions.AllowsIPAddress() {
if isIPAddress {
err = &hostNameError{addressError{str: str, key: "ipaddress.host.error.ipaddress"}}
return
}
} else if isIPAddress || isPossiblyIPv4 || isPossiblyIPv6 {
provider, address_Error, hostErr := func() (provider ipAddressProvider, address_Error address_error.AddressError, hostErr address_error.HostNameError) {
pa := parsedIPAddress{
ipAddressParseData: ipAddressParseData{addressParseData: addressParseData{str: str}},
options: addressOptions,
originator: fromHost,
}
hostQualifier := psdHost.getQualifier()
if squareBracketed {
// Note:
// Firstly, we need to find the address end which is denoted by the end bracket
// Secondly, while zones appear inside bracket, prefix or port appears outside, according to rfc 4038
// So keep track of the boolean endsWithPrefix to differentiate.
endIndex := addrLen - 1
endsWithQualifier := str[endIndex] != IPv6EndBracket
if endsWithQualifier {
for endIndex--; str[endIndex] != IPv6EndBracket; endIndex-- {
if endIndex == 1 {
err = &hostNameError{addressError{str: str, key: "ipaddress.host.error.bracketed.missing.end"}}
return
}
}
}
startIndex := 1
if strings.HasPrefix(str[1:], SmtpIPv6Identifier) {
// SMTP rfc 2821 allows [IPv6:ipv6address]
startIndex = 6
} else {
/*
RFC 3986 section 3.2.2
host = IP-literal / IPv4address / reg-name
IP-literal = "[" ( IPv6address / IPvFuture ) "]"
IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
If a URI containing an IP-literal that starts with "v" (case-insensitive),
indicating that the version flag is present, is dereferenced by an application that does not know the meaning of that version flag,
then the application should return an appropriate error for "address mechanism not supported".
*/
firstChar := str[1]
if firstChar == IPvFuture || firstChar == ipvFutureUppercase {
err = &hostNameError{addressError{str: str, key: "ipaddress.host.error.invalid.mechanism"}}
return
}
}
address_Error = validateIPAddress(addressOptions, str, startIndex, endIndex, pa.getIPAddressParseData(), false)
if address_Error != nil {
return
}
if endsWithQualifier {
// here check what is in the qualifier that follows the bracket: prefix/mask or port?
// if prefix/mask, we supply the qualifier to the address, otherwise we supply it to the host
prefixIndex := endIndex + 1
prefixChar := str[prefixIndex]
if prefixChar == PrefixLenSeparator {
isPrefixed = true
} else if prefixChar == PortSeparator {
hasPortOrService = true
} else {
hostErr = &hostNameIndexError{hostNameError{addressError{str: str, key: "ipaddress.host.error.invalid.character.at.index"}}, prefixIndex}
return
}
qualifierIndex = prefixIndex + 1 //skip the ']/'
endIndex = len(str)
addressParseData := pa.getAddressParseData()
address_Error = parseHostNameQualifier(
str,
addressOptions,
validationOptions,
hostQualifier,
isPrefixed,
hasPortOrService,
addressParseData.isProvidingEmpty(),
qualifierIndex,
endIndex,
pa.getProviderIPVersion())
if address_Error != nil {
return
}
insideBracketsQualifierIndex := pa.getQualifierIndex()
if pa.isZoned() && str[insideBracketsQualifierIndex] == '2' &&
str[insideBracketsQualifierIndex+1] == '5' {
//handle %25 from rfc 6874
insideBracketsQualifierIndex += 2
}
address_Error = parseHostAddressQualifier(
str,
addressOptions,
nil,
pa.hasPrefixSeparator(),
false,
pa.getIPAddressParseData(),
insideBracketsQualifierIndex,
prefixIndex-1)
if address_Error != nil {
return
}
if isPrefixed {
// since we have an address, we apply the prefix to the address rather than to the host
// rather than use the prefix as a host qualifier, we treat it as an address qualifier and leave the host qualifier as noQualifier
// also, keep in mind you can combine prefix with zone like fe80::%2/64, see https://tools.ietf.org/html/rfc4007#section-11.7
// if there are two prefix lengths, we choose the smaller (larger network)
// if two masks, we combine them (if both network masks, this is the same as choosing smaller prefix)
addrQualifier := pa.getIPAddressParseData().getQualifier()
address_Error = addrQualifier.merge(hostQualifier)
if address_Error != nil {
return
}
hostQualifier.clearPrefixOrMask()
// note it makes no sense to indicate a port or service with a prefix
}
} else {
qualifierIndex = pa.getQualifierIndex()
isPrefixed = pa.hasPrefixSeparator()
hasPortOrService = false
if pa.isZoned() && str[qualifierIndex] == '2' &&
str[qualifierIndex+1] == '5' {
//handle %25 from rfc 6874
qualifierIndex += 2
}
address_Error = parseHostAddressQualifier(str, addressOptions, validationOptions, isPrefixed, hasPortOrService, pa.getIPAddressParseData(), qualifierIndex, endIndex)
if address_Error != nil {
return
}
}
//SMTP rfc 2821 allows [ipv4address]
version := pa.getProviderIPVersion()
if !version.IsIPv6() && !validationOptions.AllowsBracketedIPv4() {
err = &hostNameError{addressError{str: str, key: "ipaddress.host.error.bracketed.not.ipv6"}}
return
}
} else { //not square-bracketed
/*
there are cases where it can be ipv4 or ipv6, but not many
any address with a '.' in it cannot be ipv6 at this point (if we hit a ':' first we would have jumped out of the loop)
any address with a ':' has gone through tests to see if up until that point it could match an ipv4 address or an ipv6 address
it can only be ipv4 if it has right number of segments, and only decimal digits.
it can only be ipv6 if it has only hex digits.
so when can it be both? if it looks like *: at the start, so that it has the right number of segments for ipv4 but does not have a '.' invalidating ipv6
so in that case we might have either something like *:1 for it to be ipv4 (ambiguous is treated as ipv4) or *:f:: to be ipv6
So we validate the potential port (or ipv6 segment) to determine which one and then go from there
Also, if it is single segment address that is all decimal digits.
*/
// We start by checking if there is potentially a port or service
// if IPv6, we may need to try a :x as a port or service and as a trailing segment
firstTrySucceeded := false
hasAddressPortOrService := false
addressQualifierIndex := -1
isPotentiallyIPv6 := isPossiblyIPv6 || tryIPv6
if isPotentiallyIPv6 {
// find the last port separator, currently we point to the first one with qualifierIndex
// note that the service we find here could be the ipv4 part of either an ipv6 address or ipv6 mask like this 1:2:3:4:5:6:1.2.3.4 or 1:2:3:4:5:6:1.2.3.4/1:2:3:4:5:6:1.2.3.4
if !isPrefixed && (validationOptions.AllowsPort() || validationOptions.AllowsService()) {
for j := len(str) - 1; j >= 0; j-- {
c := str[j]
if c == IPv6SegmentSeparator {
hasAddressPortOrService = true
addressQualifierIndex = j + 1
} else if (c >= '0' && c <= '9') ||
(c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
(c == '-') ||
(c == SegmentWildcard) {
// see validateHostNamePort for more details on valid ports and service names
continue
}
break
}
}
} else {
hasAddressPortOrService = hasPortOrService
addressQualifierIndex = qualifierIndex
}
var endIndex int
if hasAddressPortOrService {
// validate the potential port
address_Error = parsePortOrService(str, nil, validationOptions, hostQualifier, addressQualifierIndex, len(str))
if address_Error != nil {
// certainly not IPv4 since it doesn't qualify as port (see comment above)
if !isPotentiallyIPv6 {
// not IPv6 either, so we're done with checking for address
return
}
// no need to call hostQualifier.clear() since parsePortOrService does not populate qualifier on error
endIndex = len(str)
} else if isPotentiallyIPv6 {
// here it can be either a port or part of an IPv6 address, like this: fe80::6a05:caff:fe3:123
expectPort := validationOptions.ExpectsPort()
if expectPort {
// try with port first, then try as IPv6 no port
endIndex = addressQualifierIndex - 1
} else {
// try as IPv6 with no port first, try with port second
endIndex = len(str)
}
// first try
address_Error = validateIPAddress(addressOptions, str, 0, endIndex, pa.getIPAddressParseData(), false)
if address_Error == nil {
// Since no square brackets, we parse as an address (this can affect how zones are parsed).
// Also, an address cannot end with a single ':' like a port, so we cannot take a shortcut here and parse for port, we must strip it off first (hence no host parameters passed)
address_Error = parseAddressQualifier(str, addressOptions, nil, pa.getIPAddressParseData(), endIndex)
}
if firstTrySucceeded = address_Error == nil; !firstTrySucceeded {
pa = parsedIPAddress{
ipAddressParseData: ipAddressParseData{addressParseData: addressParseData{str: str}},
options: addressOptions,
originator: fromHost,
}
if expectPort {
// we tried with port first, now we try as IPv6 no port
hostQualifier.clearPortOrService()
endIndex = len(str)
} else {
// we tried as IPv6 with no port first, now we try with port second
endIndex = addressQualifierIndex - 1
}
} else if !expectPort {
// it is an address
// we tried with no port and succeeded, so clear the port, it was not a port
hostQualifier.clearPortOrService()
}
} else {
endIndex = addressQualifierIndex - 1
}
} else {
endIndex = len(str)
}
if !firstTrySucceeded {
if address_Error = validateIPAddress(addressOptions, str, 0, endIndex, pa.getIPAddressParseData(), false); address_Error == nil {
// since no square brackets, we parse as an address (this can affect how zones are parsed)
// Also, an address cannot end with a single ':' like a port, so we cannot take a shortcut here and parse for port, we must strip it off first (hence no host parameters passed)
address_Error = parseAddressQualifier(str, addressOptions, nil, pa.getIPAddressParseData(), endIndex)
}
if address_Error != nil {
return
}
}
}
// successfully parsed an IP address
provider, address_Error = chooseIPAddressProvider(fromHost, str, addressOptions, &pa)
return
}()
if hostErr != nil {
err = hostErr
return
}
if address_Error != nil {
if isIPAddress {
err = &hostAddressNestedError{nested: address_Error}
return
}
psdHost.labelsQualifier.clearPortOrService()
//fall though and evaluate as a host
} else {
psdHost.embeddedAddress.addressProvider = provider
return
}
}
hostQualifier := psdHost.getQualifier()
address_Error := parseHostNameQualifier(
str,
addressOptions,
validationOptions,
hostQualifier,
isPrefixed,
hasPortOrService,
hostIsEmpty,
qualifierIndex,
len(str),
IndeterminateIPVersion)
if address_Error != nil {
err = &hostAddressNestedError{nested: address_Error}
return
}
if hostIsEmpty {
if !validationOptions.AllowsEmpty() {
err = &hostNameError{addressError{str: str, key: "ipaddress.host.error.empty"}}
return
}
if *hostQualifier == defaultEmptyHost.labelsQualifier {
psdHost = defaultEmptyHost
}
} else {
if labelCount <= maxLocalLabels {
maxLocalLabels = labelCount
separatorIndices = make([]int, maxLocalLabels)
if validationOptions.NormalizesToLowercase() {
normalizedFlags = make([]bool, maxLocalLabels)
}
} else if labelCount != len(separatorIndices) {
trimmedSeparatorIndices := make([]int, labelCount)
copy(trimmedSeparatorIndices[maxLocalLabels:], separatorIndices[maxLocalLabels:labelCount])
separatorIndices = trimmedSeparatorIndices
if normalizedFlags != nil {
trimmedNormalizedFlags := make([]bool, labelCount)
copy(trimmedNormalizedFlags[maxLocalLabels:], normalizedFlags[maxLocalLabels:labelCount])
normalizedFlags = trimmedNormalizedFlags
}
}
for i := 0; i < maxLocalLabels; i++ {
var nextSep int
var isUpper bool
if i < 2 {
if i == 0 {
nextSep = sep0
isUpper = isUpper0
} else {
nextSep = sep1
isUpper = isUpper1
}
} else if i < 4 {
if i == 2 {
nextSep = sep2
isUpper = isUpper2
} else {
nextSep = sep3
isUpper = isUpper3
}
} else if i == 4 {
nextSep = sep4
isUpper = isUpper4
} else {
nextSep = sep5
isUpper = isUpper5
}
separatorIndices[i] = nextSep
if normalizedFlags != nil {
normalizedFlags[i] = !isUpper
isNotNormalized = isNotNormalized || isUpper
}
}
// We support a.b.com/24:80 (prefix and port combo)
// or just port, or a service where-ever a port can appear
// A prefix with port can mean a subnet of addresses using the same port everywhere (the subnet being the prefix block of the resolved address),
// or just denote the prefix length of the resolved address along with a port
//
// here we check what is in the qualifier that follows the bracket: prefix/mask or port?
// if prefix/mask, we supply the qualifier to the address, otherwise we supply it to the host
// also, it is possible the address has a zone
var addrQualifier *parsedHostIdentifierStringQualifier
if isPrefixed {
addrQualifier = hostQualifier
} else {
addrQualifier = noQualifier
}
embeddedAddr := checkSpecialHosts(str, addrLen, addrQualifier)
hasEmbeddedAddr := embeddedAddr.addressProvider != nil
if isSpecialOnlyIndex >= 0 && (!hasEmbeddedAddr || embeddedAddr.addressStringError != nil) {
if embeddedAddr.addressStringError != nil {
err = &hostAddressNestedError{
hostNameIndexError: hostNameIndexError{
hostNameError: hostNameError{
addressError{str: str, key: "ipaddress.host.error.invalid.character.at.index"},
},
index: isSpecialOnlyIndex,
},
nested: embeddedAddr.addressStringError,
}
return
}
err = &hostNameIndexError{hostNameError{addressError{str: str, key: "ipaddress.host.error.invalid.character.at.index"}}, isSpecialOnlyIndex}
return
}
psdHost.separatorIndices = separatorIndices
psdHost.normalizedFlags = normalizedFlags
if !hasEmbeddedAddr {
if !isNotNormalized {
normalizedLabels := make([]string, len(separatorIndices))
for i, lastSep := 0, -1; i < len(normalizedLabels); i++ {
index := separatorIndices[i]
normalizedLabels[i] = str[lastSep+1 : index]
lastSep = index
}
psdHost.parsedHostCache = &parsedHostCache{
host: str,
normalizedLabels: normalizedLabels,
}
}
} else {
if isPrefixed {
psdHost.labelsQualifier.clearPrefixOrMask()
}
psdHost.embeddedAddress = embeddedAddr
}
}
return
}
func createChars() (chars [int('z') + 1]byte, extendedChars [int('~') + 1]byte) {
i := byte(1)
for c := '1'; i < 10; i, c = i+1, c+1 {
chars[c] = i
}
for c, c2 := 'a', 'A'; i < 26; i, c, c2 = i+1, c+1, c2+1 {
chars[c] = i
chars[c2] = i
}
var extendedDigits = []byte{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '!', '#', '$', '%', '&', '(', ')', '*', '+', '-',
';', '<', '=', '>', '?', '@', '^', '_', '`', '{', '|', '}',
'~'}
extLen := byte(len(extendedDigits))
for i = 0; i < extLen; i++ {
c := extendedDigits[i]
extendedChars[c] = i
}
return
}
func isSingleSegmentIPv6(str string, totalDigits int, isRange bool, frontTotalDigits int,
ipv6SpecificOptions address_string_param.IPv6AddressStringParams) (isSingle bool, err address_error.AddressStringError) {
backIsIpv6 := totalDigits == ipv6SingleSegmentDigitCount || // 32 hex chars with or without 0x
(ipv6SpecificOptions.AllowsBinary() && totalDigits == ipv6BinarySingleSegmentDigitCount+2) || // 128 binary chars with 0b
(isRange && totalDigits == 0 && (frontTotalDigits == ipv6SingleSegmentDigitCount ||
(ipv6SpecificOptions.AllowsBinary() && frontTotalDigits == ipv6BinarySingleSegmentDigitCount+2)))
if backIsIpv6 && isRange && totalDigits != 0 {
frontIsIpv6 := frontTotalDigits == ipv6SingleSegmentDigitCount ||
(ipv6SpecificOptions.AllowsBinary() && frontTotalDigits == ipv6BinarySingleSegmentDigitCount+2) ||
frontTotalDigits == 0
if !frontIsIpv6 {
err = &addressStringError{addressError{str: str, key: "ipaddress.error.too.few.segments.digit.count"}}
return
}
}
isSingle = backIsIpv6
return
}
// When checking for binary single segment, it is necessary to check the exact number of digits for IPv4.
// This is because in IPv6 there is ambiguity between hexadecimal 32 characters starting with 0b and 0b before 30 binary characters.
// Therefore, for IPv4, we must avoid 0b before 30 binary characters.
// It is necessary to require 0b before 32 binary characters.
// This only applies to single segment.
// For segmented IPv4 there is no ambiguity, and we allow binary segments of different lengths as for inetAton.
func isSingleSegmentIPv4(str string, nonZeroDigits, totalDigits int, isRange bool, frontNonZeroDigits, frontTotalDigits int,
ipv4SpecificOptions address_string_param.IPv4AddressStringParams) (isSingle bool, err address_error.AddressStringError) {
backIsIpv4 := nonZeroDigits <= ipv4SingleSegmentOctalDigitCount ||
(ipv4SpecificOptions.AllowsBinary() && totalDigits == ipv4BinarySingleSegmentDigitCount+2) ||
(isRange && totalDigits == 0 && (frontTotalDigits <= ipv4SingleSegmentOctalDigitCount ||
(ipv4SpecificOptions.AllowsBinary() && frontTotalDigits == ipv4BinarySingleSegmentDigitCount+2)))
if backIsIpv4 && isRange && totalDigits != 0 {
frontIsIpv4 := frontNonZeroDigits <= ipv4SingleSegmentOctalDigitCount ||
(ipv4SpecificOptions.AllowsBinary() && frontTotalDigits == ipv4BinarySingleSegmentDigitCount+2) ||
frontTotalDigits == 0
if !frontIsIpv4 {
err = &addressStringError{addressError{str: str, key: "ipaddress.error.too.few.segments.digit.count"}}
return
}
}
isSingle = backIsIpv4
return
}
func createBase85Powers() []big.Int {
res := make([]big.Int, 10)
eightyFive := big.NewInt(85)
res[0].SetUint64(1)
for i := 1; i < len(res); i++ {
res[i].Mul(&res[i-1], eightyFive)
}
return res
}
func parse85(s string, start, end int) *big.Int {
var last bool
var result big.Int
charArray := extendedChars
for {
var partialEnd, power int
left := end - start
if last = left <= 9; last {
partialEnd = end
power = left
} else {
partialEnd = start + 9
power = 9
}
var partialResult = uint64(charArray[s[start]])
for start++; start < partialEnd; start++ {
next := charArray[s[start]]
partialResult = (partialResult * 85) + uint64(next)
}
result.Mul(&result, &base85Powers[power]).Add(&result, new(big.Int).SetUint64(partialResult))
if last {
break
}
}
return &result
}
func assign3Attributes2Values1Flags(start, end, leadingZeroStart int, parseData *addressParseData, parsedSegIndex int, value, extendedValue uint64, flags uint32) {
ustart := uint32(start)
uend := uint32(end)
uleadingZeroStart := uint32(leadingZeroStart)
parseData.set7Index4ValuesFlags(parsedSegIndex,
flagsIndex, flags,
keyLowerStrDigitsIndex, uleadingZeroStart,
keyLowerStrStartIndex, ustart,
keyLowerStrEndIndex, uend,
keyUpperStrDigitsIndex, uleadingZeroStart,
keyUpperStrStartIndex, ustart,
keyUpperStrEndIndex, uend,
keyLower, value,
keyExtendedLower, extendedValue,
keyUpper, value,
keyExtendedUpper, extendedValue)
}
func assign3Attributes1Values1Flags(start, end, leadingZeroStart int, parseData *addressParseData, parsedSegIndex int, value uint64, flags uint32) {
ustart := uint32(start)
uend := uint32(end)
uleadingZeroStart := uint32(leadingZeroStart)
parseData.set7Index2ValuesFlags(parsedSegIndex,
flagsIndex, flags,
keyUpperStrDigitsIndex, uleadingZeroStart,
keyLowerStrDigitsIndex, uleadingZeroStart,
keyUpperStrStartIndex, ustart,
keyLowerStrStartIndex, ustart,
keyUpperStrEndIndex, uend,
keyLowerStrEndIndex, uend,
keyLower, value,
keyUpper, value)
}
func assign7Attributes4Values1Flags(frontStart, frontEnd, frontLeadingZeroStartIndex, start, end, leadingZeroStartIndex int,
parseData *addressParseData, parsedSegIndex int, frontValue, frontExtendedValue, value, extendedValue uint64, flags uint32, upperRadix uint32) {
parseData.set8Index4ValuesFlags(parsedSegIndex,
flagsIndex, flags,
keyLowerStrDigitsIndex, uint32(frontLeadingZeroStartIndex),
keyLowerStrStartIndex, uint32(frontStart),
keyLowerStrEndIndex, uint32(frontEnd),
keyUpperRadixIndex, uint32(upperRadix),
keyUpperStrDigitsIndex, uint32(leadingZeroStartIndex),
keyUpperStrStartIndex, uint32(start),
keyUpperStrEndIndex, uint32(end),
keyLower, frontValue,
keyExtendedLower, frontExtendedValue,
keyUpper, value,
keyExtendedUpper, extendedValue)
}
func assign6Attributes4Values1Flags(frontStart, frontEnd, frontLeadingZeroStartIndex, start, end, leadingZeroStartIndex int,
parseData *addressParseData, parsedSegIndex int, frontValue, frontExtendedValue, value, extendedValue uint64, flags uint32) {
parseData.set7Index4ValuesFlags(parsedSegIndex,
flagsIndex, flags,
keyLowerStrDigitsIndex, uint32(frontLeadingZeroStartIndex),
keyLowerStrStartIndex, uint32(frontStart),
keyLowerStrEndIndex, uint32(frontEnd),
keyUpperStrDigitsIndex, uint32(leadingZeroStartIndex),
keyUpperStrStartIndex, uint32(start),
keyUpperStrEndIndex, uint32(end),
keyLower, frontValue,
keyExtendedLower, frontExtendedValue,
keyUpper, value,
keyExtendedUpper, extendedValue)
}
func assign6Attributes2Values1Flags(frontStart, frontEnd, frontLeadingZeroStartIndex, start, end, leadingZeroStartIndex int,
parseData *addressParseData, parsedSegIndex int, frontValue, value uint64, flags uint32) {
parseData.set7Index2ValuesFlags(parsedSegIndex,
flagsIndex, flags,
keyLowerStrDigitsIndex, uint32(frontLeadingZeroStartIndex),
keyLowerStrStartIndex, uint32(frontStart),