lib/NOLookup/RDAP/RDAPLookup.pm untested

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