File: IPv6Addr.pm

package info (click to toggle)
libnet-ipv6addr-perl 1.02-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 328 kB
  • sloc: perl: 598; makefile: 2
file content (693 lines) | stat: -rw-r--r-- 13,766 bytes parent folder | download
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
package Net::IPv6Addr;

use strict;
use warnings;

our @ISA = qw(Exporter);
our @EXPORT = qw();
our @EXPORT_OK = qw(
    from_bigint
    in_network
    in_network_of_size
    ipv6_chkip
    ipv6_parse
    is_ipv6
    to_array
    to_bigint
    to_intarray
    to_string_base85
    to_string_compressed
    to_string_ip6_int
    to_string_ipv4
    to_string_ipv4_compressed
    to_string_preferred
);

our %EXPORT_TAGS = (all => \@EXPORT_OK);

our $VERSION = '1.02';

use Carp;
use Math::BigInt '1.999813';

my $base85ok;
eval {
    require Math::Base85;
};
if (! $@) {
    $base85ok = 1;
}

sub base85ok
{
    return $base85ok
}

#  ____       _   _                      
# |  _ \ __ _| |_| |_ ___ _ __ _ __  ___ 
# | |_) / _` | __| __/ _ \ '__| '_ \/ __|
# |  __/ (_| | |_| ||  __/ |  | | | \__ \
# |_|   \__,_|\__|\__\___|_|  |_| |_|___/
#                                       

# Match one to four digits of hexadecimal

my $h = qr/[a-f0-9]{1,4}/i;

my $ipn = qr!
    (
	25[0-5]
    |
	2[0-4][0-9]
    |
	1[0-9]{2}
    |
	[1-9][0-9]
    |
	[0-9]
    )
!x;

my $ipv4 = qr!($ipn\.){3}$ipn!;

sub ipv4_validate
{
    my ($ip) = @_;
    if ($ip !~ /$ipv4/) {
	croak "Holy macaroni batman";
    }
}

# base-85

my $base85_re;
if ($base85ok) {
    my $digits = $Math::Base85::base85_digits;
    $digits =~ s/-//;
    $base85_re = qr![$digits-]{20}!;
}

my %ipv6_patterns = (
    'preferred' => [
	qr/^(?:$h:){7}$h$/i,
	\&ipv6_parse_preferred,
    ],
    'compressed' => [
	qr/^[a-f0-9]{0,4}::$/i,
	qr/^:(?::$h){1,7}$/i,
	qr/^(?:$h:){1,}:$/i,
	qr/^(?:$h:)(?::$h){1,6}$/i,
	qr/^(?:$h:){2}(?::$h){1,5}$/i,
	qr/^(?:$h:){3}(?::$h){1,4}$/i,
	qr/^(?:$h:){4}(?::$h){1,3}$/i,
	qr/^(?:$h:){5}(?::$h){1,2}$/i,
	qr/^(?:$h:){6}(?::$h)$/i,
	\&ipv6_parse_compressed,
    ],
    'ipv4' => [
	qr/^(?:0:){5}ffff:$ipv4$/i,
	qr/^(?:0:){6}$ipv4$/,
	\&ipv6_parse_ipv4,
    ],
    'ipv4 compressed' => [
	qr/^::(?:ffff:)?$ipv4$/i,
	\&ipv6_parse_ipv4_compressed,
    ],
    'ipv6v4' => [
	qr/^[a-f0-9]{0,4}::$ipv4$/i,
	# ::1:2:3:4:1.2.3.4
	qr/^::(?:$h:){1,5}$ipv4$/i,
	qr/^(?:$h:):(?:$h:){1,4}$ipv4$/i,
	qr/^(?:$h:){2}:(?:$h:){1,3}$ipv4$/i,
	qr/^(?:$h:){3}:(?:$h:){1,2}$ipv4$/i,
	qr/^(?:$h:){4}:(?:$h:){1}$ipv4$/i,
	# 1:2:3:4:5::1.2.3.4
	qr/^(?:$h:){1,5}:$ipv4$/i,
	# 1:2:3:4:5:6:1.2.3.4
	qr/^(?:$h:){6}$ipv4$/i,
	\&parse_mixed_ipv6v4_compressed,
    ],
);

if ($base85ok) {
    $ipv6_patterns{'base85'} = [
	$base85_re,
	\&ipv6_parse_base85,
    ],
}

#  ____       _            _       
# |  _ \ _ __(_)_   ____ _| |_ ___ 
# | |_) | '__| \ \ / / _` | __/ _ \
# |  __/| |  | |\ V / (_| | ||  __/
# |_|   |_|  |_| \_/ \__,_|\__\___|
#                                 

# Errors which include the package name and the subroutine name. This
# is for consistency with earlier versions of the module.

sub mycroak
{
    my ($message) = @_;
    my @caller = caller (1);
    croak $caller[3] . ' -- ' . $message;
}

# Given one argument with a slash or two arguments, return them as two
# arguments, and check there are one or two arguments.

sub getargs
{
    my ($ip, $pfx);
    if (@_ == 2) {
	($ip, $pfx) = @_;
    }
    elsif (@_ == 1) {
	($ip, $pfx) = split(m!/!, $_[0], 2)
    }
    else {
	mycroak "wrong number of arguments (need 1 or 2)";
    }
    return ($ip, $pfx);
}

# Match $ip against the regexes of type $type, or die.

sub match_or_die
{
    my ($ip, $type) = @_;
    # Instead of trying to construct a gigantic regex which only
    # allows two colons in a row, just check here.
    if ($ip =~ /:::/) {
	mycroak "invalid address $ip for type $type";
    }
    my $patterns = $ipv6_patterns{$type};
    for my $p (@$patterns) {
	# The last thing in the pattern is a code reference, so this
	# match indicates no matches were found.
	if (ref($p) eq 'CODE') {
	    mycroak "invalid address $ip for type $type";
	}
	if ($ip =~ $p) {
	    return;
	}
    }
}

# Make the bit mask for "in_network_of_size".

sub bitmask
{
    my ($j) = @_;
    my $bitmask = '1' x $j . '0' x (16 - $j);
    my $k = unpack("n",pack("B16", $bitmask));
    return $k;
}

#  ____                              
# |  _ \ __ _ _ __ ___  ___ _ __ ___ 
# | |_) / _` | '__/ __|/ _ \ '__/ __|
# |  __/ (_| | |  \__ \  __/ |  \__ \
# |_|   \__,_|_|  |___/\___|_|  |___/
#                                   

# Private parser

sub ipv6_parse_preferred
{
    my $ip = shift;
    match_or_die ($ip, 'preferred');
    my @pieces = split (/:/, $ip);
    splice (@pieces, 8);
    return map { hex } @pieces;
}

# Private parser

sub ipv6_parse_compressed
{
    my $ip = shift;
    my $type = 'compressed';
    match_or_die ($ip, $type);
    my $colons = ($ip =~ tr/:/:/);
    my $expanded = ':' x (9 - $colons);
    $ip =~ s/::/$expanded/;
    my @pieces = split (/:/, $ip, 8);
    return map { hex } @pieces;
}

sub parse_mixed_ipv6v4_compressed
{
    my $ip = shift;
    match_or_die ($ip, 'ipv6v4');
    my @result;
    my $v4addr;
    my $colons;
    $colons = ($ip =~ tr/:/:/);
    my $expanded = ':' x (8 - $colons);
    $ip =~ s/::/$expanded/;
    my @v6pcs = split(/:/, $ip, 7);
    $v4addr = $v6pcs[-1];
    splice(@v6pcs, 6);
    push @result, map { hex } @v6pcs;
    ipv4_validate($v4addr);
    my @v4pcs = split(/\./, $v4addr);
    splice(@v4pcs, 4);
    push @result, unpack("n", pack("CC", @v4pcs[0,1]));
    push @result, unpack("n", pack("CC", @v4pcs[2,3]));
    return @result;
}

# Private parser

sub ipv6_parse_ipv4
{
    my $ip = shift;
    match_or_die ($ip, 'ipv4');
    my @result;
    my $v4addr;
    my @v6pcs = split(/:/, $ip);
    $v4addr = $v6pcs[-1];
    splice(@v6pcs, 6);
    push @result, map { hex } @v6pcs;
    ipv4_validate($v4addr);
    my @v4pcs = split(/\./, $v4addr);
    push @result, unpack("n", pack("CC", @v4pcs[0,1]));
    push @result, unpack("n", pack("CC", @v4pcs[2,3]));
    return @result;
}

# Private parser

sub ipv6_parse_ipv4_compressed
{
    my $ip = shift;
    match_or_die ($ip, 'ipv4 compressed');
    my @result;
    my $v4addr;
    my $colons;
    $colons = ($ip =~ tr/:/:/);
    my $expanded = ':' x (8 - $colons);
    $ip =~ s/::/$expanded/;
    my @v6pcs = split(/:/, $ip, 7);
    $v4addr = $v6pcs[-1];
    splice(@v6pcs, 6);
    push @result, map { hex } @v6pcs;
    ipv4_validate($v4addr);
    my @v4pcs = split(/\./, $v4addr);
    splice(@v4pcs, 4);
    push @result, unpack("n", pack("CC", @v4pcs[0,1]));
    push @result, unpack("n", pack("CC", @v4pcs[2,3]));
    return @result;
}

# Private parser

sub ipv6_parse_base85
{
    if (! $base85ok) {
	carp "Math::Base85 is not installed";
	return ();
    }
    my $ip = shift;
    match_or_die ($ip, 'base85');
    my $r;
    my $bigint = Math::Base85::from_base85($ip);
    my @result;
    while ($bigint > 0) {
	$r = $bigint & 0xffff;
	unshift @result, sprintf("%d", $r);
	$bigint = $bigint >> 16;
    }
    foreach $r ($#result+1..7) {
        $result[$r] = 0;
    }
    return @result;
}

#  ____        _     _ _      
# |  _ \ _   _| |__ | (_) ___ 
# | |_) | | | | '_ \| | |/ __|
# |  __/| |_| | |_) | | | (__ 
# |_|    \__,_|_.__/|_|_|\___|
#                            

# Public

sub new
{
    my $proto = shift;
    my $class = ref ($proto) || $proto;
    my $maybe_ip = shift;
    my $parser = ipv6_chkip ($maybe_ip);
    if (ref $parser ne 'CODE') {
	mycroak "invalid IPv6 address $maybe_ip";
    }
    my @hexadecets = $parser->($maybe_ip);
    my $self = \@hexadecets;
    bless $self, $class;
    return $self;
}

# Public

sub ipv6_chkip
{
    my $ip = shift; 

    my $parser = undef;

    TYPE:
    for my $k (keys %ipv6_patterns) {
	my @patlist = @{$ipv6_patterns{$k}};
	PATTERN:
	for my $pattern (@patlist) {
	    last PATTERN if (ref($pattern) eq 'CODE');
	    if ($ip =~ $pattern) {
		$parser = $patlist[-1];
		last TYPE;
	    }
	}
    }
    return $parser;
}

# Public

sub ipv6_parse
{
    my ($ip, $pfx) = getargs (@_);

    if (! ipv6_chkip ($ip)) {
	mycroak "invalid IPv6 address $ip";
    }

    if (! defined $pfx) {
	return $ip;
    }

    $pfx =~ s/\s+//g;

    if ($pfx =~ /^[0-9]+$/) {
	if ($pfx > 128) {
	    mycroak "invalid prefix length $pfx";
	}
    }
    else {
	mycroak "non-numeric prefix length $pfx";
    }

    if (wantarray ()) {
	return ($ip, $pfx);
    }
    return "$ip/$pfx";
}

# Public

sub is_ipv6
{
    my $r;
    eval {
	$r = ipv6_parse (@_);
    };
    if ($@) {
	return undef;
    }
    return $r;
}

# Public

sub to_string_preferred
{
    my $self = shift;
    if (ref $self ne __PACKAGE__) {
	$self = Net::IPv6Addr->new ($self);
    }
    return v6part (@$self);
}

# Public

sub to_string_compressed
{
    my $self = shift;
    if (ref $self ne __PACKAGE__) {
	$self = Net::IPv6Addr->new ($self);
    }
    my $expanded = v6part (@$self);
    $expanded =~ s/^0:/:/;
    $expanded =~ s/:0/:/g;
    if ($expanded =~ s/:::::::/_/ or
	$expanded =~ s/::::::/_/ or
	$expanded =~ s/:::::/_/ or
	$expanded =~ s/::::/_/ or
	$expanded =~ s/:::/_/ or
	$expanded =~ s/::/_/
    ) {
        $expanded =~ s/:(?=:)/:0/g;
	$expanded =~ s/^:(?=[0-9a-f])/0:/;
	$expanded =~ s/([0-9a-f]):$/$1:0/;
	$expanded =~ s/_/::/;
    }
    return $expanded;
}

# Private

sub bytes
{
    my ($in) = @_;
    my $low = $in & 0xff;
    my $high = $in >> 8;
    return ($high, $low);
}

# Private

sub v4part
{
    my ($t, $b) = @_;
    return join('.', bytes ($t), bytes ($b));
}

# Private

sub v6part
{
    return join(':', map { sprintf("%x", $_) } @_);
}

# Public

sub to_string_ipv4
{
    my $self = shift;
    if (ref $self ne __PACKAGE__) {
	$self = Net::IPv6Addr->new ($self);
    }
    my $v6part = v6part (@$self[0..5]);
    my $v4part = v4part (@$self[6, 7]);
    return "$v6part:$v4part";
}

# Public

sub to_string_ipv4_compressed
{
    my $self = shift;
    if (ref $self ne __PACKAGE__) {
	$self = Net::IPv6Addr->new ($self);
    }
    my $v6part = v6part (@$self[0..5]);
    $v6part .= ':';
    $v6part =~ s/(^|:)(0:)+/::/;
    my $v4part = v4part (@$self[6, 7]);
    return "$v6part$v4part";
}

# Public

sub to_string_base85
{
    if (! $base85ok) {
	carp "Math::Base85 is not installed";
	return undef;
    }
    my $self = shift;
    if (ref $self ne __PACKAGE__) {
	$self = Net::IPv6Addr->new ($self);
    }
    my $bigint = new Math::BigInt("0");
    for my $i (@{$self}[0..6]) {
	$bigint = $bigint + $i;
	$bigint = $bigint << 16;
    }
    $bigint = $bigint + $self->[7];
    return Math::Base85::to_base85($bigint);
}

# Public

sub to_bigint
{
    my $self = shift;
    if (ref $self ne __PACKAGE__) {
	$self = Net::IPv6Addr->new ($self);
    }
    my $bigint = new Math::BigInt("0");
    for my $i (@{$self}[0..6]) {
	$bigint = $bigint + $i;
	$bigint = $bigint << 16;
    }
    $bigint = $bigint + $self->[7];
    $bigint =~ s/\+//;
    return $bigint;
}

# Public

sub to_array
{
    my $self = shift;
    if (ref $self ne __PACKAGE__) {
	$self = Net::IPv6Addr->new ($self);
    }
    return map {sprintf "%04x", $_} @$self;
}

# Public

sub to_intarray
{
    my $self = shift;
    if (ref $self ne __PACKAGE__) {
	$self = Net::IPv6Addr->new ($self);
    }
    return @$self;
}

# Public

sub to_string_ip6_int
{
    my $self = shift;
    if (ref $self ne __PACKAGE__) {
	$self = Net::IPv6Addr->new ($self);
    }
    my $hexdigits = sprintf("%04x" x 8, @$self);
    my @nibbles = ('INT', 'IP6', split(//, $hexdigits));
    my $ptr = join('.', reverse @nibbles);
    return $ptr . ".";
}

# Private - validate a given netsize

sub validate_netsize
{
    my ($netsize) = @_;
    if ($netsize !~ /^[0-9]+$/ || $netsize > 128) {
	mycroak "invalid network size $netsize";
    }
}

# Public

sub in_network_of_size
{
    my $self = shift;
    if (ref $self ne __PACKAGE__) {
	if ($self =~ m!(.+)/(.+)!) {
	    unshift @_, $2;
	    $self = $1;
	}
	$self = Net::IPv6Addr->new($self);
    }
    my $netsize = shift;
    if (! defined $netsize) {
	mycroak "network size not given";
    }
    $netsize =~ s!/!!;
    validate_netsize ($netsize);
    my @parts = @$self;
    my $i = int ($netsize / 16);
    if ($i < 8) {
	my $j = $netsize % 16;
	if ($j) {
	    # If $netsize is not a multiple of 16, truncate the lowest
	    # 16-$j bits of the $ith element of @parts.
	    $parts[$i] &= bitmask ($j);
	    # Jump over this element.
	    $i++;
	}
	# Set all the remaining lower parts to zero.
	for ($i..$#parts) {
	    $parts[$_] = 0;
	}
    }
    return bless \@parts;
}

# Public

sub in_network
{
    my $self = shift;
    if (ref $self ne __PACKAGE__) {
	$self = Net::IPv6Addr->new ($self);
    }
    my ($net, $netsize) = getargs (@_);
    unless (defined $netsize) {
	mycroak "not enough parameters, need netsize";
    }
    $netsize =~ s!/!!;
    validate_netsize ($netsize);
    if (! ref $net) {
	$net = Net::IPv6Addr->new($net);
    }
    my @s = $self->in_network_of_size($netsize)->to_intarray;
    my @n = $net->in_network_of_size($netsize)->to_intarray;
    my $i = int ($netsize / 16) + 1;
    if ($i > $#s) {
	$i = $#s;
    }
    for (0..$i) {
	if ($s[$_] != $n[$_]) {
	    return undef;
	}
    }
    return 1;
}

# Public

sub from_bigint
{
    my ($big) = @_;
    # Input is a scalar or a Math::BigInt object.
    if (! ref ($big)) {
	$big = Math::BigInt->new ($big);
    }
    if (ref ($big) ne 'Math::BigInt') {
	mycroak "Cannot process non-scalar, non-Math::BigInt input";
    }
    # Convert the number to a hexadecimal string
    my $hex = $big->to_hex ();
    # Pad if necessary for the colon placement
    if (length ($hex) < 32) {
	my $leading = '0' x (32 - length ($hex));
	$hex = $leading . $hex;
    }
    # Reversing the string makes adding colons with a substitution
    # operator easier.
    my $ipr = reverse $hex;
    $ipr =~ s/(....)/$1:/g;
    $ipr = reverse $ipr;
    # Remove the excess colon.
    $ipr =~ s/^://;
    # Should be OK now, let "new" handle any further issues.
    return Net::IPv6Addr->new ($ipr);
}

1;