lib/NOLookup/RDAP/RDAPLookup.pm untested

filter: Statementstmt 0.0% 0 / 845 Branchbran 0.0% 0 / 432 Conditioncond 0.0% 0 / 195 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 45 Podpod 0.0% 0 / 21 totaltotal 0.0% 0 / 1538 CC 216 SCAR 69.3
CC
216
Cov
0%
validate_and_analyze
2756.0
_fetch_get_pages
1640.0
rdap_obj_as_string
1260.0
CRAP 1017.4
1 package NOLookup::RDAP::RDAPLookup;
2  
3 use warnings;
4 use strict;
5 use POSIX qw(locale_h);
6 use URI::Encode qw(uri_encode);
7 use URI;
8 use JSON;
9 use base qw(Class::Accessor::Chained); ## Provides a new() method
10 use Net::DNS::Domain;
11 use Net::IP;
12 use List::MoreUtils qw(any);
13 use Text::Wrap;
14 use base qw(Net::RDAP);
15 use Net::RDAP::EPPStatusMap;
16 use Net::RDAP::Error;
17 use IO::Socket qw / AF_INET AF_INET6 /;
18 use Sys::HostIP;
19 use Data::Validate::IP qw(is_ip);
20 use Regexp::Common qw /net/;
21 use Net::LibIDN ':all';
22 use Data::Validate::Domain qw(is_hostname is_domain);
23 use NOLookup;
24  
25 use Data::Dumper;
26 $Data::Dumper::Indent=1;
27  
28 our $VERSION = $NOLookup::VERSION;
29  
30 use vars qw(@ISA @EXPORT_OK);
31  
32 @ISA = qw( Exporter Class::Accessor::Chained Net::RDAP);
33 @EXPORT_OK = qw / $RDAP_LOOKUP_ERR_NO_CONN
34  
35 $RDAP_LOOKUP_ERR_QUOTA_EXCEEDED
36 $RDAP_LOOKUP_ERR_NO_ACCESS
37 $RDAP_LOOKUP_ERR_REFERRAL_DENIED
38 $RDAP_LOOKUP_ERR_OTHER
39 $RDAP_LOOKUP_ERR_NO_MATCH
40 $RDAP_LOOKUP_ERR_NO_CONFORMANCE
41 $RDAP_LOOKUP_ERR_FORBIDDEN
42 $RDAP_LOOKUP_ERR_INVALID
43 $RDAP_LOOKUP_NOT_AUTHORIZED
44  
45 %rdap_head_get_method_args
46 %rdap_get_method_args
47 $sepln
48  
49 $RDAP_LAYER_UNSET_OR_UNKNOWN
50 %RDAP_REGISTERED_LAYERS
51  
52 %RDAP_FIELDSETS
53  
54 $RDAP_PAGE_SIZE
55 $RDAP_ENTITY_QUOTA_PAGES
56  
57 /;
58  
59 # Some accessor methods.
60 # Those starting with '_' are meant for internal use.
61 my @methods = qw /
62  
63 warning
64 error
65 status
66 description
67 access_layer
68 is_a_search
69  
70 size
71 total_size
72  
73 total_no_pages
74  
75 page_size
76 page_number
77 first_page
78 cur_page
79 next_page
80 prev_page
81  
82 get_href_page_cursor
83 result
84 raw_json_decoded
85  
86 _method
87 _uri
88 _full_url
89  
90 /;
91  
92 __PACKAGE__->mk_accessors(
93 @methods
94 );
95  
96 # Connection problems
97 our $RDAP_LOOKUP_ERR_NO_CONN = 100;
98  
99 # Controlled refuses
100 our $RDAP_LOOKUP_ERR_QUOTA_EXCEEDED = 101;
101 our $RDAP_LOOKUP_ERR_NO_ACCESS = 102;
102 our $RDAP_LOOKUP_ERR_REFERRAL_DENIED = 103;
103 our $RDAP_LOOKUP_ERR_OTHER = 104;
104 our $RDAP_LOOKUP_ERR_NO_MATCH = 105;
105 our $RDAP_LOOKUP_ERR_NO_CONFORMANCE = 106;
106 our $RDAP_LOOKUP_ERR_FORBIDDEN = 107;
107 our $RDAP_LOOKUP_NOT_AUTHORIZED = 108;
108 our $RDAP_LOOKUP_ERR_INVALID = 109;
109  
110 # Layer data
111 our $RDAP_LAYER_UNSET_OR_UNKNOWN = 'unset-or-unknown';
112  
113 # expected and known layers
114 our %RDAP_REGISTERED_LAYERS = (
115 anonymous => 1,
116 registrar => 1,
117 registry => 1,
118 specialuser => 1
119 );
120  
121 # known fieldsets, default is empty, which does the same as 'id'
122 our %RDAP_FIELDSETS = (
123 'id' => 1,
124 'full' => 1,
125 );
126  
127 ##
128 # Page control defaults.
129 # * $RDAP_PAGE_SIZE should be set to the page size used by the rdap
130 # server.
131 # * $RDAP_ENTITY_QUOTA_PAGES should be set to a value big enough to fetch all
132 # domains on a single subscriber handle. For .no the quota is 100,
133 # but special entities can have up to nearly 800 domains.
134 # Thus RDAP_PAGE_SIZE*RDAP_RDAP_ENTITY_QUOTA_PAGES should be at
135 # least 800.
136 our $RDAP_PAGE_SIZE = 50;
137 our $RDAP_ENTITY_QUOTA_PAGES = 16;
138  
139 # We turn the search count on always, for convenience. The user cannot
140 # control this parameter.
141 my $URI_ARG_COUNT = '1'; # 'true' or empty
142  
143 # 'brief' => 0, # Not yet implemented
144  
145 my %default_matchspec = (
146 "m_header__X-Access-Layer" => [ keys %RDAP_REGISTERED_LAYERS ]
147 );
148  
149 my $RDAP_TIMEOUT = 60; # secs (default is 180 secs but we want shorter time).
150  
151 # Default API service URL
152 my $SERVICE_URL = "https://rdap.norid.no";
153  
154 our $sepln = '='x60 . "\n";
155  
156 ############
157 #
158 # RDAP API. See section 'About the Norid RDAP API' below for more info.
159 #
160  
161 # Both HEAD and GET methods, HEAD used if 'check'.
162 our %rdap_head_get_method_args = (
163 DBDN => 'domain/',
164 EBEH => 'entity/',
165 NBNH => 'nameserver_handle/'
166 );
167  
168 # Not used RBRH => 'registrar/', same as EBEH => 'entity/'
169  
170 # GET only methods
171 our %rdap_get_method_args = (
172 DBDN => 'domains?name=',
173 DBRH => 'domains?registrant=',
174 DBID => 'domains?identity=',
175 DBNI => 'domains?nsIp=',
176 DBNL => 'domains?nsLdhName=',
177
178 NBNN => 'nameservers?name=',
179 NBNI => 'nameservers?ip=',
180  
181 EBFN => 'entities?fn=',
182 EBID => 'entities?identity=',
183 );
184  
185  
186 # Sort keys (not yet in use)
187 my %sort_keys = (
188 domains => {
189 registrationDate => 1,
190 lastChangedDate => 1,
191 expirationDate => 1,
192 name => 1,
193 },
194 nameservers => {
195 registrationDate => 1,
196 lastChangedDate => 1,
197 name => 1,
198 },
199 entities => {
200 registrationDate => 1,
201 lastChangedDate => 1,
202 handle => 1,
203 fn => 1,
204 org => 1,
205 country => 1,
206 cc => 1,
207 city => 1,
208 },
209 );
210  
211 # No info info in output
212 my $NO_FURTHER_INFO = " (no further information available)\n\n";
213  
214 #my $ht;
215  
216 ##
217 # RDAP API conformance values.
218 # This library supports and expects the following conformance values.
219 # if other values are returned, the library _may_ need an upgrade, so the
220 # lookup will simply fail if any conformance mismatch is detected.
221 #
222  
223 my %rdapConformance_vals_supported = (
224 'rdap_level_0' => 1,
225 'rdap_objectTag_level_0' => 1,
226 'norid_level_0' => 1,
227 'subsetting_level_0' => 1,
228 'sorting_level_0' => 1,
229 'paging_level_0' => 1,
230 );
231  
232  
233 # Set an env var to suppress warnings from Net::RDAP
234 unless ($ENV{'NET_RDAP_UA_DEBUG'}) {
235 $ENV{'NET_RDAP_UA_DEBUG'} = 0;
236 }
237  
238 =head1 Methods
239  
240 Module methods.
241  
242 Those starting with '_' are meant for internal use.
243  
244 =cut
245  
246  
247 =head2 new
248  
249 new handles the following parameters:
250  
251 {
252 use_cache => <0|1>,
253 debug => <0..8>,
254 service_url => <0|service_url,
255 norid_header_secret => <0|test_secret>,
256 norid_header_proxy => <0|1>,
257 norid_referral_ip => <0|1|ip-address>,
258 bauth_username => <0|bauth_username>,
259 bauth_password => <0|bauth_password>,
260 fieldset => <0|fieldset>
261 access_layers => { layer1=>1, layer2=>2, .. }
262 page_size => <0|page size>, default $RDAP_PAGE_SIZE
263 cursor => <0|cursor>
264 nopages => <0|nopages>, default $RDAP_ENTITY_QUOTA_PAGES
265 insert_page_info => <0|1>
266 force_ipv => <0|4|6>
267 }
268  
269 All parameters are optional:
270  
271 * use_cache:
272 - 1: activate Net::RDAP lookup cache, see Net::RDAP for use,
273 Note: usage not needed or tested for this lib.
274  
275 * debug:
276 - 0 : debug off
277 - 1 : debug output from this module
278 - 2 : headers output from LWP UA callback
279 - 3 : Debug output from Net::RDAP::UA (headers and contents)
280 - 4-8: Debug output using LWP::ConsoleLogger::Easy,
281 which then must be installed
282  
283 * service_url:
284 - the full http(s)-address of the Norid RDAP-servie to
285 be accessed.
286 - default is $SERVICE_URL above.
287  
288 * norid_header_secret:
289 - access token for layered access, and
290 the token is sent in the 'X-RDAP-Secret' header.
291  
292 * norid_header_proxy :
293 - Norid internal use only.
294 - true if the calling client can act as a proxy,
295 and the header 'X-RDAP-Web-Proxy' is then set to 1.
296  
297 * norid_referral_ip :
298 - Norid internal use only.
299 - set if the calling client ip address argument shall be sent. When set:
300 - if the argument passed is a pure integer, use the local ip-address as value.
301 - if the argument passed is a valid ip address, use that address
302 as value. This is the normal variant to be used to pass a proper client
303 ip address.
304 - the ip-address is passed to the server in the '?client_ip=<ip-address>'
305 argument.
306  
307 * bauth_username:
308 - Basic authentication username
309 For a Norid registrar RDAP user where
310 - RDAP username is : 'rdapuser',
311 - Norid registrar id is: 'reg1234'
312 the basic username must be set as follows: 'rdapuser@reg1234'.
313  
314 * bauth_password:
315 - Basic authentication password
316  
317 * fieldset:
318 - Undef or one of the valid fieldSets to determine how much data
319 should be returned for search hits
320 If rate limiting becomes a problem, fieldset='full' could be
321 considered.
322  
323 * access_layers:
324 - Optional. Access_layers to be expected and handled. Replaces the
325 preconfigered and default ones in %RDAP_REGISTERED_LAYERS.
326  
327 Paging parameters:
328  
329 * page_size:
330 Page size for the the RDAP service.
331 Recommended set by the caller, as the lib may have wrong default
332 values.
333  
334 * cursor:
335 - Undef or a cursor string to be used in succeeding page lookups,
336 undef for first page.
337  
338 * nopages:
339 - max number of pages from cursor (1..x, default 10).
340 The pageSize in the RDAP service decides the number of hits per
341 page.
342  
343  
344 * insert_page_info:
345 - Text formatting option, insert page info in the text if set.
346  
347 Paging parameters set by lib, read them only:
348  
349 * total_no_pages:
350 Total number of pages that can be fetched with a search combo.
351 Calculated as total_size / page_size and set by lib as soon as
352 we know the value.
353  
354 * page_number:
355 The page number signalled by the rdap service.
356  
357 * first_page|cur_page|prev_page|next_page:
358 - Page hrefs set by lib when a search is performed.
359  
360 Various:
361  
362 * force_ipv:
363 - force use of ip protocl version, 0/undef is default, else set to
364 4 or 6
365  
366 =cut
367  
368 sub new {
369 my ($self, $args)=@_;
370
371 # defaults
372 $args->{service_url} = $SERVICE_URL unless ($args->{service_url});
373
374 if ($args->{norid_referral_ip} && $args->{norid_referral_ip} =~ m/^\d+$/) {
375 # Set to true (a pure number) - then select a local ip-address
376 delete($args->{norid_referral_ip});
377 my $ip = get_my_ip_address();
378 $args->{norid_referral_ip} = $ip if ($ip);
379 }
380  
381 # If both secret and basic auth params are set, select basic auth,
382 # delete secret
383 # FIXME: Remove secret support when totally replaced by auth rules.
384 delete $args->{norid_header_secret} if ($args->{bauth_username});
385  
386 # This debug dumps everything using $Net::RDAP::UA::DEBUG
387 if ($args->{'debug'} && $args->{debug} == 3) {
388 $Net::RDAP::UA::DEBUG = $args->{'debug'};
389 }
390  
391 my $ro = $self->SUPER::new($args);
392  
393 # Activate requested protocol, if set
394 # https://metacpan.org/pod/IO::Socket::IP
395 if ($args->{force_ipv}) {
396 my $ua = $ro->ua;
397  
398 if ($args->{force_ipv} == 4) {
399 # Use ipv4 only sockets and addresses
400 print STDERR "RDAPLookup: Connecting forcibly over ipv4\n" if ($args->{debug});
401 $ua->ssl_opts(Domain => AF_INET);
402 } elsif ($args->{force_ipv} == 6) {
403 print STDERR "RDAPLookup: Connecting forcibly over ipv6\n" if ($args->{debug});
404 $ua->ssl_opts(Domain => AF_INET6);
405 }
406 # Also, on force_ipv, disable ssl verify
407 use IO::Socket::SSL;
408 $ua->ssl_opts( verify_hostname => 0, SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE);
409 print STDERR "RDAPLookup: Connecting forcibly, also turn of SSL verify mode\n" if ($args->{debug});
410 }
411  
412 return $ro;
413
414 }
415  
416 =head2 lookup
417  
418 Do an RDAP lookup.
419  
420 - $query : Specifies the query string.
421 - $check : Specifies if http 'head' shall be done, default is 'get'.
422 - $nameservers: Must be set to 1 for nameserver_name search
423 and 2 for a domains by nameserver name search
424 - $entity : Must be set to true for entity lookup, in which case the query should
425 identify an entity, like:
426 - a domain name or a handle
427 For a search, this is more complex:
428 - For identities (orgno, N.XXX.YYY or registrant handles),
429 a search domains by identity/registrant is done as default.
430 To force the search to search for entities by
431 identity/registrant instead, this option must be
432 set.
433  
434 =cut
435  
436 sub lookup {
437 my ($self, $query, $check, $nameservers, $entity ) = @_;
438  
439 #print STDERR "RDAPLookup: lookup on query: $query, check: ", $check || 0, ", nameservers: ", $nameservers || 0, ", entity: ", $entity || 0, "\n";
440  
441 unless ($self->validate_and_analyze($query, $check, $nameservers, $entity)) {
442 # errno has already been set
443 return $self;
444 }
445 # _method (head or get) and args are set in $self
446 $self->_lookup_rdap($query, $self->_method, $self->_uri);
447
448 }
449  
450 =head2 _lookup_rdap
451  
452 Do an RDAP HEAD or GET lookup.
453  
454 - $http_type: 'head' or 'get'
455 - $uri : full arguments to base URI, identifying the actual lookup
456 method and args
457 - other args as passed in $self.
458  
459 =cut
460  
461 sub _lookup_rdap {
462 my ($self, $query, $http_type, $uri ) = @_;
463  
464 my $ua = $self->ua;
465  
466 my $debug = $self->{debug} || 0;
467  
468 # Debug >= 4: Use LWP::ConsoleLogger::Easy debug
469 if ($debug >= 4) {
470 # debug only for dev env.
471 print STDERR "LWP::ConsoleLogger::Easy usage is commented out in code. If you need it, uncomment in the code!\n";
472 #use LWP::ConsoleLogger::Easy qw /debug_ua /;
473 #debug_ua ( $ua, $self->{debug});
474 }
475  
476 # Debug == 2: Show headers via callback methods
477 if ($debug == 2) {
478 $ua->add_handler(
479 "request_send",
480 sub {
481 print STDERR $sepln;
482 print STDERR "-- UA Debug: HTTP request headers:\n";
483 my $msg = shift; # HTTP::Message
484 print STDERR $msg->headers_as_string(), "\n";
485 return;
486 }
487 );
488
489 $ua->add_handler(
490 "response_done",
491 sub {
492 print STDERR "-- UA Debug: HTTP response headers: ---- \n";
493 my $msg = shift; # HTTP::Message
494 print STDERR $msg->headers_as_string(), "\n";
495 print STDERR $sepln;
496 return;
497 }
498 );
499 }
500  
501 ####
502 # Catching response header values are a pain, must be done by a handler,
503 # which only catches known values, not unknown or unexpected,
504 # like if a new layer name suddenly comes into question.
505 # https://metacpan.org/pod/HTTP::Config#Matching
506 unless ($self->{access_layers}) {
507 $ua->add_handler( response_header => \&_ua_callback, %default_matchspec );
508 #print STDERR "Using default access_layers: ", Dumper \%default_matchspec;
509 } else {
510 my %passed_matchspec = (
511 "m_header__X-Access-Layer" => [ keys %{$self->{access_layers}} ]
512 );
513 $ua->add_handler( response_header => \&_ua_callback, %passed_matchspec );
514 #print STDERR "Using application passed access_layers: ", Dumper \%passed_matchspec;
515 }
516  
517 $ua->default_header( Charset => "UTF-8");
518 $ua->default_header( 'Content-Type' => "application/rdap+json");
519  
520 if ($self->{norid_header_secret}) {
521 # Use Norid RDAP layer secret header
522 $ua->default_header( 'X-RDAP-Secret' => $self->{norid_header_secret});
523 }
524  
525 if ($self->{norid_header_proxy}) {
526 # Use Norid RDAP proxy headers
527 $ua->default_header( 'X-RDAP-Web-Proxy' => 1);
528 }
529  
530 my $URL = $self->{service_url} . "/$uri";
531  
532 if ($self->{norid_referral_ip}) {
533 my $a = '?';
534 if ($URL =~ m/\?/) {
535 # args already exists, use '&' for extra arg
536 $a = '&';
537 }
538 $URL .= $a ."client_ip=" . $self->{norid_referral_ip};
539 }
540
541 $self->_full_url($URL);
542  
543 if ($debug == 1) {
544 print STDERR $sepln;
545 print STDERR "RDAPLookup: _lookup_rdap (v$VERSION) called with:\n";
546 print STDERR " URL : '$URL'\n";
547 print STDERR " norid proxy is: ", $self->{norid_header_proxy} , "\n" if ($self->{norid_header_proxy});
548 print STDERR " secret is : ", $self->{norid_header_secret}, "\n" if ($self->{norid_header_secret});
549 print STDERR " bauth_username: ", $self->{bauth_username}, "\n" if ($self->{bauth_username});
550 print STDERR " referral_ip : ", $self->{norid_referral_ip} , "\n" if ($self->{norid_referral_ip});
551 print STDERR " is_a_search : ", $self->is_a_search || 0, "\n";
552 }
553  
554 my $resp;
555  
556 # RDAP CHECK = HEAD?
557 if ($http_type eq 'head') {
558 # An RDAP HEAD operation. Head is not supported by Net::RDAP,
559 # so call it via the already created UA
560 $resp = $ua->head($URL);
561  
562 my $access_layer = $self->ua->{response_headers}->{'x-access-layer'} ||
563 $RDAP_LAYER_UNSET_OR_UNKNOWN;
564  
565 $self->access_layer($access_layer);
566
567 unless ($resp->is_success) {
568 $self->error(_map_rdap_error($query, $resp->code));
569 $self->status($resp->status_line);
570 }
571  
572 if ($self->{debug} == 100) {
573 print STDERR "Net::RDAP self for HEAD: ", Dumper $self, "\n";
574 #print STDERR "Net::RDAP resp for HEAD: ", Dumper $resp, "\n";
575 }
576
577 return $self;
578 }
579  
580  
581 ####
582 # A GET lookup, search or simple GET?
583 # Now the lookup itself
584 ###
585 $resp = $self->_fetch_get_pages($query, $URL);
586
587 return $self;
588 }
589  
590 =head2 _fetch_get_pages
591  
592 Handle RDAP GET operations.
593  
594 If search, loop and fetch the requested number of pages from the
595 offset set by the cursor parameter.
596  
597 =cut
598  
599 sub _fetch_get_pages {
600 my ($self, $query, $URL) = @_;
601  
602 my $ua = $self->ua;
603 my $debug = $self->{debug} || 0;
604  
605 my $max_pg_to_fetch = 1;
606 my $fpcursor = '';
607 my $cursor = '';
608  
609 #print STDERR "RDAPLookup _fetch_get_pages on URL: '$URL'\n";
610 #print STDERR " is_a_search: '", $self->is_a_search || 0, "'\n";
611
612 if ($self->is_a_search) {
613 $max_pg_to_fetch = $self->{nopages} || $RDAP_ENTITY_QUOTA_PAGES;
614  
615 # first page cursor
616 $fpcursor = $self->{cursor} || '';
617 $cursor = $fpcursor;
618 }
619  
620 my $pcnt = 1;
621  
622 # A place to collect the total result
623 my $result;
624 my $count = 0;
625  
626 # Basic auth params must be passed to the fetch() operation
627 my %BA_OPTIONS;
628 if ($self->{bauth_username} && $self->{bauth_password} ) {
629 # Add basic authentication header via options hash
630 $BA_OPTIONS{user} = $self->{bauth_username};
631 $BA_OPTIONS{pass} = $self->{bauth_password};
632 }
633  
634 # Add cursor, initially the $cursor passed in $self, succeding
635 # values from next href in each loop
636 my $FURL = $URL;
637 if ($cursor) {
638 $FURL .= "&cursor=$cursor";
639 }
640  
641 while ($FURL && $pcnt <= $max_pg_to_fetch) {
642
643 # Remember size before next lookup. If size has not increased, stop the loop.
644
645 my $resp = $self->fetch(URI->new($FURL), %BA_OPTIONS );
646  
647 my $access_layer = $self->ua->{response_headers}->{'x-access-layer'} ||
648 $RDAP_LAYER_UNSET_OR_UNKNOWN;
649  
650 if ($debug == 1) {
651 print STDERR " RDAPLookup search, pcnt: '$pcnt', lookup on FURL: $FURL\n";
652 print STDERR " pcnt: '$pcnt', max_pg_to_fetch: '$max_pg_to_fetch'\n";
653 print STDERR " returned x-access-layer header: ", $access_layer, "\n" ;
654 }
655  
656 $self->access_layer($access_layer);
657  
658 if ($self->{debug} == 100) {
659 #print STDERR "Net::RDAP self for GET: ", Dumper $self, "\n";
660 print STDERR "Net::RDAP resp for GET: ", Dumper $resp, "\n";
661 }
662  
663 if ($debug == 3) {
664 print STDERR "UA Debug: UA: ", Dumper $ua, "\n";
665 }
666
667 unless ($resp) {
668 #print STDERR "Empty GET resp1 for query: '", $self->{query}, "\n";
669 $self->error( _map_rdap_error($query, 404) );
670 $self->status("Lookup returned nothing!");
671 return $self;
672 }
673  
674 #print STDERR "Acccess layer: ", $self->access_layer, "\n";
675 #print STDERR "resp pcnt: '$pcnt': ", Dumper $resp, "\n";
676 #print STDERR "ua: ", Dumper $ua, "\n";
677 #print STDERR "ua: ", Dumper $ua->{handlers}->{response_header}, "\n";
678 #print STDERR "response_headers: ", Dumper $self->ua->{response_headers}, "\n";
679 #print STDERR "self: ", Dumper $self, "\n";
680 #print STDERR "self: ", Dumper $self->resp->{def_headers}, "\n";
681
682 if ($resp->isa('Net::RDAP::Error')) {
683 #print STDERR "Net::RDAP::Error on GET on query '$query', resp: " , Dumper $resp, "\n";
684 #print STDERR "Empty GET resp2 for query: '", $self->{query}, "\n";
685 #print STDERR "Empty GET resp2 for uri: '", $self->_uri, "\n";
686 $self->error(_map_rdap_error($query,$resp->errorCode));
687 $self->status($resp->title);
688 $self->description($resp->description);
689 $self->raw_json_decoded(to_json({%{$resp}}, {utf8 => 1, pretty => 1}));
690 return $self;
691 }
692
693 if ($resp->isa('NOLookup::RDAP::RDAPLookup')) {
694 # a $resp is returned, but when fetch() finds nothing, it
695 # just returs the $self-object, possible with an error[] filled in,
696 # so handle it as nothing found
697 # This may also happen if QUOTA / too many requests, in
698 # which case we want to return the hits found so far.
699
700 my $err = $resp->error;
701 if (ref($err) eq 'ARRAY') {
702 #print STDERR "pcnt: '$pcnt', Error ARRAY 'NOLookup::RDAP::RDAPLookup': ", Dumper $err, "\n";
703 my $ix = 0;
704 foreach my $el (@$err) {
705 if ($el eq 'errorCode') {
706 #print STDERR " Each Error ARRAY 'NOLookup::RDAP::RDAPLookup', ix: $ix+1: ", Dumper($err->[$ix+1]), "\n";
707 $self->error( _map_rdap_error($query, $err->[$ix+1]) );
708 #print STDERR " ARRAY error:", $self->error, "\n";
709
710 } elsif ($el eq 'title') {
711 #print STDERR " Each Error status title NOLookup::RDAP::RDAPLookup', ix: $ix+1: , el: $el", Dumper($err->[$ix+1]), "\n";
712 $self->status($err->[$ix+1]);
713 }
714 ++$ix;
715 }
716 } else {
717 #print STDERR "Error SCALAR 'NOLookup::RDAP::RDAPLookup': ", Dumper $err, "\n";
718 $self->error(_map_rdap_error($query, $err));
719 $self->status("Lookup rejected or returned no match!");
720 }
721 #print STDERR " pcnt:'$pcnt', RDAPLookup.pm: lookup_error on URL: $URL, error: ", $self->error, "\n";
722  
723 if ($self->error == $RDAP_LOOKUP_ERR_QUOTA_EXCEEDED && $result) {
724 # Hit by rate limiting, but we have collected some
725 # result data so far, return what we have, but warn
726 # about the truncated data.
727 $self->warning($self->error);
728 $self->status("Query stopped by RDAP rate limiting, the result may be truncated!");
729 # not fatal, so clear error
730 $self->error(0);
731 #print STDERR " QUOTA EXCEEDED, status: ", $self->status, "\n";
732 last;
733 }
734 return $self;
735 }
736  
737 #### A lookup GET response with data
738
739 # Check conformance values before we accept the answer
740 my @cf = @{$resp->{rdapConformance}};
741
742 #print STDERR "NOLookup resp: ", Dumper $resp, "\n";
743  
744 #print STDERR "cf: ", Dumper \@cf, "\n";
745  
746 foreach my $cfe (@cf) {
747 unless ($rdapConformance_vals_supported{$cfe}) {
748 $self->status("Conformance mismatch on key $cfe, this library does not support this RDAP version!");
749 $self->error($RDAP_LOOKUP_ERR_NO_CONFORMANCE);
750 return $self;
751 }
752 }
753  
754 #print "LOOP $pcnt, result is: ", Dumper $resp;
755 #exit;
756  
757 if (!$self->is_a_search) {
758 # Single lookup and no search: A domain, an entity etc. found
759 $FURL = undef;
760 $result = $resp;
761 $count = 1;
762  
763 } elsif ($resp->isa('Net::RDAP::SearchResult')) {
764  
765 my $ndom = scalar(@{$resp->{domainSearchResults}}) if ($resp->{domainSearchResults});
766 my $nns = scalar(@{$resp->{nameserverSearchResults}}) if ($resp->{nameserverSearchResults});
767 my $nent = scalar(@{$resp->{entitySearchResults}}) if ($resp->{entitySearchResults});
768  
769 $count += $ndom if $ndom;
770 $count += $nns if $nns;
771 $count += $nent if $nent;
772
773 if ($pcnt == 1) {
774 $result = $resp;
775 #print STDERR "pcnt: $pcnt, count: $count, result count: ", scalar(@{$result->{domainSearchResults}}), "\n" if ($ndom);
776 #print STDERR "pcnt: $pcnt, count: $count, result count: ", scalar(@{$result->{nameserverSearchResults}}), "\n" if ($nns);
777 #print STDERR "pcnt: $pcnt, count: $count, result count: ", scalar(@{$result->{entitySearchResults}}), "\n" if ($nent);
778
779 } else {
780 # $result already has the hits from $pcnt==1, add extra
781 # hits found by the loop to the $result
782  
783 push @{$result->{domainSearchResults}}, @{$resp->{domainSearchResults}} if $ndom;
784 push @{$result->{nameserverSearchResults}}, @{$resp->{nameserverSearchResults}} if $nns;
785 push @{$result->{entitySearchResults}}, @{$resp->{entitySearchResults}} if $nent;
786 #print STDERR "LOOP and search and page '$pcnt', result is: ", Dumper $result;
787 }
788  
789 if (my @links = $resp->links) {
790 my $link = $links[0];
791  
792 if ($link && $link->{rel} eq 'self') {
793 #print STDERR "NOlookup self link: ", Dumper $link, "\n";
794  
795 # set prev/cur/next page refs
796 # cur_page points to the last page read.
797 $self->prev_page($self->cur_page) if ($self->cur_page);
798 $self->cur_page($link->href->as_string || $FURL);
799 }
800 }
801  
802 # Paging data should be found, handle it.
803 # ? If so, loop from the cursor and dump
804 if (my $pm = $resp->{paging_metadata}) {
805  
806 #print STDERR "NOLookup: Paging metadata found: ", Dumper $pm, "\n";
807  
808 #print STDERR "Paging self: ", Dumper $self, "\n";
809 #print STDERR "Paging self _uri: ", $self->_uri, "\n";
810 #print STDERR "Paging self _full_url: ", $self->_full_url, "\n";
811 #print STDERR "Paging self cursor : ", $self->{cursor} || "-", "\n";
812  
813 my $pagenumber = $pm->{pageNumber} || 1;
814 my $pagesize = $pm->{pageSize} || $RDAP_PAGE_SIZE;
815 my $totalsize = $pm->{totalCount} || 0;
816  
817 $self->page_number($pagenumber);
818  
819 my $link = @{$pm->{links}}[0];
820 #print STDERR "PM data link: ", Dumper $link, "\n";;
821  
822 my $nextref;
823  
824 $self->total_size($totalsize);
825  
826 #print STDERR "1 page_number: ", $self->page_number() || "-", "\n";
827 #print STDERR "1 first_page : ", $self->first_page() || "-", "\n";
828 #print STDERR "1 cur_page : ", $self->cur_page() || "-", "\n";
829 #print STDERR "1 prev_page : ", $self->prev_page() || "-", "\n";
830 #print STDERR "1 next_page : ", $self->next_page() || "-", "\n";
831  
832 if ($pcnt == 1) {
833  
834 #print STDERR "NOLookup pcnt: $pcnt, first_page: ", $self->first_page, "\n";
835  
836 # Remember first page also, since multiple can be fetched
837 # If first_page is passed by the caller, keep that value.
838 $self->first_page($self->cur_page) unless ($self->first_page);
839  
840 # Can be useful to know to page size, remember it
841 # now, since that is the max. number returned by
842 # the rdap service.
843 # If page_size is passed by the caller, he knows
844 # it already, so keep that value.
845 $self->page_size($pagesize) unless ($self->page_size);
846  
847 # Calculate number of pages in total
848 my $nopages_int = int($self->total_size/$self->page_size);
849 my $nopages_mod = $self->total_size % $self->page_size;
850 ++$nopages_int if ($nopages_mod > 0);
851 $self->total_no_pages($nopages_int);
852  
853 }
854
855 if ($link && $link->{rel} && $link->{rel} eq 'next') {
856 # At least one next is found. If we do not get
857 # here, only a single page is found, and
858 # next link is not applicable
859  
860 #print STDERR "PM data link for next: ", Dumper $link, "\n";;
861  
862 # nextref in 'href'
863 $nextref = $link->{href};
864 #print STDERR "Nextref href: $nextref\n\n";
865
866 # For testing on lab, an URL/cursor trick to
867 # get a working next link when we have two
868 # rdap.lab.norid.no instances, because the cursor only
869 # works per instance
870 my $cursor = get_href_page_cursor($nextref);
871  
872 #print STDERR "FURL : $FURL\n";
873 #print STDERR "URL : $URL\n";
874 #print STDERR "cursor from nextref: $cursor\n";
875  
876 if ($cursor) {
877 $nextref = $URL;
878 $nextref .= "&cursor=$cursor";
879 }
880 $self->next_page($nextref);
881  
882 #print STDERR "Pagenumber: $pagenumber\n";
883 #print STDERR "Pagesize : $pagesize\n";
884 #print STDERR "Nextref : $nextref\n\n";
885  
886 } else {
887 #print STDERR "No next page\n";
888 $self->next_page(undef);
889 }
890  
891 #print STDERR "2 first_page: ", $self->first_page() || "-", "\n";
892 #print STDERR "2 cur_page : ", $self->cur_page() || "-", "\n";
893 #print STDERR "2 prev_page : ", $self->prev_page() || "-", "\n";
894 #print STDERR "2 next_page : ", $self->next_page() || "-", "\n";
895  
896 # $FURL is set to undef if no more pages
897 $FURL = $nextref;
898  
899 #print STDERR "LOOP and page 2, result is: ", Dumper $result;
900 #print STDERR "LOOP and page $pcnt, result count: $count above\n--\n";
901 }
902 ++$pcnt;
903 }
904 }
905  
906
907
908 #
909 $self->raw_json_decoded(to_json({%{$result}}, {utf8 => 1, pretty => 1}));
910  
911 # Set size of returned data
912 $self->size($count);
913  
914 # Initialize some page data unless set by a search
915 $self->total_no_pages(1) unless ($self->total_no_pages);
916 $self->total_size(1) unless ($self->total_size);
917  
918 #print STDERR "NOLookup returns:\n";
919 #print STDERR " size : ", $self->size, "\n";
920 #print STDERR " total_size : ", $self->total_size, "\n";
921 #print STDERR " total_no_pages: ", $self->total_no_pages, "\n";
922
923 #print STDERR "3 page_size : ", $self->page_size || "-", "\n";
924 #print STDERR "3 first_page : ", $self->first_page || "-", "\n";
925 #print STDERR "3 cur_page : ", $self->cur_page || "-", "\n";
926 #print STDERR "3 prev_page : ", $self->prev_page || "-", "\n";
927 #print STDERR "3 next_page : ", $self->next_page || "-", "\n";
928
929 print STDERR " Actual found search hits returned, size is: '$count'\n" if ($debug);
930
931 $self->result($result);
932  
933 }
934  
935 =head2 get_href_page_cursor
936  
937 Find and return cursor value from a href page link
938  
939 =cut
940  
941 sub get_href_page_cursor {
942 my ($href) = @_;
943  
944 return unless $href;
945
946 my $cursor = "";
947  
948 if ($href =~ m/.+(cursor=(.+))&/ ||
949 $href =~ m/.+(cursor=(.+))$/) {
950 $cursor = $2;
951 }
952 return $cursor;
953 }
954  
955 =head2 _ua_callback
956  
957 UA callback function to collect relevant info from the HTTP response.
958  
959 For now, we want the response headers.
960  
961 =cut
962  
963 sub _ua_callback {
964 my($response, $ua, $handler) = @_;
965  
966 #print STDERR "callback response: ", Dumper $response, "n";
967 #print STDERR "callback response headers: ", Dumper $response->headers->{'x-access-layer'}, "n";
968 #print STDERR "callback ua : ", Dumper $ua, "n";
969 #print STDERR "handler : ", Dumper $handler, "n";
970  
971 $ua->{response_headers} = $response->headers;
972
973 }
974  
975  
976 =head2 _map_rdap_error
977  
978 Some RDAP error is returned from Net::RDAP, ref. Net::RDAP::Error.
979  
980 Those are normally HTTP response errors in the 400 and 500 range,
981 which are mapped to one of the $RDAP_LOOKUP_ERR_XXX local errors.
982  
983 https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
984 - All 1xx, 2xx, 3xx are not errors, but OK, need not be handled.
985 - All 4xx, 5xx indicate some problem, so map relevant ones.
986 - Some are not mapped. A warning is given, which may indicate that
987 some error case has occured, and that the situation may need to be
988 handled and added to this lib.
989  
990 =cut
991  
992 sub _map_rdap_error {
993 my ($query, $rdap_error) = @_;
994  
995 my $rcode;
996 if ($rdap_error =~ m/^4\d+$/) {
997 # Some client side problem
998 if ($rdap_error == 404) {
999 $rcode = $RDAP_LOOKUP_ERR_NO_MATCH;
1000 } elsif ($rdap_error == 403) {
1001 $rcode = $RDAP_LOOKUP_ERR_FORBIDDEN;
1002 } elsif ($rdap_error == 429) {
1003 $rcode = $RDAP_LOOKUP_ERR_QUOTA_EXCEEDED;
1004 } elsif ($rdap_error == 401) {
1005 $rcode = $RDAP_LOOKUP_NOT_AUTHORIZED;
1006 } else {
1007 $rcode = $RDAP_LOOKUP_ERR_INVALID;
1008 }
1009  
1010 } elsif ($rdap_error =~ m/^5\d+$/) {
1011 # Some some server side problems
1012 if ($rdap_error == 501) {
1013 $rcode = $RDAP_LOOKUP_ERR_INVALID;
1014 } else {
1015 $rcode = $RDAP_LOOKUP_ERR_NO_CONN;
1016 }
1017  
1018 } else {
1019 $rcode = $RDAP_LOOKUP_ERR_OTHER;
1020 # report other case in case the code can be mapped to a better value
1021 print STDERR "_map_rdap_error - some other error code: '$rdap_error' was returned for query: $query\n";
1022 }
1023  
1024 #print STDERR "_map_rdap_error returned rdap_error: $rdap_error, mapped to rcode: $rcode for query: $query\n";
1025
1026 return $rcode;
1027  
1028 }
1029  
1030 =head2 get_my_ip_address
1031  
1032 Find local ip-address.
1033  
1034 (Note: Sys::HostAddr were also tried for this purpose, but could die at
1035 random, so Sys::HostIP is selected. Only ipv4 seems to be processed by
1036 Sys::HostIP, so the selection is limited to ipv4.
1037 TODO: Consider using another module, which also supports v6).
1038  
1039 Best guess IP seems to be the one on the en0-interface, but when a VPN
1040 is in use, you might want that address to be selected. So, try to do
1041 the best ip selection by ourselves by a reverse sort instead of a
1042 sort, thus selecting the 'highest' numbered and public ip-address).
1043  
1044 Return localhost if no other ip is found.
1045  
1046 Return empty if localhost iface not found.
1047  
1048 =cut
1049  
1050 sub get_my_ip_address {
1051  
1052 my $hostip = Sys::HostIP->new;
1053
1054 my $if_info = $hostip->if_info;
1055 my $lo_found;
1056 foreach my $key ( reverse sort keys %{$if_info} ) {
1057 # we don't want the loopback
1058 if ( $if_info->{$key} eq '127.0.0.1' ) {
1059 $lo_found++;
1060 next;
1061 }
1062 # now we return the first one that comes up
1063 return ( $if_info->{$key} );
1064 }
1065
1066 # we get here if loopback is the only active device
1067 $lo_found and return '127.0.0.1';
1068
1069 return '';
1070  
1071 }
1072  
1073 =head2 _is_a_valid_parameter
1074  
1075 Check whether a parameter contains something fishy
1076  
1077 Ref. CSS:
1078 https://www.owasp.org/index.php/Testing_for_Cross_site_scripting#Description_of_Cross-site_scripting_Vulnerabilities
1079  
1080 Returns 0 if not ok, 1 if OK.
1081  
1082 The below code can be used if special chars should also be generally
1083 blocked, but not in use for now:
1084  
1085 my $ILLCHARS = q/`';_|<>${}[]^]/;
1086 my $ILLCHARSqr = qr/[\|<>\$\{\}\[\]\^';_\|]/mx;
1087 if ($v =~ $ILLCHARSqr) {
1088 print STDERR "Parameter value contains illegal character(s), one or more of: '$ILLCHARS': '$v'";
1089 return;
1090 }
1091  
1092 =cut
1093  
1094 sub _is_a_valid_parameter {
1095 my $q = shift;
1096  
1097 # The ZAP tool testing recommends to block the following general CSS:
1098 return if ($q =~ m|onMouseOver|gi);
1099 return if ($q =~ m|<.*script|gi);
1100  
1101 return 1;
1102 }
1103  
1104 =head2 validate_and_analyze
1105  
1106 1) Validate ip address, if set
1107
1108 2) Validate query, return if query not among the expexted ones.
1109 - domain name or name server name
1110 - some object handle (D, P, R, H)
1111 - some registrar handle (regXXX-NORID)
1112 - some identity (9 digits orgno, N.XXX.yyyyyyyy)
1113  
1114 2) Analyze query and args and find what http method and uri arguments
1115 to use for the lookup and set them in '_method' and '_uri'
1116  
1117 =cut
1118  
1119 sub validate_and_analyze {
1120 my ($self, $q, $check, $ns, $entity) = @_;
1121  
1122 unless (&_is_a_valid_parameter($q)) {
1123 $self->status("Invalid character in parameter: $q");
1124 $self->error($RDAP_LOOKUP_ERR_INVALID);
1125 return 0;
1126 }
1127
1128 if (my $ip = $self->{norid_referral_ip}) {
1129 unless (is_ip($ip)) {
1130 $self->status("Invalid referral ip address: $ip");
1131 $self->error($RDAP_LOOKUP_ERR_INVALID);
1132 return 0;
1133 }
1134 }
1135  
1136 my $debug = $self->{debug} || 0;
1137 my $rawtype = $self->{rawtype};
1138  
1139 my $fieldset = $self->{fieldset} || '';
1140 $fieldset = lc($fieldset);
1141  
1142 my $cursor = $self->{cursor} || '';
1143  
1144 # Fieldset among the supported values?
1145 if ($fieldset && !$RDAP_FIELDSETS{$fieldset}) {
1146 $self->status("Invalid fieldset: '$fieldset', must be one of [" . join(", ", keys %RDAP_FIELDSETS) . "].");
1147 $self->error($RDAP_LOOKUP_ERR_INVALID);
1148 return 0;
1149 }
1150
1151 # Supported rawtype arg syntax?
1152 if ($rawtype) {
1153 my $rawvalid = 0;
1154 foreach my $a (keys(%rdap_head_get_method_args), keys(%rdap_get_method_args)) {
1155
1156 my $mhg = $rdap_head_get_method_args{$a};
1157 my $mg = $rdap_get_method_args{$a};
1158  
1159 #print STDERR "Raw q: '$q', a: '$a', mhg: '$mhg'\n" if ($mhg);
1160 #print STDERR "Raw q: '$q', a: '$a', mg: '$mg'\n" if ($mg);
1161  
1162 # We use \Q and \E to tell regexp to interpret with no
1163 # special chars, needed because of the '?' character which
1164 # can be present
1165 if ($mhg && $q =~ m/^\Q$mhg\E/i) {
1166 #print STDERR "Raw mhg match q: '$q' arg match on a: '$a' / mhg: '$mhg' in head_get methods\n";
1167 ++$rawvalid;
1168 last;
1169 }
1170 if ($mg && $q =~ m/^\Q$mg\E/i) {
1171 #print STDERR "Raw mg match q: '$q' arg match on a: '$a' / mg: '$mg' in get methods\n";
1172 ++$rawvalid;
1173 last;
1174 }
1175 }
1176 unless ($rawvalid) {
1177 #print STDERR "Rawtpe is set, but invalid: $rawtype\n";
1178 $self->status("Raw lookup arguments '$q' is not valid or supported");
1179 $self->error($RDAP_LOOKUP_ERR_INVALID);
1180 return 0;
1181 }
1182  
1183 # Validate URL arguments special because new gTLDs need to
1184 # be accepted. Found an regexp on the web which seems to
1185 # do the trick, at http://www.regexpal.com/94502:
1186 #
1187 # 1) this one makes the 'http(s)://' part optional:
1188 # ($av =~ m|^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$|i)
1189 #
1190 # 2) this one is the same as above, except makes the 'http(s)://' part mandatory
1191 # ($av =~ m|^(?:http(s)?:\/\/)[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$|i)
1192 #
1193 # We use parts of the above
1194
1195 if ($q =~ m|^(http(s)?)|i) {
1196 # We do not accept any http(s) parts
1197 $self->status("Invalid URL, remove http(s) part: $q");
1198 $self->error($RDAP_LOOKUP_ERR_INVALID);
1199 return 0;
1200 }
1201 # The rest of the URL args must be valid as url arguments
1202 unless ($q =~ m|^[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$|i) {
1203 $self->status("Invalid URL arguments: $q");
1204 $self->error($RDAP_LOOKUP_ERR_INVALID);
1205 return 0;
1206 }
1207 }
1208  
1209 my $arg;
1210 my $search;
1211  
1212 # Remove unwanted spaces before, after and collapse inside to one
1213 if ($q) {
1214 $q =~ s/\s+/ /g;
1215 $q =~ s/^\s+//;
1216 $q =~ s/\s+$//;
1217 }
1218  
1219 unless ($q) {
1220 $self->status("mandatory query parameter not specified");
1221 $self->error($RDAP_LOOKUP_ERR_INVALID);
1222 return 0;
1223 }
1224 if ($ns && $ns != 1 && $ns != 2) {
1225 #print STDERR "VALIDATE ns: $ns\n";
1226 $self->status("nameservers parameter must be set to 1 or 2");
1227 $self->error($RDAP_LOOKUP_ERR_INVALID);
1228 return 0;
1229 }
1230  
1231 # A search must be performed with a GET only if '*' is found in
1232 # the $q, this parameter us used below where HEAD or GET are
1233 # possible, but then GET shall be selected if $search
1234 if ($q =~ /\*/i) {
1235 #print STDERR "Asterix found, so a search is to be performed, which one is decided below\n";
1236 ++$search;
1237 }
1238
1239 if ($rawtype) {
1240 # User has specified type and also all complete arguments already.
1241 $arg = $self->{rawtype};
1242
1243 } elsif ($q =~ m/^\d{9}$/) {
1244 #print STDERR "Orgno found so a search is to be performed, which one is decided below\n";
1245
1246 # org number OK
1247 if ($q eq "000000000") {
1248 $self->status("Invalid ID: $q");
1249 $self->error($RDAP_LOOKUP_ERR_INVALID);
1250 return 0;
1251  
1252 } elsif ($q !~ m/^[8|9]\d{8}/) {
1253 $self->status("Invalid ID, org.number must start on 8 or 9: $q");
1254 $self->error($RDAP_LOOKUP_ERR_INVALID);
1255 return 0;
1256 }
1257  
1258 # Lookup an id is a search
1259 ++$search;
1260
1261 # Search domains by identity to get list of domain names for that identity
1262 $arg = 'DBID';
1263 if ($entity) {
1264 # search entities by identity to get list of handles with that identity
1265 $arg = 'EBID';
1266 }
1267  
1268 } elsif ($q =~ /^N\.(PRI|LEG|ORG|REG)\.\d+$/i) {
1269  
1270 $q = uc($q);
1271  
1272 # Lookup an id is a search
1273 ++$search;
1274  
1275 # search domains by identity is default
1276 $arg = 'DBID';
1277 if ($entity) {
1278 # search entities by identity
1279 $arg = 'EBID';
1280 }
1281  
1282 } elsif ($q =~ /REG(\d+)(-NORID)*$/i) {
1283 # registrar handle lookup
1284 # is case sensitive, syntax: 'reg2-NORID'
1285 $q = "reg$1-NORID";
1286  
1287 # registrar by reg handle RBRH, same as EBEH, so use that
1288 $arg = 'EBEH';
1289
1290 } elsif ($q =~ /^[a-z]{1,}[0-9]{1,}([D])(-NORID)*$/i) {
1291 # Domain (D) handle lookup is not supported by the rdap, use the domain name instead
1292 $self->status("Invalid query, domain handle not supported, use the domain name instead: $q");
1293 $self->error($RDAP_LOOKUP_ERR_INVALID);
1294 return 0;
1295
1296 } elsif ($q =~ /^[a-z]{1,}[0-9]{1,}([PORH])(-NORID)*$/i) {
1297 # P, O, R or H handle
1298 $q = uc($q);
1299
1300 my $ot = uc($1);
1301
1302 if ($ot eq 'P' || $ot eq 'O') {
1303 # is a registrant handle
1304  
1305 # domains by registrant handle is default
1306 $arg = 'DBRH';
1307 # Lookup an id is a search
1308 ++$search;
1309
1310 if ($entity || $check) {
1311 # entities by entity handle
1312 $arg = 'EBEH';
1313 $search = 0;
1314 }
1315  
1316 } elsif ($ot eq 'H') {
1317 # is a H, only option is by nameserver handle
1318 $arg = 'NBNH';
1319  
1320 } else {
1321 # is an R, only option is lookup entity by entity handle
1322 $arg = 'EBEH';
1323 }
1324  
1325 } elsif (
1326 # IP addresses?
1327 # (ip blocks/ranges not supported yet, but can be added if needed:
1328 # $q =~ /^\d{1,3}\.\d{1,3}\.{0,1}\d{0,3}\.{0,1}\d{0,3}\/\d{1,2}$/ || # ipv4 range
1329 # $q =~ /^[0-9a-f:]+\/\d{1,3}$/i) { # ipv6 range
1330 #
1331 $q =~ m/^$RE{net}{IPv4}$/i || # ipv4 decimal
1332 #$q =~ m/^$RE{net}{IPv4}{hex}$/i || # ipv4 hex not expected nor supported
1333 $q =~ m/^$RE{net}{IPv6}$/i) { # ipv6 hex
1334
1335 #print STDERR "Is IP-address or block in $q, search on nameservers by IP\n";
1336 $q = lc($q);
1337  
1338 # Domains by name server IP (DBNI) is default
1339 $arg = 'DBNI';
1340 ++$search;
1341
1342 if ($ns && $ns == 1) {
1343 # nameservers by IP (NBNI) is a search
1344 $arg = 'NBNI';
1345 #print STDERR "Nameservers by IP search for $q: $arg\n";
1346
1347 } else {
1348 #print STDERR "Domains by nameserver IP search for $q: $arg\n";
1349 }
1350  
1351 } elsif (
1352 # domain or nameserver name
1353 $q =~ /^(no)$/i || # 'no'
1354 $q =~ /^\.(no)$/i || # '.no'
1355 $q =~ /^(no)\.$/i || # 'no.'
1356 $q =~ /^(.+\.no)$/i || # 'xxx.no' : domain name(s) or nameserver(s) under .no
1357 $q =~ /^(.+\..+)$/i) { # 'ns1.hyp.net' : possible nameserver(s) not under no
1358  
1359 $q = lc($1);
1360  
1361 unless (is_a_valid_domainname($q, $ns)) {
1362 #print STDERR "q is INVALID\n";
1363 $self->status("Invalid domain name or nameserver name: $q");
1364 $self->error($RDAP_LOOKUP_ERR_INVALID);
1365 return 0;
1366 }
1367  
1368 #print "STDERR: a single no domain or nameserver search requested, q: $q\n";
1369
1370 # domain by domain name is default
1371 $arg = 'DBDN';
1372 if ($ns) {
1373 if ($check) {
1374 # nameservers by name server name (NBNN) is a search
1375 #print STDERR "nameserver name and check not supported for $q: $arg\n";
1376  
1377 $self->status("Invalid query, check on nameserver name not supported, use the nameserver handle instead: $q");
1378 $self->error($RDAP_LOOKUP_ERR_INVALID);
1379 return 0;
1380  
1381 } elsif ($ns == 2) {
1382 # domains by name server (ldh)name (DBNL) is a search
1383 ++$search;
1384 $arg = 'DBNL';
1385 #print STDERR "domains by nameserver name search for $q: $arg\n";
1386  
1387 } else {
1388 # $ns == 1:
1389 ++$search;
1390 $arg = 'NBNN';
1391 #print STDERR "nameserver search for $q: $arg\n";
1392 }
1393 }
1394 #print STDERR "domain search for $q: '$arg'\n";
1395  
1396 } elsif ($q =~ /.+/i) {
1397 # Some other string has one or more character inside is
1398 # assumed to be an ns, if $ns, or name of a person, role or org
1399 $q = lc($q);
1400  
1401 if ($ns) {
1402 $arg = 'NBNN';
1403 } else {
1404 # entity by full name
1405 $arg = 'EBFN';
1406 }
1407 ++$search;
1408
1409 } else {
1410 $self->status("Invalid query, not supported by the RDAP service: $q");
1411 $self->error($RDAP_LOOKUP_ERR_INVALID);
1412 return 0;
1413 }
1414  
1415 unless ($arg) {
1416 $self->status("No success in finding a lookup method, try a valid query combination: $q");
1417 $self->error($RDAP_LOOKUP_ERR_INVALID);
1418 return 0;
1419 }
1420  
1421 unless ($arg) {
1422 $self->status("No success in finding a lookup method, try a valid query combination: $q");
1423 $self->error($RDAP_LOOKUP_ERR_INVALID);
1424 return 0;
1425 }
1426  
1427 #print STDERR "validate(): q: '$q' gave arg: '$arg'\n";
1428  
1429 if ($entity) {
1430 #print STDERR "validate and entity as search was selected\n";
1431 unless ($arg eq 'EBID' || $arg eq 'EBEH' || $arg eq 'DBRH') {
1432 #print STDERR "ERROR: validate and entity search combo for '$q' and '$arg' not supported because of potential many hits\n";
1433 # We must have selected one of the entity searches, else reject
1434 # domain or ns search must not also have the entity set
1435 $self->status("Invalid query, this search cannot be done as an entity search: $q");
1436 $self->error($RDAP_LOOKUP_ERR_INVALID);
1437 return 0;
1438 }
1439 }
1440  
1441 if ($ns) {
1442 #print STDERR "validate and ns search was selected, ns: '$ns', arg: '$arg'\n";
1443 # One of the ns searches are selected.
1444 # Make sure found search is consistent with an ns lookup.
1445 unless ($arg eq 'NBNN' || $arg eq 'NBNI' || $arg eq 'DBNL' || $arg eq 'DBNI') {
1446 #print STDERR "ERROR: validate and nameserver searc for '$q' and '$arg' not supported\n";
1447 $self->status("Invalid query, this search cannot be done as a nameserver search: $q");
1448 $self->error($RDAP_LOOKUP_ERR_INVALID);
1449 return 0;
1450 }
1451 }
1452  
1453 if ($check) {
1454 # HEAD
1455 unless ($rdap_head_get_method_args{$arg}) {
1456 $self->status("No success in finding a HEAD lookup method for $arg, try a valid query combination: $q");
1457 $self->error($RDAP_LOOKUP_ERR_INVALID);
1458 return 0;
1459 }
1460 $self->_method('head');
1461 $self->_uri($rdap_head_get_method_args{$arg} . $q);
1462  
1463 } else {
1464 # GET
1465 unless ($self->{rawtype} || $rdap_head_get_method_args{$arg} || $rdap_get_method_args{$arg}) {
1466 $self->status("No success in finding a GET lookup method for $arg, try a valid query combination: $q");
1467 $self->error($RDAP_LOOKUP_ERR_INVALID);
1468 return 0;
1469 }
1470  
1471 $self->_method('get');
1472  
1473 my $uri_arg = "";
1474  
1475 if ($self->{rawtype}) {
1476 $uri_arg = $q;
1477 } else {
1478 if (!$search && $rdap_head_get_method_args{$arg}) {
1479 $uri_arg = $rdap_head_get_method_args{$arg} . $q;
1480 } else {
1481 $uri_arg = $rdap_get_method_args{$arg} . $q;
1482 }
1483
1484 # RDAP args only allowed for searches:
1485 if ($search && !$rawtype) {
1486  
1487 my $a = '?';
1488 if ($uri_arg =~ m/\?/) {
1489 # args already set, use '&' for extra arg
1490 $a = '&';
1491 }
1492  
1493 # alrays add count argument
1494 $uri_arg .= $a . "count=$URI_ARG_COUNT";
1495  
1496 # Add fieldset arg. if user wants it
1497 if ($fieldset) {
1498 $uri_arg .= "&fieldSet=$fieldset";
1499 }
1500 }
1501 }
1502  
1503 $self->_uri($uri_arg);
1504
1505 }
1506
1507 # remember the query
1508 $self->{query} = $q;
1509 $self->is_a_search($search);
1510  
1511 if ($debug == 1) {
1512 print STDERR $sepln;
1513 print STDERR "RDAPLookup: Search URI for arg '$arg': ", $self->_uri, "\n";
1514 }
1515 return 1;
1516 }
1517  
1518 =head2 is_a_valid_domainname
1519  
1520 Check whether a domainname or nameserver is valid.
1521  
1522 Returns undef if not ok.
1523 Returns 1 if OK.
1524  
1525 =cut
1526  
1527 sub is_a_valid_domainname {
1528 my ($q, $ns) = @_;
1529  
1530 my $ace;
1531 $q = lc($q);
1532  
1533 # A domain name or a nameserver name can contain an '*' in case of
1534 # wildchar search. We just strip all '*' before validating.
1535 if ($q =~ m/\*/) {
1536 $q =~ s/\*//g;
1537 # remove leftover '.' at the start, if we have the *.labnic.no case
1538 $q =~ s/^\.//;
1539 }
1540  
1541 # Special case: Accept '.no' or 'no' as valid zone name
1542 if (!$ns && $q =~ m/^\.no$|^no$/) {
1543 return 1;
1544 }
1545  
1546 # Both domain names and host names should be possible to convert to ace
1547 unless ($ace = idn_to_ascii($q, 'utf-8', IDNA_USE_STD3_ASCII_RULES)) {
1548 return;
1549 }
1550  
1551 if ($ns) {
1552 # $ace and $q must be identical
1553 unless ($q eq $ace) {
1554 return;
1555 }
1556 unless(is_hostname($ace)) {
1557 return;
1558 }
1559 } else {
1560 unless(is_domain($ace)) {
1561 return;
1562 }
1563 # Domain name must end on '.no'
1564 unless ($ace =~ m/^.+\.no$/) {
1565 #print STDERR "Domain name does not end with '.no'\n";
1566 return;
1567 }
1568 }
1569  
1570 # A domain or host must be two letters minimum, so length must be
1571 # at least 5 ('xx.no')
1572 unless (length($ace) > 4) {
1573 return;
1574 }
1575  
1576 return 1;
1577 }
1578  
1579 =head2 rdap_get_obj_name
1580  
1581 Fetch the name from an object.
1582  
1583 If we have a Net::DNS::Domain object (domain/ns), also get the xname.
1584  
1585 =cut
1586  
1587 sub rdap_get_obj_name {
1588 my ($self, $o) = @_;
1589  
1590 my $xname;
1591 my $name = $o->name;
1592 return unless $name;
1593
1594 if ('Net::DNS::Domain' eq ref($name)) {
1595 $xname = $name->xname;
1596 $name = $name->name;
1597 } else {
1598 $xname = $name;
1599 }
1600 return $name, $xname;
1601 }
1602  
1603 =head2 norid_handle_type
1604  
1605 Determine type of Norid handle.
1606  
1607 =cut
1608  
1609 sub norid_handle_type {
1610 my ($self, $handle) = @_;
1611  
1612 $handle = uc($handle);
1613
1614 if ($handle =~ m/REG\d+-NORID$/) {
1615 return 'registrar';
1616  
1617 } elsif ($handle =~ m/.+([O|P|R|H|D])-NORID$/) {
1618 return 'organization' if ($1 eq 'O');
1619 return 'role' if ($1 eq 'R');
1620 return 'person' if ($1 eq 'P');
1621 return 'host' if ($1 eq 'H');
1622 return 'domain' if ($1 eq 'D');
1623 }
1624 #die "unknown handle type for: $handle";
1625 print STDERR "norid_handle_type: unknown handle type - please check\n";
1626 return;
1627 }
1628  
1629 =head2 result_as_rdap_string
1630  
1631 Return sensible rdap formatted text string.
1632 Uses internal helper formatting functions.
1633  
1634 Shows how to access data returned by Net::RDAP.
1635  
1636 =cut
1637  
1638 sub result_as_rdap_string {
1639 my ($self, $check, $nameservers, $entity, $short, $expand) = @_;
1640  
1641 my (@ra, @errors);
1642  
1643 my $response = $self->result;
1644  
1645 # A check has no data, let the caller handle it.
1646 return if ($check);
1647  
1648 if ($response->isa('Net::RDAP::Error')) {
1649 push(@errors, sprintf("%03u (%s)", $response->errorCode, $response->title));
1650 }
1651  
1652 my ($nrs, $nerrs) = $self->rdap_notice_or_remark_as_string($response, 'notices');
1653 my ($rrs, $rerrs) = $self->rdap_notice_or_remark_as_string($response, 'remarks');
1654  
1655 if ($response->isa('Net::RDAP::SearchResult')) {
1656 # Put page info on top of page
1657 $self->rdap_page_info_as_string(\@ra);
1658 push @ra, "";
1659  
1660 my $cnt = 1;
1661 foreach my $o ($response->nameservers, $response->domains, $response->entities) {
1662 my ($rst, $errs) = $self->rdap_obj_as_string($o, $check, $nameservers, $entity, $short, $expand);
1663 push @ra, "[$cnt]";
1664 push @ra, $rst if ($rst);
1665 push @errors, @$errs if ($errs && @$errs);
1666 ++$cnt;
1667 }
1668  
1669 } else {
1670 push @ra, "";
1671  
1672 my ($rst, $errs) = $self->rdap_obj_as_string($response, $check, $nameservers, $entity, $short, $expand);
1673 push @ra, $rst if ($rst);
1674 push @errors, @$errs if ($errs && @$errs);
1675 }
1676  
1677 return ( $nrs . $rrs . (join("\n", @ra)) ), \@errors;
1678  
1679 }
1680  
1681 =head2 rdap_obj_as_string
1682  
1683 Return sensible rdap formatted text string for an rdap object.
1684  
1685 Code stolen from rdapper and adapted.
1686  
1687 =cut
1688  
1689 sub rdap_obj_as_string {
1690 my ($self, $response, $check, $nameservers, $entity, $short, $expand) = @_;
1691  
1692 my (@ra, @errors, @doms);
1693  
1694 #print STDERR "rdap_obj_as_string CLASS: ", $response->class, "\n";
1695 #print STDERR "check: '$check', nameservers: '$nameservers', entity: '$entity', short: '$short', expand: '$expand'\n";
1696  
1697 if ('entity' ne $response->class) {
1698 my ($name, $xname) = $self->rdap_get_obj_name($response);
1699  
1700 my $handle = $response->handle;
1701 my $htype = $self->norid_handle_type($handle);
1702  
1703 push @ra, sprintf("Handle: %s\n", $response->handle);
1704  
1705 if ($xname ne $name) {
1706 push @ra, sprintf("Domain Name: %s\n", $xname);
1707 push @ra, sprintf("Domain ACE Name: %s\n", $name);
1708 } else {
1709 if ($htype eq 'host') {
1710 push @ra, sprintf("Nameserver Name: %s\n", $name);
1711 } else {
1712 push @ra, sprintf("Domain Name: %s\n", $name);
1713 }
1714 }
1715 }
1716  
1717 unless ('domain' eq $response->class || 'nameserver' eq $response->class) {
1718 if ('entity' eq $response->class) {
1719 push @ra, sprintf("Entity:");
1720 }
1721 push @ra, sprintf(" Handle: %s", $response->handle);
1722 push @ra, "" if ($self->is_a_search);
1723 }
1724  
1725 if ('ip network' eq $response->class) {
1726 push @ra, sprintf("Range: %s", $response->range->prefix);
1727 push @ra, sprintf("Domain: %s", $response->domain->as_string);
1728
1729 } elsif ('autnum' eq $response->class) {
1730 push @ra, sprintf("Range: %u - %u", $response->start, $response->end) if ($response->start > 0 && $response->end > 0);
1731 push @ra, sprintf("Type: %s", $response->type) if ($response->type);
1732
1733 } elsif ('domain' eq $response->class) {
1734 my @ns = $response->nameservers;
1735 if (scalar(@ns) > 0) {
1736 push @ra, "Nameservers:";
1737 foreach my $ns (sort { lc($a->name->name) cmp lc($b->name->name) } @ns) {
1738 push @ra, sprintf(" %s: %s", "Handle", $ns->handle);
1739 push @ra, sprintf(" %s: %s", "Nameserver Name", $ns->name->name);
1740 push @ra, "";
1741 }
1742 }
1743
1744 my @ds = $response->ds;
1745 if (scalar(@ds) > 0) {
1746 push @ra, "DNSSEC:";
1747 foreach my $ds ($response->ds) {
1748
1749 push @ra, sprintf(" %s. IN DS %u %u %u %s", uc($ds->name),
1750 $ds->keytag, $ds->algorithm, $ds->digtype, uc($ds->digest));
1751 }
1752 push @ra, "";
1753 }
1754
1755 my @keys = $response->keys;
1756 if (scalar(@keys) > 0) {
1757 push @ra, "DNSSEC Keys:";
1758 foreach my $key (@keys) {
1759 push @ra, sprintf(" %s. IN DNSKEY %u %u %u %s", uc($key->name), $key->flags, $key->protocol, $key->algorithm, uc($key->key));
1760 }
1761 push @ra, "";
1762 }
1763
1764 } elsif ('entity' eq $response->class) {
1765  
1766 my @ids = $response->ids();
1767 my $indent = ' ' x 2;
1768  
1769 foreach my $id (@ids) {
1770 push @ra, sprintf("%sType: %s", $indent, $id->type);
1771 push @ra, sprintf("%sIdentity: %s", $indent, $id->identifier);
1772 }
1773
1774 my $card = $response->vcard;
1775 if (!$card) {
1776 #push @ra, $NO_FURTHER_INFO;
1777 } else {
1778 push @ra, $self->rdap_vcard_as_string($response->vcard, ' ' x 2, $response);
1779 }
1780  
1781 my $handle = $response->handle;
1782 my $htype = $self->norid_handle_type($handle);
1783  
1784 # Also get domain list if we have a subscriber entity handle
1785 if (($expand || $entity) &&
1786 ($htype eq 'organization' || $htype eq 'person')) {
1787  
1788 $self->rdap_get_domains_by_entity_handle($handle, $check,
1789 $nameservers, \@doms, \@errors);
1790 }
1791  
1792 } elsif ('nameserver' eq $response->class) {
1793  
1794 my @addrs = $response->addresses;
1795 if (scalar(@addrs) > 0) {
1796 push @ra, "IP Addresses:";
1797 foreach my $ip (@addrs) {
1798 push @ra, sprintf(" IP Address: %s", $ip->ip);
1799 }
1800 push @ra, "";
1801 } else {
1802 #push @ra, " * (no IP addresses returned)";
1803 }
1804
1805 }
1806  
1807 my @events = $response->events;
1808 if (scalar(@events)) {
1809 push @ra, "Events:";
1810 foreach my $event (@events) {
1811 # DateTime object is UTC, convert to localtime
1812 my $to = $event->date;
1813 $to->set_time_zone('Europe/Oslo');
1814
1815 push @ra, sprintf(" %s: %s", ucfirst($event->action), scalar($to->date));
1816 }
1817 push @ra, "";
1818 }
1819
1820 my @status = $response->status;
1821 if (scalar(@status) > 0) {
1822 push @ra, "Status:";
1823 foreach my $status (@status) {
1824 my $epp = rdap2epp($status);
1825 if ($epp) {
1826 push @ra, sprintf(" * %s (EPP: %s)", $status, $epp);
1827
1828 } else {
1829 push @ra, sprintf(" * %s", $status);
1830 }
1831 }
1832 push @ra, "";
1833 }
1834
1835 my @entities = $response->entities;
1836 my %entities;
1837 foreach my $ent (@entities) {
1838  
1839 if (!$ent->vcard && $expand) {
1840 #print STDERR "rdap_obj_as_string(): Expand set\n" if ($self->{debug});
1841  
1842 my $ro = NOLookup::RDAP::RDAPLookup->new(
1843 {
1844 service_url => $self->{service_url},
1845 debug => $self->{debug},
1846 use_cache => $self->{use_cache},
1847 norid_header_secret => $self->{norid_header_secret},
1848 norid_header_proxy => $self->{norid_header_proxy},
1849 bauth_username => $self->{bauth_username},
1850 bauth_password => $self->{bauth_password},
1851 force_ipv => $self->{force_ipv},
1852 nopages => $self->{nopages}
1853 });
1854
1855 my $new = $ro->lookup($ent->handle, $check, $nameservers, 1);
1856  
1857 if ($new->error) {
1858 #print STDERR "RDAPLookup: New gave error on handle lookup ", $ent->handle, " error: ", Dumper $new->error, "\n";
1859  
1860 # better error handling
1861 $self->error($new->error);
1862 $self->status($new->status);
1863 @ra = ();
1864
1865 return $self;
1866 }
1867
1868 if ($new->isa('Net::RDAP::Error')) {
1869 push(@errors, sprintf('Unable to expand %s: %d (%s)',
1870 $ent->handle, $new->errorCode, $new->title));
1871 } else {
1872 $ent = $new->result;
1873 }
1874 }
1875
1876 map { $entities{$_} = $ent } $ent->roles;
1877 }
1878
1879 if (scalar(@entities) > 0) {
1880 push @ra, "Entities:";
1881
1882 foreach my $entity (@entities) {
1883
1884 my @roles = $entity->roles;
1885 my $handle = $entity->handle;
1886  
1887 if (scalar(@roles) > 0) {
1888 if ($handle) {
1889 push @ra, sprintf(" Handle: %s", $handle);
1890 push @ra, sprintf(" Role: %s", join(', ', sort(@roles)));
1891
1892 } else {
1893 push @ra, sprintf(" %s:", join(', ', map { sprintf('%s Contact', ucfirst($_)) } sort(@roles)));
1894 }
1895
1896 } else {
1897 push @ra, sprintf(" Handle: %s", $handle);
1898 }
1899  
1900 # Show Ids
1901 my @ids = $entity->ids();
1902 my $indent = ' ' x 2;
1903
1904 foreach my $id (@ids) {
1905 push @ra, sprintf("%sType: %s", $indent, $id->type);
1906 push @ra, sprintf("%sIdentity: %s", $indent, $id->identifier);
1907 }
1908  
1909 my $card = $entity->vcard;
1910 if (!$card) {
1911 push @ra, "";
1912 #push @ra, $NO_FURTHER_INFO;
1913 } else {
1914 push @ra, $self->rdap_vcard_as_string($card, ' ' x 2, $entity);
1915 }
1916 }
1917 }
1918  
1919 # List the domains when relevant
1920 if (scalar(@doms)) {
1921 my $ds = "";
1922 my @dns;
1923  
1924 foreach my $dom (@doms) {
1925  
1926 my ($name, $xname) = $self->rdap_get_obj_name($dom);
1927  
1928 if ($xname) {
1929 push @dns, $xname;
1930 } else {
1931 push @dns, $name;
1932 }
1933 }
1934  
1935 # extend domain list with both total number and domain list
1936 if (@dns) {
1937 push @ra, "Total Number Of Domains: " . scalar(@doms);
1938 push @ra, "";
1939 push @ra, "Domains:";
1940 foreach my $dn (@dns) {
1941 push @ra, " Domain Name: $dn";
1942 }
1943 push @ra, "";
1944 }
1945 }
1946  
1947 if (!$short) {
1948 my @links = $response->links;
1949 if (scalar(@links) > 0) {
1950 push @ra, "";
1951 push @ra, "Links:";
1952 foreach my $link (@links) {
1953 push @ra, sprintf(" * %s (%s)", $link->href->as_string, $link->title || $link->rel || '-');
1954 }
1955 push @ra, "";
1956
1957 }
1958 }
1959  
1960 return join("\n", @ra), \@errors;
1961  
1962 }
1963  
1964 =head2 rdap_notice_or_remark_as_string
1965  
1966 Format RDAP notice or remark as text string.
1967  
1968 =cut
1969  
1970 sub rdap_notice_or_remark_as_string {
1971 my ($self, $response, $what) = @_;
1972  
1973 unless ($what eq 'notices' || $what eq 'remarks') {
1974 die "Illegal argument $what, must be 'notices' or 'remarks'";
1975 }
1976  
1977 my (@errors, @ra);
1978  
1979 my @whats = $response->$what;
1980 if (scalar(@whats) > 0) {
1981 my $indent = ' ' x 2;
1982
1983 foreach my $we (@whats) {
1984 push @ra, $we->title;
1985  
1986 foreach my $link ($we->links) {
1987 push @ra, sprintf("%s%s", $indent, $link->href->as_string);
1988 }
1989  
1990 push @ra, "";
1991 push @ra, fill($indent, $indent, join("\n", $we->description));
1992 push @ra, "";
1993 }
1994 }
1995  
1996 return join("\n", @ra), \@errors;
1997 }
1998  
1999  
2000 =head2 rdap_vcard_as_string
2001  
2002 Format vcard object(s) as a text string.
2003  
2004 =cut
2005  
2006 sub rdap_vcard_as_string {
2007 my ($self, $card, $indent, $eo) = @_;
2008  
2009 #print STDERR "rdap_vcard_as_string Name for card: ", Dumper $card, "\n";
2010
2011 my @vca;
2012 my $vc = "";
2013
2014 push @vca, sprintf("%sName: %s", $indent, $card->full_name) if ($card->full_name);
2015 push @vca, sprintf("%sOrganization: %s", $indent, $card->organization) if ($card->organization);
2016
2017 my @addresses = @{$card->addresses};
2018 if (scalar(@addresses) > 0) {
2019 foreach my $address (@addresses) {
2020 push @vca, sprintf("%sAddress:", $indent);
2021 $vc .= sprintf("%sAddress:\n\n", $indent);
2022
2023 my @lines;
2024 foreach my $element (@{$address->{'address'}}) {
2025 push(@lines, ('ARRAY' eq ref($element) ? @{$element} : $element));
2026 }
2027
2028 push @vca, sprintf $indent." ".join(sprintf("\n%s ", $indent), grep { length > 0 } map { s/^[ \t\r\n]+//g ; s/[ \t\r\n]+$//g ; $_ } @lines);
2029 }
2030 }
2031
2032 foreach my $email (@{$card->email_addresses}) {
2033 if ($email->{'type'}) {
2034 push @vca, sprintf("%sEmail: %s (%s)", $indent, $email->{'address'}, $email->{'type'});
2035
2036 } else {
2037 push @vca, sprintf("%sEmail: %s", $indent, $email->{'address'});
2038 }
2039 }
2040  
2041 # Hack: Web address (url) for an entity is not supported via the card
2042 # object, ref. code for vcard() in
2043 # https://metacpan.org/source/GBROWN/Net-RDAP-0.14/lib/Net/RDAP/Object/Entity.pm
2044 # which does not process the url info.
2045 #
2046 # Therefore just fetch the url from inside the $eo instead.
2047 #
2048 # TODO: This should be fixed in Net::RDAP::Object::Entity, a bug
2049 # report has been filed with a request for support.
2050 # (Could also be fixed by local subclassing here, but we
2051 # prefer a central fix)
2052 #
2053 my $vca = $eo->{vcardArray};
2054  
2055 if ($vca && $vca->[0] && $vca->[0] eq 'vcard' && $vca->[1]) {
2056 foreach my $vc (@{$vca->[1]}) {
2057 if ($vc->[0] && $vc->[0] eq 'url') {
2058 if ($vc->[0] && $vc->[0] eq 'url' &&
2059 $vc->[2] && $vc->[2] eq 'uri' &&
2060 $vc->[3]) {
2061 push @vca, sprintf("%sWeb Address: %s", $indent, $vc->[3]);
2062 }
2063 }
2064 }
2065 }
2066  
2067 foreach my $number (@{$card->phones}) {
2068  
2069 my @types = ('ARRAY' eq ref($number->{'type'}) ? @{$number->{'type'}} : ($number->{'type'}));
2070
2071 # Separate between fax, voice and cell phone
2072 my $type = 'voice';
2073 foreach my $t (@types) {
2074 $t = lc($t);
2075 if ($t eq 'fax' || $t eq 'cell') {
2076 $type = $t;
2077 last;
2078 }
2079 }
2080  
2081 # strip the 'tel:' prefix
2082 my $no = $number->{'number'};
2083 $no =~ s/^tel://;
2084  
2085 push @vca, sprintf("%s%s: %s", $indent, ucfirst($type), $no);
2086  
2087 }
2088 push @vca, "";
2089 return join("\n", @vca);
2090
2091 }
2092  
2093 =head2 rdap_page_info_as_string
2094  
2095 Format and insert page info, if requested.
2096  
2097  
2098 =cut
2099  
2100 sub rdap_page_info_as_string {
2101 my ($self, $wa) = @_;
2102  
2103 #For now, just use the same format as we use for whois page info.
2104 &NOLookup::RDAP::RDAPLookup::Whois::rdap_page_info_as_norid_whois_string($self, $wa);
2105  
2106 #$self->rdap_page_info_as_norid_whois_string($wa);
2107  
2108 }
2109  
2110 =head2 rdap_get_entities_by_entity_handle
2111  
2112 Based on a subscriber handle (O or P), fetch domain list for it.
2113  
2114 =cut
2115  
2116 sub rdap_get_entities_by_entity_handle {
2117 my ($self, $handle, $check, $nameservers, $ent, $errors) = @_;
2118  
2119 #print STDERR "rdap_get_entities_by_entity_handle() on handle: '$handle'\n";
2120  
2121 my (%entities, $entity);
2122  
2123 my $ro = NOLookup::RDAP::RDAPLookup->new(
2124 {
2125 service_url => $self->{service_url},
2126 debug => $self->{debug},
2127 use_cache => $self->{use_cache},
2128 norid_header_secret => $self->{norid_header_secret},
2129 norid_header_proxy => $self->{norid_header_proxy},
2130 bauth_username => $self->{bauth_username},
2131 bauth_password => $self->{bauth_password},
2132 force_ipv => $self->{force_ipv},
2133 nopages => $self->{nopages}
2134 });
2135  
2136 my $new = $ro->lookup($handle, $check, $nameservers, 1);
2137  
2138 if ($new->error) {
2139 #print STDERR "New gave error: ", Dumper $new->error, "\n";
2140 $self->error($new->error);
2141 $self->status($new->status);
2142 push @$errors, "Entity handle '$handle' lookup error";
2143  
2144 } elsif ($new->isa('Net::RDAP::Error')) {
2145 #print STDERR "New gave error Net::RDAP::Error: ", Dumper $new, "\n";
2146 push @$errors, "Unable to lookup $handle: $handle, errorcode:" .
2147 $new->errorCode . "desc: " . $new->title;
2148  
2149 } elsif ($new->result) {
2150 #print STDERR "New gave result: ", Dumper $new->result, "\n";
2151 $entity = $new->result;
2152 if ($entity->isa('Net::RDAP::Object::Entity')) {
2153 #print STDERR "New gave Net::RDAP::Object::Entity result: ", Dumper $new->result, "\n";
2154 my @nent = $entity->entities;
2155 push @$ent, @nent if (@nent);
2156 }
2157 }
2158 }
2159  
2160 =head2 rdap_get_domains_by_entity_handle
2161  
2162 Based on a subscriber handle (O or P), fetch domain list for it.
2163  
2164 For domain list on entity, we will try fetch all domains possible on a
2165 single quota as default via $RDAP_ENTITY_QUOTA_PAGES since it is set to a high
2166 enough value. User may try fewer or more pages bt specifying nopages.
2167  
2168 =cut
2169  
2170 sub rdap_get_domains_by_entity_handle {
2171 my ($self, $handle, $check, $nameservers, $doms, $errors) = @_;
2172  
2173 #print STDERR "rdap_get_domains_by_entity_handle() on handle: '$handle'\n";
2174  
2175 # Do a domain search on registrant handle to get the
2176 # associated domains. If the lookup fails, it may be
2177 # that the access layer does not allow for it,
2178 # so on errors we do not return.
2179  
2180 my (%entities, $entity);
2181  
2182 my $ro = NOLookup::RDAP::RDAPLookup->new(
2183 {
2184 service_url => $self->{service_url},
2185 debug => $self->{debug},
2186 use_cache => $self->{use_cache},
2187 norid_header_secret => $self->{norid_header_secret},
2188 norid_header_proxy => $self->{norid_header_proxy},
2189 bauth_username => $self->{bauth_username},
2190 bauth_password => $self->{bauth_password},
2191 force_ipv => $self->{force_ipv},
2192 nopages => $self->{nopages} || $RDAP_ENTITY_QUOTA_PAGES
2193 });
2194  
2195 my $new = $ro->lookup($handle, $check, $nameservers, 0);
2196  
2197 if ($new->error) {
2198 if ($new->error == $RDAP_LOOKUP_ERR_NO_MATCH) {
2199 # Fallthru, skip silently as this may occur if
2200 # a registrant handle has no domains.
2201 #print STDERR "New 2 gave not found: ", $new->error, "\n";
2202 } else {
2203 $self->error($new->error);
2204 $self->status($new->status);
2205 push @$errors, "Domain search for registrant entity handle '$handle' could not be done!";
2206 }
2207  
2208 } elsif ($new->isa('Net::RDAP::Error')) {
2209 push @$errors, "Unable to lookup $handle: $handle, errorcode:" .
2210 $new->errorCode . "desc: " . $new->title;
2211 } else {
2212 $entity = $new->result;
2213 if ($entity && $entity->isa('Net::RDAP::SearchResult')) {
2214 my @ndoms = $entity->domains;
2215 push @$doms, @ndoms;
2216 }
2217 }
2218  
2219 }
2220  
2221 =head2 rdap_get_entities_by_domain_name
2222  
2223 Domain lookup entities for a domain name.
2224  
2225 =cut
2226  
2227 sub rdap_get_entities_by_domain_name {
2228 my ($self, $name, $check, $nameservers, $ent, $errors) = @_;
2229  
2230 #print STDERR "rdap_get_entities_by_domain_name() on name: '$name'\n";
2231  
2232 my (%entities, $entity);
2233  
2234 my $ro = NOLookup::RDAP::RDAPLookup->new(
2235 {
2236 service_url => $self->{service_url},
2237 debug => $self->{debug},
2238 use_cache => $self->{use_cache},
2239 norid_header_secret => $self->{norid_header_secret},
2240 norid_header_proxy => $self->{norid_header_proxy},
2241 bauth_username => $self->{bauth_username},
2242 bauth_password => $self->{bauth_password},
2243 force_ipv => $self->{force_ipv},
2244 nopages => $self->{nopages}
2245 });
2246  
2247 my $new = $ro->lookup($name, $check, $nameservers, 1);
2248  
2249 if ($new->error) {
2250 $self->error($new->error);
2251 $self->status($new->status);
2252 push @$errors, "Domain name '$name' lookup error";
2253  
2254 } elsif ($new->isa('Net::RDAP::Error')) {
2255 push @$errors, "Unable to lookup domain name: '$name', errorcode:" .
2256 $new->errorCode . "desc: " . $new->title;
2257  
2258 } elsif ($new->result) {
2259 $entity = $new->result;
2260 my @nent = $entity->entities if ($entity->entities);
2261 push @$ent, @nent if (@nent);
2262  
2263 } elsif ($new->isa('NOLookup::RDAP::RDAPLookup')) {
2264 # No result, error set by lookup function
2265 }
2266 }
2267  
2268  
2269 =pod
2270  
2271 =encoding ISO-8859-1
2272  
2273 =head1 NAME
2274  
2275 NOLookup::RDAP::RDAPLookup - Lookup RDAP data from the Norid (.no)
2276 RDAP service.
2277  
2278 =head1 SYNOPSIS
2279  
2280 use Encode;
2281 use NOLookup::RDAP::RDAPLookup;
2282
2283 # Default API service URL
2284 my $SERVICE_URL = "https://rdap.norid.no";
2285  
2286 # Example 1: Domain name lookup
2287 # Decode the query when needed, like for IDNs
2288 # or names with national characters.
2289  
2290 my $q = 'norid.no';
2291 #$q = decode('ISO8859-1', 'øl.no');
2292  
2293 # Authenticate with secret and be a proxy (Norid only)
2294 my $bo = NOLookup::RDAP::RDAPLookup->new(
2295 {
2296 service_url => 'https://rdap.norid.no',
2297 debug => 0,
2298 use_cache => 0,
2299 norid_header_secret => '<secret>',
2300 norid_header_proxy => 1,
2301 });
2302  
2303 # Authenticate with basic authentication
2304 my $bo = NOLookup::RDAP::RDAPLookup->new(
2305 {
2306 service_url => 'https://rdap.norid.no',
2307 debug => 0,
2308 use_cache => 0,
2309 bauth_username => 'rdapuser@reg1234',
2310 bauth_password => '<password>',
2311 });
2312  
2313 # test HEAD operation for existence
2314 $bo->lookup($q, 1, 0, 0);
2315 if ($bo->error) {
2316 print "HEAD: Error, error / status: ",
2317 $bo->error . "/" . $bo->status) . "\n";
2318 }
2319  
2320 # test GET operations
2321 $bo->lookup($q, 0, 0, 0);
2322 if ($bo->error) {
2323 print "GET: Error, error / status: ",
2324 $bo->error . "/" . $bo->status) . "\n";
2325 }
2326
2327 # result of lookup is in $bo->result
2328 # This result contains response objects built by Net::RDAP
2329  
2330 # if a lookup has arguments which results in a search type, the
2331 # is_a_search method returns true. This is a hint to the caller to
2332 # process paging information in the result, and maybe perform several
2333 # next-lookups to get more data.
2334  
2335 my $res = $bo->result;
2336 print "handle: ", $bo->handle, "\n";
2337  
2338 * See bin/no_rdap.pl for more information on usage.
2339  
2340 * See various formatting/helper functions in this file for how to
2341 access the various objects returned by Net::RDAP.
2342  
2343 =head1 DESCRIPTION
2344  
2345 This module provides an object oriented API for use with the
2346 Norid RDAP service. It uses the Net::RDAP module from Cpan
2347 internally to fetch information from the Norid RDAP.
2348  
2349 =head1 SUPPORT
2350  
2351 For now, support questions should be sent to:
2352  
2353 E<lt>(nospam)info(at)norid.noE<gt>
2354  
2355 =head1 SEE ALSO
2356  
2357 L<https://www.norid.no/en>
2358 L<https://teknisk.norid.no/en/integrere-mot-norid/rdap-tjenesten>
2359  
2360 =head1 CAVEATS
2361  
2362 =head1 AUTHOR
2363  
2364 Trond Haugen, E<lt>(nospam)info(at)norid.noE<gt>
2365  
2366 =head1 COPYRIGHT
2367  
2368 Copyright (c) 2020- Trond Haugen <(nospam)info(at)norid.no>.
2369 All rights reserved.
2370  
2371 This program is free software; you can redistribute it and/or modify
2372 it under the terms of the GNU General Public License as published by
2373 the Free Software Foundation; either version 2 of the License, or
2374 (at your option) any later version.
2375  
2376 =head1 LICENSE
2377  
2378 This library is free software. You can redistribute it and/or modify
2379 it under the same terms as Perl itself.
2380  
2381 =head1 About the Norid RDAP API
2382  
2383 See
2384 L<https://teknisk.norid.no/en/integrere-mot-norid/rdap-tjenesten>
2385  
2386 =cut
2387  
2388 1;