1 package PVE
::RESTHandler
;
4 no strict
'refs'; # our autoload requires this
7 use PVE
::Exception
qw(raise raise_param_exc);
9 use HTTP
::Status
qw(:constants :is status_message);
13 my $method_registry = {};
14 my $method_by_name = {};
15 my $method_path_lookup = {};
17 our $AUTOLOAD; # it's a package global
19 sub api_clone_schema
{
23 my $ref = ref($schema);
24 die "not a HASH reference" if !($ref && $ref eq 'HASH');
26 foreach my $k (keys %$schema) {
27 my $d = $schema->{$k};
28 if ($k ne 'properties') {
29 $res->{$k} = ref($d) ? clone
($d) : $d;
32 # convert indexed parameters like -net\d+ to -net[n]
33 foreach my $p (keys %$d) {
35 if ($p =~ m/^([a-z]+)(\d+)$/) {
36 my ($name, $idx) = ($1, $2);
39 } elsif (defined($d->{"${name}0"})) {
40 next; # only handle once for -xx0, but only if -xx0 exists
43 $res->{$k}->{$p} = ref($pd) ? clone
($pd) : $pd;
51 my ($tree, $index, $class, $prefix) = @_;
53 $prefix = '' if !$prefix;
55 my $ma = $method_registry->{$class};
57 foreach my $info (@$ma) {
59 my $path = "$prefix/$info->{path}";
62 if ($info->{subclass
}) {
63 api_dump_full
($tree, $index, $info->{subclass
}, $path);
67 # check if method is unique
69 $realpath =~ s/\{[^\}]+\}/\{\}/g;
70 my $fullpath = "$info->{method} $realpath";
71 die "duplicate path '$realpath'" if $index->{$fullpath};
72 $index->{$fullpath} = $info;
78 foreach my $dir (split('/', $path)) {
81 $res = (grep { $_->{text
} eq $dir } @$treedir)[0];
83 $res->{children
} = [] if !$res->{children
};
84 $treedir = $res->{children
};
92 $treedir = $res->{children
};
98 foreach my $k (keys %$info) {
99 next if $k eq 'code' || $k eq "match_name" || $k eq "match_re" ||
104 if ($k eq 'parameters') {
105 $data->{$k} = api_clone_schema
($d);
108 $data->{$k} = ref($d) ? clone
($d) : $d;
111 $res->{info
}->{$info->{method}} = $data;
117 sub api_dump_cleanup_tree
{
120 foreach my $rec (@$tree) {
121 delete $rec->{children
} if $rec->{children
} && !scalar(@{$rec->{children
}});
122 if ($rec->{children
}) {
124 api_dump_cleanup_tree
($rec->{children
});
133 my ($class, $prefix) = @_;
138 api_dump_full
($tree, $index, $class);
139 api_dump_cleanup_tree
($tree);
143 sub validate_method_schemas
{
145 foreach my $class (keys %$method_registry) {
146 my $ma = $method_registry->{$class};
148 foreach my $info (@$ma) {
149 PVE
::JSONSchema
::validate_method_info
($info);
154 sub register_method
{
155 my ($self, $info) = @_;
163 if ($info->{subclass
}) {
164 $errprefix = "register subclass $info->{subclass} at ${self}/$info->{path} -";
165 $method = 'SUBCLASS';
167 $errprefix = "register method ${self}/$info->{path} -";
168 $info->{method} = 'GET' if !$info->{method};
169 $method = $info->{method};
172 $method_path_lookup->{$self} = {} if !defined($method_path_lookup->{$self});
173 my $path_lookup = $method_path_lookup->{$self};
175 die "$errprefix no path" if !defined($info->{path
});
177 foreach my $comp (split(/\/+/, $info->{path
})) {
178 die "$errprefix path compoment has zero length\n" if $comp eq '';
180 if ($comp =~ m/^\{(\w+)(:(.*))?\}$/) {
182 $regex = $3 ?
$3 : '\S+';
183 push @$match_re, $regex;
184 push @$match_name, $name;
187 push @$match_re, $name;
188 push @$match_name, undef;
192 $path_lookup->{regex
} = {} if !defined($path_lookup->{regex
});
194 my $old_name = $path_lookup->{regex
}->{match_name
};
195 die "$errprefix found changed regex match name\n"
196 if defined($old_name) && ($old_name ne $name);
197 my $old_re = $path_lookup->{regex
}->{match_re
};
198 die "$errprefix found changed regex\n"
199 if defined($old_re) && ($old_re ne $regex);
200 $path_lookup->{regex
}->{match_name
} = $name;
201 $path_lookup->{regex
}->{match_re
} = $regex;
203 die "$errprefix path match error - regex and fixed items\n"
204 if defined($path_lookup->{folders
});
206 $path_lookup = $path_lookup->{regex
};
209 $path_lookup->{folders
}->{$name} = {} if !defined($path_lookup->{folders
}->{$name});
211 die "$errprefix path match error - regex and fixed items\n"
212 if defined($path_lookup->{regex
});
214 $path_lookup = $path_lookup->{folders
}->{$name};
218 die "$errprefix duplicate method definition\n"
219 if defined($path_lookup->{$method});
221 if ($method eq 'SUBCLASS') {
222 foreach my $m (qw(GET PUT POST DELETE)) {
223 die "$errprefix duplicate method definition SUBCLASS and $m\n" if $path_lookup->{$m};
226 $path_lookup->{$method} = $info;
228 $info->{match_re
} = $match_re;
229 $info->{match_name
} = $match_name;
231 $method_by_name->{$self} = {} if !defined($method_by_name->{$self});
234 die "$errprefix method name already defined\n"
235 if defined($method_by_name->{$self}->{$info->{name
}});
237 $method_by_name->{$self}->{$info->{name
}} = $info;
240 push @{$method_registry->{$self}}, $info;
243 sub register_page_formatter
{
244 my ($self, %config) = @_;
246 my $format = $config{format
} ||
247 die "missing format";
249 my $path = $config{path
} ||
252 my $method = $config{method} ||
253 die "missing method";
255 my $code = $config{code
} ||
256 die "missing formatter code";
259 my ($handler, $info) = $self->find_handler($method, $path, $uri_param);
260 die "unabe to find handler for '$method: $path'" if !($handler && $info);
262 die "duplicate formatter for '$method: $path'"
263 if $info->{formatter
} && $info->{formatter
}->{$format};
265 $info->{formatter
}->{$format} = $code;
268 sub DESTROY
{}; # avoid problems with autoload
273 # also see "man perldiag"
276 (my $method = $sub) =~ s/.*:://;
278 my $info = $this->map_method_by_name($method);
282 return $self->handle($info, @_);
287 sub method_attributes
{
290 return $method_registry->{$self};
293 sub map_method_by_name
{
294 my ($self, $name) = @_;
296 my $info = $method_by_name->{$self}->{$name};
297 die "no such method '${self}::$name'\n" if !$info;
302 sub map_path_to_methods
{
303 my ($class, $stack, $uri_param, $pathmatchref) = @_;
305 my $path_lookup = $method_path_lookup->{$class};
307 # Note: $pathmatchref can be used to obtain path including
308 # uri patterns like '/cluster/firewall/groups/{group}'.
309 # Used by pvesh to display help
310 if (defined($pathmatchref)) {
311 $$pathmatchref = '' if !$$pathmatchref;
314 while (defined(my $comp = shift @$stack)) {
315 return undef if !$path_lookup; # not registerd?
316 if ($path_lookup->{regex
}) {
317 my $name = $path_lookup->{regex
}->{match_name
};
318 my $regex = $path_lookup->{regex
}->{match_re
};
320 return undef if $comp !~ m/^($regex)$/;
321 $uri_param->{$name} = $1;
322 $path_lookup = $path_lookup->{regex
};
323 $$pathmatchref .= '/{' . $name . '}' if defined($pathmatchref);
324 } elsif ($path_lookup->{folders
}) {
325 $path_lookup = $path_lookup->{folders
}->{$comp};
326 $$pathmatchref .= '/' . $comp if defined($pathmatchref);
328 die "internal error";
331 return undef if !$path_lookup;
333 if (my $info = $path_lookup->{SUBCLASS
}) {
334 $class = $info->{subclass
};
336 my $fd = $info->{fragmentDelimiter
};
339 # we only support the empty string '' (match whole URI)
340 die "unsupported fragmentDelimiter '$fd'"
343 $stack = [ join ('/', @$stack) ] if scalar(@$stack) > 1;
345 $path_lookup = $method_path_lookup->{$class};
349 return undef if !$path_lookup;
351 return ($class, $path_lookup);
355 my ($class, $method, $path, $uri_param, $pathmatchref) = @_;
357 my $stack = [ grep { length($_) > 0 } split('\/+' , $path)]; # skip empty fragments
359 my ($handler_class, $path_info);
361 ($handler_class, $path_info) = $class->map_path_to_methods($stack, $uri_param, $pathmatchref);
364 syslog
('err', $err) if $err;
366 return undef if !($handler_class && $path_info);
368 my $method_info = $path_info->{$method};
370 return undef if !$method_info;
372 return ($handler_class, $method_info);
376 my ($self, $info, $param) = @_;
378 my $func = $info->{code
};
380 if (!($info->{name
} && $func)) {
381 raise
("Method lookup failed ('$info->{name}')\n",
382 code
=> HTTP_INTERNAL_SERVER_ERROR
);
385 if (my $schema = $info->{parameters
}) {
386 # warn "validate ". Dumper($param}) . "\n" . Dumper($schema);
387 PVE
::JSONSchema
::validate
($param, $schema);
388 # untaint data (already validated)
389 my $extra = delete $param->{'extra-args'};
390 while (my ($key, $val) = each %$param) {
391 ($param->{$key}) = $val =~ /^(.*)$/s;
393 $param->{'extra-args'} = [map { /^(.*)$/ } @$extra] if $extra;
396 my $result = &$func($param);
398 # todo: this is only to be safe - disable?
399 if (my $schema = $info->{returns
}) {
400 PVE
::JSONSchema
::validate
($result, $schema, "Result verification failed\n");
406 # format option, display type and description
408 # $display_name: for example "-$name" of "<$name>", pass undef to use "$name:"
409 # $phash: json schema property hash
410 # $format: 'asciidoc', 'short', 'long' or 'full'
411 # $style: 'config', 'arg' or 'fixed'
412 my $get_property_description = sub {
413 my ($name, $style, $phash, $format, $hidepw, $fileparams) = @_;
417 $format = 'asciidoc' if !defined($format);
419 my $descr = $phash->{description
} || "no description available";
421 if ($phash->{verbose_description
} &&
422 ($style eq 'config' || $style eq 'config-sub')) {
423 $descr = $phash->{verbose_description
};
428 my $type = PVE
::JSONSchema
::schema_get_type_text
($phash);
430 if ($hidepw && $name eq 'password') {
434 if ($fileparams && $type eq 'string') {
435 foreach my $elem (@$fileparams) {
436 if ($name eq $elem) {
443 if ($format eq 'asciidoc') {
445 if ($style eq 'config') {
447 } elsif ($style eq 'config-sub') {
449 } elsif ($style eq 'arg') {
451 } elsif ($style eq 'fixed') {
452 $res .= "`<$name>` ";
454 die "unknown style '$style'";
457 $res .= "`$type` " if $type;
459 if (defined(my $dv = $phash->{default})) {
460 $res .= "(default=`$dv`)";
463 if ($style eq 'config-sub') {
471 $wdescr =~ s/^$/+/mg;
473 $res .= $wdescr . "\n";
475 if (my $req = $phash->{requires
}) {
476 my $tmp .= ref($req) ?
join(', ', @$req) : $req;
477 $res .= "+\nNOTE: Requires option(s): `$tmp`\n";
481 } elsif ($format eq 'short' || $format eq 'long' || $format eq 'full') {
484 if (defined(my $dv = $phash->{default})) {
485 $defaulttxt = " (default=$dv)";
489 if ($style eq 'config') {
490 $display_name = "$name:";
491 } elsif ($style eq 'arg') {
492 $display_name = "-$name";
493 } elsif ($style eq 'fixed') {
494 $display_name = "<$name>";
496 die "unknown style '$style'";
499 my $tmp = sprintf " %-10s %s$defaulttxt\n", $display_name, "$type";
502 $res .= Text
::Wrap
::wrap
('', $indend, ($tmp));
504 $res .= Text
::Wrap
::wrap
($indend, $indend, ($descr)) . "\n\n";
506 if (my $req = $phash->{requires
}) {
507 my $tmp = "Requires option(s): ";
508 $tmp .= ref($req) ?
join(', ', @$req) : $req;
509 $res .= Text
::Wrap
::wrap
($indend, $indend, ($tmp)). "\n\n";
513 die "unknown format '$format'";
519 # generate usage information for command line tools
521 # $name ... the name of the method
522 # $prefix ... usually something like "$exename $cmd" ('pvesm add')
523 # $arg_param ... list of parameters we want to get as ordered arguments
524 # on the command line (or single parameter name for lists)
525 # $fixed_param ... do not generate and info about those parameters
527 # 'long' ... default (text, list all options)
528 # 'short' ... command line only (text, one line)
529 # 'full' ... text, include description
530 # 'asciidoc' ... generate asciidoc for man pages (like 'full')
531 # $hidepw ... hide password option (use this if you provide a read passwork callback)
532 # $stringfilemap ... mapping for string parameters to file path parameters
534 my ($self, $name, $prefix, $arg_param, $fixed_param, $format, $hidepw, $stringfilemap) = @_;
536 $format = 'long' if !$format;
538 my $info = $self->map_method_by_name($name);
539 my $schema = $info->{parameters
};
540 my $prop = $schema->{properties
};
548 $arg_param = [ $arg_param ] if $arg_param && !ref($arg_param);
550 foreach my $p (@$arg_param) {
551 next if !$prop->{$p}; # just to be sure
552 my $pd = $prop->{$p};
555 $args .= " " if $args;
556 if ($pd->{format
} && $pd->{format
} =~ m/-list/) {
559 $args .= $pd->{optional
} ?
"[<$p>]" : "<$p>";
564 foreach my $k (@$arg_param) {
565 next if defined($fixed_param->{$k}); # just to be sure
566 next if !$prop->{$k}; # just to be sure
567 $argdescr .= &$get_property_description($k, 'fixed', $prop->{$k}, $format, 0);
570 my $idx_param = {}; # -vlan\d+ -scsi\d+
573 foreach my $k (sort keys %$prop) {
574 next if $arg_hash->{$k};
575 next if defined($fixed_param->{$k});
577 my $type = $prop->{$k}->{type
} || 'string';
579 next if $hidepw && ($k eq 'password') && !$prop->{$k}->{optional
};
582 if ($k =~ m/^([a-z]+)(\d+)$/) {
583 my ($name, $idx) = ($1, $2);
584 next if $idx_param->{$name};
586 $idx_param->{$name} = 1;
587 $base = "${name}[n]";
591 my $mapping = defined($stringfilemap) ?
&$stringfilemap($name) : undef;
592 $opts .= &$get_property_description($base, 'arg', $prop->{$k}, $format,
595 if (!$prop->{$k}->{optional
}) {
596 $args .= " " if $args;
597 $args .= "-$base <$type>"
601 if ($format eq 'asciidoc') {
602 $out .= "*${prefix}*";
603 $out .= " `$args`" if $args;
604 $out .= $opts ?
" `[OPTIONS]`\n" : "\n";
606 $out .= "USAGE: " if $format ne 'short';
607 $out .= "$prefix $args";
608 $out .= $opts ?
" [OPTIONS]\n" : "\n";
611 return $out if $format eq 'short';
613 if ($info->{description
}) {
614 if ($format eq 'asciidoc') {
615 my $desc = Text
::Wrap
::wrap
('', '', ($info->{description
}));
616 $out .= "\n$desc\n\n";
617 } elsif ($format eq 'full') {
618 my $desc = Text
::Wrap
::wrap
(' ', ' ', ($info->{description
}));
619 $out .= "\n$desc\n\n";
623 $out .= $argdescr if $argdescr;
625 $out .= $opts if $opts;
630 # generate docs from JSON schema properties
631 sub dump_properties
{
632 my ($prop, $format, $style, $filterFn) = @_;
638 my $idx_param = {}; # -vlan\d+ -scsi\d+
640 foreach my $k (sort keys %$prop) {
641 my $phash = $prop->{$k};
643 next if defined($filterFn) && &$filterFn($k, $phash);
644 next if $phash->{alias
};
647 if ($k =~ m/^([a-z]+)(\d+)$/) {
648 my ($name, $idx) = ($1, $2);
649 next if $idx_param->{$name};
651 $idx_param->{$name} = 1;
652 $base = "${name}[n]";
656 $raw .= &$get_property_description($base, $style, $phash, $format, 0);
658 next if $style ne 'config';
660 my $prop_fmt = $phash->{format
};
663 if (ref($prop_fmt) ne 'HASH') {
664 $prop_fmt = PVE
::JSONSchema
::get_format
($prop_fmt);
667 next if !(ref($prop_fmt) && (ref($prop_fmt) eq 'HASH'));
669 $raw .= dump_properties
($prop_fmt, $format, 'config-sub')
676 my $replace_file_names_with_contents = sub {
677 my ($param, $mapping) = @_;
680 foreach my $elem ( @$mapping ) {
681 $param->{$elem} = PVE
::Tools
::file_get_contents
($param->{$elem})
682 if defined($param->{$elem});
690 my ($self, $prefix, $name, $args, $arg_param, $fixed_param, $pwcallback, $stringfilemap) = @_;
692 my $info = $self->map_method_by_name($name);
696 my $param = PVE
::JSONSchema
::get_options
($info->{parameters
}, $args, $arg_param, $fixed_param, $pwcallback);
697 &$replace_file_names_with_contents($param, &$stringfilemap($name))
698 if defined($stringfilemap);
699 $res = $self->handle($info, $param);
704 die $err if !$ec || $ec ne "PVE::Exception" || !$err->is_param_exc();
706 $err->{usage
} = $self->usage_str($name, $prefix, $arg_param, $fixed_param, 'short', $pwcallback, $stringfilemap);
715 # note: this modifies the original hash by adding the id property
717 my ($hash, $idprop) = @_;
720 return $res if !$hash;
722 foreach my $k (keys %$hash) {
723 $hash->{$k}->{$idprop} = $k;
724 push @$res, $hash->{$k};