1 package PVE
::RESTHandler
;
6 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 our $standard_output_options = {
20 'output-format' => PVE
::JSONSchema
::get_standard_option
('pve-output-format'),
22 description
=> "Do not show column headers (for 'text' format).",
28 description
=> "Do not draw borders (for 'text' format).",
34 description
=> "Suppress printing results.",
39 description
=> "Call output rendering functions to produce human readable text.",
46 sub api_clone_schema
{
47 my ($schema, $no_typetext) = @_;
50 my $ref = ref($schema);
51 die "not a HASH reference" if !($ref && $ref eq 'HASH');
53 foreach my $k (keys %$schema) {
54 my $d = $schema->{$k};
55 if ($k ne 'properties') {
56 $res->{$k} = ref($d) ? clone
($d) : $d;
59 # convert indexed parameters like -net\d+ to -net[n]
60 foreach my $p (keys %$d) {
62 if ($p =~ m/^([a-z]+)(\d+)$/) {
63 my ($name, $idx) = ($1, $2);
64 if ($idx == 0 && defined($d->{"${name}1"})) {
66 } elsif ($idx > 0 && defined($d->{"${name}0"})) {
67 next; # only handle once for -xx0, but only if -xx0 exists
70 my $tmp = ref($pd) ? clone
($pd) : $pd;
71 # NOTE: add typetext property for complexer types, to make the web api-viewer code simpler
72 if (!$no_typetext && !(defined($tmp->{enum
}) || defined($tmp->{pattern
}))) {
73 my $typetext = PVE
::JSONSchema
::schema_get_type_text
($tmp);
74 if ($tmp->{type
} && ($tmp->{type
} ne $typetext)) {
75 $tmp->{typetext
} = $typetext;
78 $res->{$k}->{$p} = $tmp;
86 my ($tree, $index, $class, $prefix, $raw_dump) = @_;
88 $prefix = '' if !$prefix;
90 my $ma = $method_registry->{$class};
92 foreach my $info (@$ma) {
94 my $path = "$prefix/$info->{path}";
97 if ($info->{subclass
}) {
98 api_dump_full
($tree, $index, $info->{subclass
}, $path, $raw_dump);
102 # check if method is unique
103 my $realpath = $path;
104 $realpath =~ s/\{[^\}]+\}/\{\}/g;
105 my $fullpath = "$info->{method} $realpath";
106 die "duplicate path '$realpath'" if $index->{$fullpath};
107 $index->{$fullpath} = $info;
113 foreach my $dir (split('/', $path)) {
116 $res = (grep { $_->{text
} eq $dir } @$treedir)[0];
118 $res->{children
} = [] if !$res->{children
};
119 $treedir = $res->{children
};
126 push @$treedir, $res;
127 $treedir = $res->{children
};
133 foreach my $k (keys %$info) {
134 next if $k eq 'code' || $k eq "match_name" || $k eq "match_re" ||
142 if ($k eq 'parameters') {
143 $data->{$k} = api_clone_schema
($d);
144 } elsif ($k eq 'returns') {
145 $data->{$k} = api_clone_schema
($d, 1);
147 $data->{$k} = ref($d) ? clone
($d) : $d;
151 $res->{info
}->{$info->{method}} = $data;
157 sub api_dump_cleanup_tree
{
160 foreach my $rec (@$tree) {
161 delete $rec->{children
} if $rec->{children
} && !scalar(@{$rec->{children
}});
162 if ($rec->{children
}) {
164 api_dump_cleanup_tree
($rec->{children
});
172 # api_dump_remove_refs: prepare API tree for use with to_json($tree)
173 sub api_dump_remove_refs
{
176 my $class = ref($tree);
177 return $tree if !$class;
179 if ($class eq 'ARRAY') {
181 foreach my $el (@$tree) {
182 push @$res, api_dump_remove_refs
($el);
185 } elsif ($class eq 'HASH') {
187 foreach my $k (keys %$tree) {
188 if (my $itemclass = ref($tree->{$k})) {
189 if ($itemclass eq 'CODE') {
190 next if $k eq 'completion';
192 $res->{$k} = api_dump_remove_refs
($tree->{$k});
194 $res->{$k} = $tree->{$k};
198 } elsif ($class eq 'Regexp') {
199 return "$tree"; # return string representation
201 die "unknown class '$class'\n";
206 my ($class, $prefix, $raw_dump) = @_;
211 api_dump_full
($tree, $index, $class, $prefix, $raw_dump);
212 api_dump_cleanup_tree
($tree);
216 sub validate_method_schemas
{
218 foreach my $class (keys %$method_registry) {
219 my $ma = $method_registry->{$class};
221 foreach my $info (@$ma) {
222 PVE
::JSONSchema
::validate_method_info
($info);
227 sub register_method
{
228 my ($self, $info) = @_;
236 if ($info->{subclass
}) {
237 $errprefix = "register subclass $info->{subclass} at ${self}/$info->{path} -";
238 $method = 'SUBCLASS';
240 $errprefix = "register method ${self}/$info->{path} -";
241 $info->{method} = 'GET' if !$info->{method};
242 $method = $info->{method};
244 # apply default value
245 $info->{allowtoken
} = 1 if !defined($info->{allowtoken
});
248 $method_path_lookup->{$self} = {} if !defined($method_path_lookup->{$self});
249 my $path_lookup = $method_path_lookup->{$self};
251 die "$errprefix no path" if !defined($info->{path
});
253 foreach my $comp (split(/\/+/, $info->{path
})) {
254 die "$errprefix path compoment has zero length\n" if $comp eq '';
256 if ($comp =~ m/^\{([\w-]+)(?::(.*))?\}$/) {
258 $regex = $2 ?
$2 : '\S+';
259 push @$match_re, $regex;
260 push @$match_name, $name;
263 push @$match_re, $name;
264 push @$match_name, undef;
268 $path_lookup->{regex
} = {} if !defined($path_lookup->{regex
});
270 my $old_name = $path_lookup->{regex
}->{match_name
};
271 die "$errprefix found changed regex match name\n"
272 if defined($old_name) && ($old_name ne $name);
273 my $old_re = $path_lookup->{regex
}->{match_re
};
274 die "$errprefix found changed regex\n"
275 if defined($old_re) && ($old_re ne $regex);
276 $path_lookup->{regex
}->{match_name
} = $name;
277 $path_lookup->{regex
}->{match_re
} = $regex;
279 die "$errprefix path match error - regex and fixed items\n"
280 if defined($path_lookup->{folders
});
282 $path_lookup = $path_lookup->{regex
};
285 $path_lookup->{folders
}->{$name} = {} if !defined($path_lookup->{folders
}->{$name});
287 die "$errprefix path match error - regex and fixed items\n"
288 if defined($path_lookup->{regex
});
290 $path_lookup = $path_lookup->{folders
}->{$name};
294 die "$errprefix duplicate method definition\n"
295 if defined($path_lookup->{$method});
297 if ($method eq 'SUBCLASS') {
298 foreach my $m (qw(GET PUT POST DELETE)) {
299 die "$errprefix duplicate method definition SUBCLASS and $m\n" if $path_lookup->{$m};
302 $path_lookup->{$method} = $info;
304 $info->{match_re
} = $match_re;
305 $info->{match_name
} = $match_name;
307 $method_by_name->{$self} = {} if !defined($method_by_name->{$self});
310 die "$errprefix method name already defined\n"
311 if defined($method_by_name->{$self}->{$info->{name
}});
313 $method_by_name->{$self}->{$info->{name
}} = $info;
316 push @{$method_registry->{$self}}, $info;
319 sub DESTROY
{}; # avoid problems with autoload
324 # also see "man perldiag"
327 (my $method = $sub) =~ s/.*:://;
329 my $info = $this->map_method_by_name($method);
332 no strict
'refs'; ## no critic (ProhibitNoStrict)
335 return $self->handle($info, @_);
341 sub method_attributes
{
344 return $method_registry->{$self};
347 sub map_method_by_name
{
348 my ($self, $name) = @_;
350 my $info = $method_by_name->{$self}->{$name};
351 die "no such method '${self}::$name'\n" if !$info;
356 sub map_path_to_methods
{
357 my ($class, $stack, $uri_param, $pathmatchref) = @_;
359 my $path_lookup = $method_path_lookup->{$class};
361 # Note: $pathmatchref can be used to obtain path including
362 # uri patterns like '/cluster/firewall/groups/{group}'.
363 # Used by pvesh to display help
364 if (defined($pathmatchref)) {
365 $$pathmatchref = '' if !$$pathmatchref;
368 while (defined(my $comp = shift @$stack)) {
369 return undef if !$path_lookup; # not registerd?
370 if ($path_lookup->{regex
}) {
371 my $name = $path_lookup->{regex
}->{match_name
};
372 my $regex = $path_lookup->{regex
}->{match_re
};
374 return undef if $comp !~ m/^($regex)$/;
375 $uri_param->{$name} = $1;
376 $path_lookup = $path_lookup->{regex
};
377 $$pathmatchref .= '/{' . $name . '}' if defined($pathmatchref);
378 } elsif ($path_lookup->{folders
}) {
379 $path_lookup = $path_lookup->{folders
}->{$comp};
380 $$pathmatchref .= '/' . $comp if defined($pathmatchref);
382 die "internal error";
385 return undef if !$path_lookup;
387 if (my $info = $path_lookup->{SUBCLASS
}) {
388 $class = $info->{subclass
};
390 my $fd = $info->{fragmentDelimiter
};
393 # we only support the empty string '' (match whole URI)
394 die "unsupported fragmentDelimiter '$fd'"
397 $stack = [ join ('/', @$stack) ] if scalar(@$stack) > 1;
399 $path_lookup = $method_path_lookup->{$class};
403 return undef if !$path_lookup;
405 return ($class, $path_lookup);
409 my ($class, $method, $path, $uri_param, $pathmatchref) = @_;
411 my $stack = [ grep { length($_) > 0 } split('\/+' , $path)]; # skip empty fragments
413 my ($handler_class, $path_info);
415 ($handler_class, $path_info) = $class->map_path_to_methods($stack, $uri_param, $pathmatchref);
418 syslog
('err', $err) if $err;
420 return undef if !($handler_class && $path_info);
422 my $method_info = $path_info->{$method};
424 return undef if !$method_info;
426 return ($handler_class, $method_info);
429 my sub untaint_recursive
: prototype($) {
430 use feature
'current_sub';
434 my $ref = ref($param);
435 if ($ref eq 'HASH') {
436 $param->{$_} = __SUB__-
>($param->{$_}) for keys $param->%*;
437 } elsif ($ref eq 'ARRAY') {
438 for (my $i = 0; $i < scalar($param->@*); $i++) {
439 $param->[$i] = __SUB__-
>($param->[$i]);
442 if (defined($param)) {
443 my ($newval) = $param =~ /^(.*)$/s;
451 # convert arrays to strings where we expect a '-list' format and convert scalar
452 # values to arrays when we expect an array (because of www-form-urlencoded)
454 # only on the top level, since www-form-urlencoded cannot be nested anyway
456 # FIXME: change gui/api calls to not rely on this during 8.x, mark the
457 # behaviour deprecated with 9.x, and remove it with 10.x
458 my $normalize_legacy_param_formats = sub {
459 my ($param, $schema) = @_;
461 return $param if !$schema->{properties
};
462 return $param if (ref($param) // '') ne 'HASH';
464 for my $key (keys $schema->{properties
}->%*) {
465 if (my $value = $param->{$key}) {
466 my $type = $schema->{properties
}->{$key}->{type
} // '';
467 my $format = $schema->{properties
}->{$key}->{format
} // '';
468 my $ref = ref($value);
469 if ($ref && $ref eq 'ARRAY' && $type eq 'string' && $format =~ m/-list$/) {
470 $param->{$key} = join(',', $value->@*);
471 } elsif (!$ref && $type eq 'array') {
472 $param->{$key} = [$value];
481 my ($self, $info, $param, $result_verification) = @_;
483 my $func = $info->{code
};
485 if (!($info->{name
} && $func)) {
486 raise
("Method lookup failed ('$info->{name}')\n", code
=> HTTP_INTERNAL_SERVER_ERROR
);
489 if (my $schema = $info->{parameters
}) {
490 # warn "validate ". Dumper($param}) . "\n" . Dumper($schema);
491 $param = $normalize_legacy_param_formats->($param, $schema);
492 PVE
::JSONSchema
::validate
($param, $schema);
493 # untaint data (already validated)
494 $param = untaint_recursive
($param);
497 my $result = $func->($param); # the actual API code execution call
499 if ($result_verification && (my $schema = $info->{returns
})) {
500 # return validation is rather lose-lose, as it can require quite a bit of time and lead to
501 # false-positive errors, any HTTP API handler should avoid enabling it by default.
502 PVE
::JSONSchema
::validate
($result, $schema, "Result verification failed\n");
507 # format option, display type and description
509 # $display_name: for example "-$name" of "<$name>", pass undef to use "$name:"
510 # $phash: json schema property hash
511 # $format: 'asciidoc', 'short', 'long' or 'full'
512 # $style: 'config', 'config-sub', 'arg' or 'fixed'
513 # $mapdef: parameter mapping ({ desc => XXX, func => sub {...} })
514 my $get_property_description = sub {
515 my ($name, $style, $phash, $format, $mapdef) = @_;
519 $format = 'asciidoc' if !defined($format);
521 my $descr = $phash->{description
} || "no description available";
523 if ($phash->{verbose_description
} &&
524 ($style eq 'config' || $style eq 'config-sub')) {
525 $descr = $phash->{verbose_description
};
530 my $type_text = PVE
::JSONSchema
::schema_get_type_text
($phash, $style);
532 if ($mapdef && $phash->{type
} eq 'string') {
533 $type_text = $mapdef->{desc
};
536 if ($format eq 'asciidoc') {
538 if ($style eq 'config') {
540 } elsif ($style eq 'config-sub') {
542 } elsif ($style eq 'arg') {
543 $res .= "`--$name` ";
544 } elsif ($style eq 'fixed') {
545 $res .= "`<$name>`: ";
547 die "unknown style '$style'";
550 $res .= "`$type_text` " if $type_text;
552 if (defined(my $dv = $phash->{default})) {
553 $res .= "('default =' `$dv`)";
556 if ($style eq 'config-sub') {
564 $wdescr =~ s/^$/+/mg;
566 $wdescr =~ s/{/\\{/g;
567 $wdescr =~ s/}/\\}/g;
569 $res .= $wdescr . "\n";
571 if (my $req = $phash->{requires
}) {
572 my $tmp .= ref($req) ?
join(', ', @$req) : $req;
573 $res .= "+\nNOTE: Requires option(s): `$tmp`\n";
577 } elsif ($format eq 'short' || $format eq 'long' || $format eq 'full') {
580 if (defined(my $dv = $phash->{default})) {
581 $defaulttxt = " (default=$dv)";
585 if ($style eq 'config') {
586 $display_name = "$name:";
587 } elsif ($style eq 'arg') {
588 $display_name = "-$name";
589 } elsif ($style eq 'fixed') {
590 $display_name = "<$name>";
592 die "unknown style '$style'";
595 my $tmp = sprintf " %-10s %s%s\n", $display_name, "$type_text", "$defaulttxt";
598 $res .= Text
::Wrap
::wrap
('', $indend, ($tmp));
599 $res .= Text
::Wrap
::wrap
($indend, $indend, ($descr)) . "\n\n";
601 if (my $req = $phash->{requires
}) {
602 my $tmp = "Requires option(s): ";
603 $tmp .= ref($req) ?
join(', ', @$req) : $req;
604 $res .= Text
::Wrap
::wrap
($indend, $indend, ($tmp)). "\n\n";
608 die "unknown format '$format'";
614 # translate parameter mapping definition
615 # $mapping_array is a array which can contain:
616 # strings ... in that case we assume it is a parameter name, and
617 # we want to load that parameter from a file
618 # [ param_name, func, desc] ... allows you to specify a arbitrary
619 # mapping func for any param
621 # Returns: a hash indexed by parameter_name,
622 # i.e. { param_name => { func => .., desc => ... } }
623 my $compute_param_mapping_hash = sub {
624 my ($mapping_array) = @_;
628 return $res if !defined($mapping_array);
630 foreach my $item (@$mapping_array) {
631 my ($name, $func, $desc, $interactive);
632 if (ref($item) eq 'ARRAY') {
633 ($name, $func, $desc, $interactive) = @$item;
634 } elsif (ref($item) eq 'HASH') {
636 $res->{$item->{name
}} = $item;
640 $func = sub { return PVE
::Tools
::file_get_contents
($_[0]) };
642 $desc //= '<filepath>';
643 $res->{$name} = { desc
=> $desc, func
=> $func, interactive
=> $interactive };
649 # generate usage information for command line tools
651 # $info ... method info
652 # $prefix ... usually something like "$exename $cmd" ('pvesm add')
653 # $arg_param ... list of parameters we want to get as ordered arguments
654 # on the command line (or single parameter name for lists)
655 # $fixed_param ... do not generate and info about those parameters
657 # 'long' ... default (text, list all options)
658 # 'short' ... command line only (text, one line)
659 # 'full' ... text, include description
660 # 'asciidoc' ... generate asciidoc for man pages (like 'full')
661 # $param_cb ... mapping for string parameters to file path parameters
662 # $formatter_properties ... additional property definitions (passed to output formatter)
664 my ($info, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties) = @_;
666 $format = 'long' if !$format;
668 my $schema = $info->{parameters
};
669 my $name = $info->{name
};
671 if ($schema->{properties
}) {
672 $prop = { %{$schema->{properties
}} }; # copy
675 my $has_output_format_option = $formatter_properties->{'output-format'} ?
1 : 0;
677 if ($formatter_properties) {
678 foreach my $key (keys %$formatter_properties) {
679 if (!$standard_output_options->{$key}) {
680 $prop->{$key} = $formatter_properties->{$key};
685 # also remove $standard_output_options from $prop (pvesh, pveclient)
686 if ($prop->{'output-format'}) {
687 $has_output_format_option = 1;
688 foreach my $key (keys %$prop) {
689 if ($standard_output_options->{$key}) {
690 delete $prop->{$key};
701 $arg_param = [ $arg_param ] if $arg_param && !ref($arg_param);
703 foreach my $p (@$arg_param) {
704 next if !$prop->{$p}; # just to be sure
705 my $pd = $prop->{$p};
708 $args .= " " if $args;
709 if ($pd->{format
} && $pd->{format
} =~ m/-list/) {
712 $args .= $pd->{optional
} ?
"[<$p>]" : "<$p>";
717 foreach my $k (@$arg_param) {
718 next if defined($fixed_param->{$k}); # just to be sure
719 next if !$prop->{$k}; # just to be sure
720 $argdescr .= $get_property_description->($k, 'fixed', $prop->{$k}, $format);
723 my $idx_param = {}; # -vlan\d+ -scsi\d+
726 foreach my $k (sort keys %$prop) {
727 next if $arg_hash->{$k};
728 next if defined($fixed_param->{$k});
730 my $type_text = $prop->{$k}->{type
} || 'string';
734 if (defined($param_cb)) {
735 my $mapping = $param_cb->($name);
736 $param_map = $compute_param_mapping_hash->($mapping);
737 next if $k eq 'password' && $param_map->{$k} && !$prop->{$k}->{optional
};
741 if ($k =~ m/^([a-z]+)(\d+)$/) {
742 my ($name, $idx) = ($1, $2);
743 next if $idx_param->{$name};
744 if ($idx == 0 && defined($prop->{"${name}1"})) {
745 $idx_param->{$name} = 1;
746 $base = "${name}[n]";
751 $opts .= $get_property_description->($base, 'arg', $prop->{$k}, $format, $param_map->{$k});
753 if (!$prop->{$k}->{optional
}) {
754 $args .= " " if $args;
755 $args .= "--$base <$type_text>"
759 if ($format eq 'asciidoc') {
760 $out .= "*${prefix}*";
761 $out .= " `$args`" if $args;
762 $out .= " `[OPTIONS]`" if $opts;
763 $out .= " `[FORMAT_OPTIONS]`" if $has_output_format_option;
766 $out .= "USAGE: " if $format ne 'short';
767 $out .= "$prefix $args";
768 $out .= " [OPTIONS]" if $opts;
769 $out .= " [FORMAT_OPTIONS]" if $has_output_format_option;
773 return $out if $format eq 'short';
775 if ($info->{description
}) {
776 if ($format eq 'asciidoc') {
777 my $desc = Text
::Wrap
::wrap
('', '', ($info->{description
}));
778 $out .= "\n$desc\n\n";
779 } elsif ($format eq 'full') {
780 my $desc = Text
::Wrap
::wrap
(' ', ' ', ($info->{description
}));
785 $out .= $argdescr if $argdescr;
787 $out .= $opts if $opts;
793 my ($self, $name, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties) = @_;
795 my $info = $self->map_method_by_name($name);
797 return getopt_usage
($info, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties);
800 # generate docs from JSON schema properties
801 sub dump_properties
{
802 my ($prop, $format, $style, $filterFn) = @_;
808 my $idx_param = {}; # -vlan\d+ -scsi\d+
810 foreach my $k (sort keys %$prop) {
811 my $phash = $prop->{$k};
813 next if defined($filterFn) && &$filterFn($k, $phash);
814 next if $phash->{alias
};
817 if ($k =~ m/^([a-z]+)(\d+)$/) {
818 my ($name, $idx) = ($1, $2);
819 next if $idx_param->{$name};
820 if ($idx == 0 && defined($prop->{"${name}1"})) {
821 $idx_param->{$name} = 1;
822 $base = "${name}[n]";
826 $raw .= $get_property_description->($base, $style, $phash, $format);
828 next if $style ne 'config';
830 my $prop_fmt = $phash->{format
};
833 if (ref($prop_fmt) ne 'HASH') {
834 $prop_fmt = PVE
::JSONSchema
::get_format
($prop_fmt);
837 next if !(ref($prop_fmt) && (ref($prop_fmt) eq 'HASH'));
839 $raw .= dump_properties
($prop_fmt, $format, 'config-sub')
846 my $replace_file_names_with_contents = sub {
847 my ($param, $param_map) = @_;
849 while (my ($k, $d) = each %$param_map) {
850 next if $d->{interactive
}; # handled by the JSONSchema's get_options code
851 $param->{$k} = $d->{func
}->($param->{$k})
852 if defined($param->{$k});
858 sub add_standard_output_properties
{
859 my ($propdef, $list) = @_;
863 $list //= [ keys %$standard_output_options ];
865 my $res = { %$propdef }; # copy
867 foreach my $opt (@$list) {
868 die "no such standard output option '$opt'\n" if !defined($standard_output_options->{$opt});
869 die "detected overwriten standard CLI parameter '$opt'\n" if defined($res->{$opt});
870 $res->{$opt} = $standard_output_options->{$opt};
876 sub extract_standard_output_properties
{
880 foreach my $opt (keys %$standard_output_options) {
881 $options->{$opt} = delete $data->{$opt} if defined($data->{$opt});
888 my ($self, $prefix, $name, $args, $arg_param, $fixed_param, $param_cb, $formatter_properties) = @_;
890 my $info = $self->map_method_by_name($name);
896 $param_map = $compute_param_mapping_hash->($param_cb->($name)) if $param_cb;
897 my $schema = { %{$info->{parameters
}} }; # copy
898 $schema->{properties
} = { %{$schema->{properties
}}, %$formatter_properties } if $formatter_properties;
899 my $param = PVE
::JSONSchema
::get_options
($schema, $args, $arg_param, $fixed_param, $param_map);
901 if ($formatter_properties) {
902 foreach my $opt (keys %$formatter_properties) {
903 $fmt_param->{$opt} = delete $param->{$opt} if defined($param->{$opt});
907 if (defined($param_map)) {
908 $replace_file_names_with_contents->($param, $param_map);
911 $res = $self->handle($info, $param, 1);
916 die $err if !$ec || $ec ne "PVE::Exception" || !$err->is_param_exc();
918 $err->{usage
} = $self->usage_str($name, $prefix, $arg_param, $fixed_param, 'short', $param_cb, $formatter_properties);
923 return wantarray ?
($res, $fmt_param) : $res;
927 # note: this modifies the original hash by adding the id property
929 my ($hash, $idprop) = @_;
932 return $res if !$hash;
934 foreach my $k (keys %$hash) {
935 $hash->{$k}->{$idprop} = $k;
936 push @$res, $hash->{$k};