GeniHRN.pm.in 11.5 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2009-2015 University of Utah and the Flux Group.
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
# 
# {{{GENIPUBLIC-LICENSE
# 
# GENI Public License
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
# 
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
# 
# }}}
29 30 31 32 33
#
package GeniHRN;

use strict;
use Exporter;
34
use Carp;
35
use vars qw(@ISA @EXPORT);
36
use overload (fallback => 1, '""' => 'Stringify');
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

@ISA    = "Exporter";
@EXPORT = qw ( );

# References:
#
#   GMOC Proposal: "Use URN as GENI identifiers" version 0.2, Viecco, 2009
#   RFC 2141, "URN Syntax", Moats, 1997
#   RFC 3151, "A URN Namespace for Public Identifiers", Walsh, 2001
#   RFC 3986, "URI Generic Syntax", Berners-Lee, 2005
#   RFC 3987, "Internationalised Resource Identifiers", Duerst, 2005
#   RFC 4343, "DNS Case Insensitivity Clarification", Eastlake, 2006

sub Unescape($)
{
    my ($uri) = @_;

    my $norm = "";
    while( $uri =~ /^([^%]*)%([0-9A-Fa-f]{2})(.*)$/ ) {
	$norm .= $1;
	my $val = hex( $2 );
	# Transform %-encoded sequences back to unreserved characters
	# where possible (see RFC 3986, section 2.3).
	if( $val == 0x2D || $val == 0x2E ||
	    ( $val >= 0x30 && $val <= 0x39 ) ||
	    ( $val >= 0x41 && $val <= 0x5A ) ||
	    $val == 0x5F ||
	    ( $val >= 0x61 && $val <= 0x7A ) ||
	    $val == 0x7E ) {
	    $norm .= chr( $val );
	} else {
	    $norm .= "%" . $2;
	}
	$uri = $3;
    }
    $norm .= $uri;

    return $norm;
}

sub IsValid($)
{
    my ($hrn) = @_;

81 82 83 84 85
    if (!defined($hrn)) {
	carp("GeniHRN::IsValid: hrn is undefined");
	return 0;
    }

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
    # Reject %00 sequences (see RFC 3986, section 7.3).
    return undef if $hrn =~ /%00/;

    # We accept ANY other %-encoded octet (following RFC 3987, section 5.3.2.3
    # in favour of RFC 2141, section 5, which specifies the opposite).
    $hrn = Unescape( $hrn );

    # The "urn" prefix is case-insensitive (see RFC 2141, section 2).
    # The "publicid" NID is case-insensitive (see RFC 2141, section 3).
    # The "IDN" specified by Viecco is believed to be case-sensitive (no
    #   authoritative reference known).
    # We regard Viecco's optional resource-type specifier as being
    #   mandatory: partly to avoid ambiguity between resource type
    #   namespaces, and partly to avoid ambiguity between a resource-type
    #   and a resource-name containing (escaped) whitespace.
101
    return $hrn =~ m'^[uU][rR][nN]:[pP][uU][bB][lL][iI][cC][iI][dD]:IDN\+[A-Za-z0-9.-]+(?::[A-Za-z0-9._-]+)*\+\w+\+(?:[-!$()*,./0-9:=@A-Z_a-z]|(?:%[0-9A-Fa-f][0-9A-Fa-f]))+$';
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
# Perform RFC 3151 transcription (from a string of legal public identifier
# characters to a URN (sub)string).
sub Transcribe($)
{
    my ($str) = @_;

    # Perform whitespace normalisation (see RFC 3151, section 1.1).
    $str =~ s/^[ \t\r\n]*//;
    $str =~ s/[ \t\r\n]*$//;
    # The replacement with a space is arbitrary and temporary; the space
    # will later be replaced with a '+' below (we can't directly use a '+'
    # yet, because we want to treat literal '+'s in the input differently).
    $str =~ s/[ \t\r\n]+/ /g;

    # The order here is critical: the intent is that from now on, at most
    # one transformation will apply to any character.
    $str =~ s/%/%25/g;
    # '% characters have been escaped; it is now unambiguous to translate
    # sequences that will contain '%'s.
    $str =~ s/#/%23/g;
    $str =~ s/'/%27/g;
    $str =~ s/\+/%2B/g;
    $str =~ s/;/%3B/g;
    $str =~ s/\?/%3F/g;
    # '+' characters have been escaped; it is now safe to translate ' ' to '+'.
    $str =~ s/ /+/g;
    # ';' characters have been escaped; it is now safe to translate '::' to
    # ';'.
    $str =~ s/::/;/g;
    # '::' sequences have been translated; any remaining ':' character must
    # have been a singleton, and can now be escaped.
    $str =~ s/:/%3A/g;
    # All ':' characters have been escaped; we can now translate '//' to ':'.
    $str =~ s|//|:|g;
    # '//' sequences have been translated; any remaining '/' character must
    # have been a singleton, and can now be escaped.
    $str =~ s|/|%2F|g;

    return $str;
}

# Perform RFC 3151 inverse transcription (from a URN (sub)string to a
# (partial) public identifier).
sub Untranscribe($)
{
    my ($str) = @_;

    # Do this in exactly the opposite order to Transcribe, for exactly
    # the same reason.
    $str =~ s|%2F|/|gi;
    $str =~ s|:|//|g;
    $str =~ s/%3A/:/gi;
    $str =~ s/;/::/g;
    $str =~ s/\+/ /g;
    $str =~ s/%3F/?/gi;
    $str =~ s/%3B/;/gi;
    $str =~ s/%2B/+/gi;
    $str =~ s/%27/'/gi;
    $str =~ s/%23/#/gi;
    $str =~ s/%25/%/gi;

    # Note that whitespace normalisation is inherently lossy, so we couldn't
    # undo it even if we wanted to: all leading and trailing whitespace is
    # irretrievably gone, and all internal whitespace sequences have collapsed
    # to single space characters.
    return $str;
}

172 173 174
# Break a URN into (sub-)authority, type, and ID components.  There
# might be further structure in the authority part, but we'll ignore
# that for now.
175
sub Parse($;$)
176
{
177
    my ($token, $hrn) = @_;
178

179 180 181 182 183 184
    #
    # When called as a Class method, we want to return an object.
    #
    if (@_ == 1) {
	$hrn = $token;
    }
185 186 187 188
    if (!defined($hrn)) {
	carp("GeniHRN::Parse: hrn is undefined");
	return 0;
    }
189 190
    return undef if !IsValid( $hrn );

191 192 193
    if (@_ == 2) {
	return GeniHRN->new($hrn);
    }
194 195 196 197
    $hrn = Unescape( $hrn );

    $hrn =~ /^[^+]*\+([^+]+)\+([^+]+)\+(.+)$/;

198
    return ($1, $2, Untranscribe( $3 ));
199 200
}

201 202 203 204 205
# Generate a ProtoGENI URN.  Note that this is a little bit more
# restrictive than the general GENI naming scheme requires: we don't
# currently apply transcription to the authority or type fields,
# though it would be easy enough to add if anybody were perverse
# enough to want it.
206 207 208 209 210 211 212
sub Generate($$$)
{
    my ($authority, $type, $id) = @_;

    # Assume that any sub-authorities are already encoded (see
    # RFC 3151, section 2).  We don't currently handle sub-authorities,
    # so this is irrelevant for now.
213 214 215 216 217 218

    # Apply case normalisation to the authority; see RFC 3987, section
    # 5.3.2.1.  According to section 5.3.3, we are supposed to go
    # further and perform RFC 3490 ToASCII UseSTD3ASCIIRules and
    # AllowUnassigned and RFC 3491 Nameprep validation to interpret IRIs,
    # but quite frankly I think I've done more than enough RFC chasing already.
219 220 221
    $authority =~ tr/A-Z/a-z/;
    return undef if $authority !~ /^[-.0-9A-Za-z:]+$/;
    return undef if $type !~ /^[-.0-9A-Z_a-z~]+$/;
222
    return undef if $id !~ m{^[-\t\n\r !#$%'()*+,./0-9:;=?\@A-Z_a-z]+$};
223

224 225
    return "urn:publicid:IDN+" . $authority . "+" . $type . "+" .
        Transcribe( $id );
226 227 228 229 230 231 232 233 234 235 236 237 238 239
}

# Apply scheme-based (and other) normalisations to a URN (see RFC 3987,
# section 5.3).  This is conformant to RFC 2141, section 5 (we recognise
# all of those lexical equivalences, and introduce additional ones as
# is permitted).  We do not perform deep interpretation of the URN, so
# this procedure can and should be applied to foreign (non-ProtoGENI) URNs.
sub Normalise($)
{
    my ($hrn) = @_;

    return undef if !IsValid( $hrn );

    my ($authority, $type, $id) = Parse( $hrn );
240
    return Generate( $authority, $type, $id );
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
}

sub Equal($$)
{
    my ($hrn0, $hrn1) = @_;

    return undef if !IsValid( $hrn0 ) || !IsValid( $hrn1 );

    my $norm0 = Normalise( $hrn0 );
    my $norm1 = Normalise( $hrn1 );

    return $norm0 eq $norm1;
}

sub Authoritative($$)
{
    my ($hrn, $authority) = @_;

    $authority =~ tr/A-Z/a-z/;
    my @hrn = Parse( $hrn );
    $hrn[ 0 ] =~ tr/A-Z/a-z/;

    return $hrn[ 0 ] eq $authority;
}

266 267 268 269 270 271 272 273 274 275 276 277 278
sub SameDomain($$)
{
    my ($a, $b) = @_;
    my ($auth_a) = Parse($a);
    my ($auth_b) = Parse($b);
    my ($dom_a)  = split(":", $auth_a);
    my ($dom_b)  = split(":", $auth_b);
    $dom_a =~ tr/A-Z/a-z/;
    $dom_b =~ tr/A-Z/a-z/;

    return $dom_a eq $dom_b;
}

279 280 281 282 283 284 285 286 287 288 289 290 291
# Helper functions to make special cases slightly less messy:

# Generate an interface URN given a node and an interface ID on that node.
# This will probably fail horribly if the node ends and/or the interface
# begins with a '/' character, but anybody who does that probably deserves
# what they get.
sub GenerateInterface($$$)
{
    my ($authority,$node,$interface) = @_;

    return Generate( $authority, "interface", $node . "//" . $interface );
}

292 293 294 295 296
# Undo the GenerateInterface into a authority/name/interface triplet.
sub ParseInterface($)
{
    my ($urn) = @_;

297 298 299 300
    if (!defined($urn)) {
	carp("GeniHRN::ParseInterface: urn is undefined");
	return 0;
    }
301 302 303 304
    # Allow as instance method.
    if (ref($urn)) {
	$urn = $urn->urn();
    }
305 306 307 308 309 310 311 312 313
    my ($authority,$type,$id) = Parse( $urn );

    return undef if $type ne "interface";

    return undef unless $id =~ m{(.*)//(.*)};

    return ( $authority, $1, $2 );
}

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
sub ParseImage($)
{
    my ($urn) = @_;

    if (!defined($urn)) {
	carp("GeniHRN::ParseImage: urn is undefined");
	return 0;
    }
    # Allow as instance method.
    if (ref($urn)) {
	$urn = $urn->urn();
    }
    my ($authority,$type,$id) = Parse( $urn );

    return undef if $type ne "image";

    my ($ospid,$os,undef,$vers) = ($id =~ m{([^/]+)//([^/]+)(//(\d+))?});
    return undef if (!defined($ospid));

    return ($authority, $ospid, $os, $vers);
}
sub GenerateImage($$$$)
{
    my ($authority,$pid,$os,$vers) = @_;

    if (defined($vers)) {
	return Generate($authority, "image", $pid . "//" . $os . "//" . $vers);
    }
    return Generate($authority, "image", $pid . "//" . $os);
}

345 346 347 348 349 350 351 352 353 354 355 356 357 358
#
# OO implementation, tired of typing same stuff all the time
#
sub new($$)
{
    my ($class, $urn) = @_;

    return $urn
	if (ref($urn) && ref($urn) eq "GeniHRN");

    if (! IsValid($urn)) {
	print STDERR "GeniHRN::new: invalid urn $urn\n";
	return undef;
    }
359
    my ($authority,$type,$id) = GeniHRN::Parse($urn);
360
    my $self = {};
361 362 363 364 365 366 367
    $self->{'urn'}        = $urn;
    $self->{'type'}       = $type;
    $self->{'id'}         = $id;
    $self->{'authority'}  = $authority;
    my ($domain,$subauth) = split(":", $authority);
    $self->{'domain'}     = $domain;
    $self->{'subauth'}    = $subauth;
368 369 370 371 372 373 374 375
    
    bless($self, $class);
    return $self;
}
# accessors
sub field($$)           { return ($_[0]->{$_[1]}); }
sub urn($)		{ return field($_[0], "urn"); }
sub asString($)         { return $_[0]->urn(); }
376
sub authority($)	{ return field($_[0], "authority"); }
377
sub domain($)		{ return field($_[0], "domain"); }
378
sub subauth($)		{ return field($_[0], "subauth"); }
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
sub type($)		{ return field($_[0], "type"); }
sub id($)		{ return field($_[0], "id"); }
sub IsAuthority()       { return $_[0]->type() =~ /^authority$/i ? 1 : 0; }
sub IsSA($)		{ return $_[0]->id() =~ /^SA$/i ? 1 : 0; }
sub IsCM($)		{ return $_[0]->id() =~ /^CM$/i ? 1 : 0; }

#
# Stringify for text context.
#
sub Stringify($)
{
    my ($self) = @_;
    
    return $self->{"urn"};
}

395 396
# _Always_ make sure that this 1 is at the end of the file...
1;