1 package PVE
::RESTHandler
;
4 no strict
'refs'; # our autoload requires this
7 use PVE
::Exception
qw(raise raise_param_exc);
10 use HTTP
::Status
qw(:constants :is status_message);
14 my $method_registry = {};
15 my $method_by_name = {};
16 my $method_path_lookup = {};
18 our $AUTOLOAD; # it's a package global
20 sub api_clone_schema
{
24 my $ref = ref($schema);
25 die "not a HASH reference" if !($ref && $ref eq 'HASH');
27 foreach my $k (keys %$schema) {
28 my $d = $schema->{$k};
29 if ($k ne 'properties') {
30 $res->{$k} = ref($d) ? clone
($d) : $d;
33 # convert indexed parameters like -net\d+ to -net[n]
34 foreach my $p (keys %$d) {
36 if ($p =~ m/^([a-z]+)(\d+)$/) {
37 my ($name, $idx) = ($1, $2);
38 if ($idx == 0 && defined($d->{"${name}1"})) {
40 } elsif (defined($d->{"${name}0"})) {
41 next; # only handle once for -xx0, but only if -xx0 exists
44 my $tmp = ref($pd) ? clone
($pd) : $pd;
45 # NOTE: add typetext property for more complex types, to
46 # make the web api viewer code simpler
47 if (!(defined($tmp->{enum
}) || defined($tmp->{pattern
}))) {
48 my $typetext = PVE
::JSONSchema
::schema_get_type_text
($tmp);
49 if ($tmp->{type
} && ($tmp->{type
} ne $typetext)) {
50 $tmp->{typetext
} = $typetext;
53 $res->{$k}->{$p} = $tmp;
61 my ($tree, $index, $class, $prefix) = @_;
63 $prefix = '' if !$prefix;
65 my $ma = $method_registry->{$class};
67 foreach my $info (@$ma) {
69 my $path = "$prefix/$info->{path}";
72 if ($info->{subclass
}) {
73 api_dump_full
($tree, $index, $info->{subclass
}, $path);
77 # check if method is unique
79 $realpath =~ s/\{[^\}]+\}/\{\}/g;
80 my $fullpath = "$info->{method} $realpath";
81 die "duplicate path '$realpath'" if $index->{$fullpath};
82 $index->{$fullpath} = $info;
88 foreach my $dir (split('/', $path)) {
91 $res = (grep { $_->{text
} eq $dir } @$treedir)[0];
93 $res->{children
} = [] if !$res->{children
};
94 $treedir = $res->{children
};
101 push @$treedir, $res;
102 $treedir = $res->{children
};
108 foreach my $k (keys %$info) {
109 next if $k eq 'code' || $k eq "match_name" || $k eq "match_re" ||
114 if ($k eq 'parameters') {
115 $data->{$k} = api_clone_schema
($d);
118 $data->{$k} = ref($d) ? clone
($d) : $d;
121 $res->{info
}->{$info->{method}} = $data;
127 sub api_dump_cleanup_tree
{
130 foreach my $rec (@$tree) {
131 delete $rec->{children
} if $rec->{children
} && !scalar(@{$rec->{children
}});
132 if ($rec->{children
}) {
134 api_dump_cleanup_tree
($rec->{children
});
143 my ($class, $prefix) = @_;
148 api_dump_full
($tree, $index, $class);
149 api_dump_cleanup_tree
($tree);
153 sub validate_method_schemas
{
155 foreach my $class (keys %$method_registry) {
156 my $ma = $method_registry->{$class};
158 foreach my $info (@$ma) {
159 PVE
::JSONSchema
::validate_method_info
($info);
164 sub register_method
{
165 my ($self, $info) = @_;
173 if ($info->{subclass
}) {
174 $errprefix = "register subclass $info->{subclass} at ${self}/$info->{path} -";
175 $method = 'SUBCLASS';
177 $errprefix = "register method ${self}/$info->{path} -";
178 $info->{method} = 'GET' if !$info->{method};
179 $method = $info->{method};
182 $method_path_lookup->{$self} = {} if !defined($method_path_lookup->{$self});
183 my $path_lookup = $method_path_lookup->{$self};
185 die "$errprefix no path" if !defined($info->{path
});
187 foreach my $comp (split(/\/+/, $info->{path
})) {
188 die "$errprefix path compoment has zero length\n" if $comp eq '';
190 if ($comp =~ m/^\{(\w+)(:(.*))?\}$/) {
192 $regex = $3 ?
$3 : '\S+';
193 push @$match_re, $regex;
194 push @$match_name, $name;
197 push @$match_re, $name;
198 push @$match_name, undef;
202 $path_lookup->{regex
} = {} if !defined($path_lookup->{regex
});
204 my $old_name = $path_lookup->{regex
}->{match_name
};
205 die "$errprefix found changed regex match name\n"
206 if defined($old_name) && ($old_name ne $name);
207 my $old_re = $path_lookup->{regex
}->{match_re
};
208 die "$errprefix found changed regex\n"
209 if defined($old_re) && ($old_re ne $regex);
210 $path_lookup->{regex
}->{match_name
} = $name;
211 $path_lookup->{regex
}->{match_re
} = $regex;
213 die "$errprefix path match error - regex and fixed items\n"
214 if defined($path_lookup->{folders
});
216 $path_lookup = $path_lookup->{regex
};
219 $path_lookup->{folders
}->{$name} = {} if !defined($path_lookup->{folders
}->{$name});
221 die "$errprefix path match error - regex and fixed items\n"
222 if defined($path_lookup->{regex
});
224 $path_lookup = $path_lookup->{folders
}->{$name};
228 die "$errprefix duplicate method definition\n"
229 if defined($path_lookup->{$method});
231 if ($method eq 'SUBCLASS') {
232 foreach my $m (qw(GET PUT POST DELETE)) {
233 die "$errprefix duplicate method definition SUBCLASS and $m\n" if $path_lookup->{$m};
236 $path_lookup->{$method} = $info;
238 $info->{match_re
} = $match_re;
239 $info->{match_name
} = $match_name;
241 $method_by_name->{$self} = {} if !defined($method_by_name->{$self});
244 die "$errprefix method name already defined\n"
245 if defined($method_by_name->{$self}->{$info->{name
}});
247 $method_by_name->{$self}->{$info->{name
}} = $info;
250 push @{$method_registry->{$self}}, $info;
253 sub DESTROY
{}; # avoid problems with autoload
258 # also see "man perldiag"
261 (my $method = $sub) =~ s/.*:://;
263 my $info = $this->map_method_by_name($method);
267 return $self->handle($info, @_);
272 sub method_attributes
{
275 return $method_registry->{$self};
278 sub map_method_by_name
{
279 my ($self, $name) = @_;
281 my $info = $method_by_name->{$self}->{$name};
282 die "no such method '${self}::$name'\n" if !$info;
287 sub map_path_to_methods
{
288 my ($class, $stack, $uri_param, $pathmatchref) = @_;
290 my $path_lookup = $method_path_lookup->{$class};
292 # Note: $pathmatchref can be used to obtain path including
293 # uri patterns like '/cluster/firewall/groups/{group}'.
294 # Used by pvesh to display help
295 if (defined($pathmatchref)) {
296 $$pathmatchref = '' if !$$pathmatchref;
299 while (defined(my $comp = shift @$stack)) {
300 return undef if !$path_lookup; # not registerd?
301 if ($path_lookup->{regex
}) {
302 my $name = $path_lookup->{regex
}->{match_name
};
303 my $regex = $path_lookup->{regex
}->{match_re
};
305 return undef if $comp !~ m/^($regex)$/;
306 $uri_param->{$name} = $1;
307 $path_lookup = $path_lookup->{regex
};
308 $$pathmatchref .= '/{' . $name . '}' if defined($pathmatchref);
309 } elsif ($path_lookup->{folders
}) {
310 $path_lookup = $path_lookup->{folders
}->{$comp};
311 $$pathmatchref .= '/' . $comp if defined($pathmatchref);
313 die "internal error";
316 return undef if !$path_lookup;
318 if (my $info = $path_lookup->{SUBCLASS
}) {
319 $class = $info->{subclass
};
321 my $fd = $info->{fragmentDelimiter
};
324 # we only support the empty string '' (match whole URI)
325 die "unsupported fragmentDelimiter '$fd'"
328 $stack = [ join ('/', @$stack) ] if scalar(@$stack) > 1;
330 $path_lookup = $method_path_lookup->{$class};
334 return undef if !$path_lookup;
336 return ($class, $path_lookup);
340 my ($class, $method, $path, $uri_param, $pathmatchref) = @_;
342 my $stack = [ grep { length($_) > 0 } split('\/+' , $path)]; # skip empty fragments
344 my ($handler_class, $path_info);
346 ($handler_class, $path_info) = $class->map_path_to_methods($stack, $uri_param, $pathmatchref);
349 syslog
('err', $err) if $err;
351 return undef if !($handler_class && $path_info);
353 my $method_info = $path_info->{$method};
355 return undef if !$method_info;
357 return ($handler_class, $method_info);
361 my ($self, $info, $param) = @_;
363 my $func = $info->{code
};
365 if (!($info->{name
} && $func)) {
366 raise
("Method lookup failed ('$info->{name}')\n",
367 code
=> HTTP_INTERNAL_SERVER_ERROR
);
370 if (my $schema = $info->{parameters
}) {
371 # warn "validate ". Dumper($param}) . "\n" . Dumper($schema);
372 PVE
::JSONSchema
::validate
($param, $schema);
373 # untaint data (already validated)
374 my $extra = delete $param->{'extra-args'};
375 while (my ($key, $val) = each %$param) {
376 ($param->{$key}) = $val =~ /^(.*)$/s;
378 $param->{'extra-args'} = [map { /^(.*)$/ } @$extra] if $extra;
381 my $result = &$func($param);
383 # todo: this is only to be safe - disable?
384 if (my $schema = $info->{returns
}) {
385 PVE
::JSONSchema
::validate
($result, $schema, "Result verification failed\n");
391 # format option, display type and description
393 # $display_name: for example "-$name" of "<$name>", pass undef to use "$name:"
394 # $phash: json schema property hash
395 # $format: 'asciidoc', 'short', 'long' or 'full'
396 # $style: 'config', 'config-sub', 'arg' or 'fixed'
397 # $mapdef: parameter mapping ({ desc => XXX, func => sub {...} })
398 my $get_property_description = sub {
399 my ($name, $style, $phash, $format, $hidepw, $mapdef) = @_;
403 $format = 'asciidoc' if !defined($format);
405 my $descr = $phash->{description
} || "no description available";
407 if ($phash->{verbose_description
} &&
408 ($style eq 'config' || $style eq 'config-sub')) {
409 $descr = $phash->{verbose_description
};
414 my $type_text = PVE
::JSONSchema
::schema_get_type_text
($phash, $style);
416 if ($hidepw && $name eq 'password') {
420 if ($mapdef && $phash->{type
} eq 'string') {
421 $type_text = $mapdef->{desc
};
424 if ($format eq 'asciidoc') {
426 if ($style eq 'config') {
428 } elsif ($style eq 'config-sub') {
430 } elsif ($style eq 'arg') {
431 $res .= "`--$name` ";
432 } elsif ($style eq 'fixed') {
433 $res .= "`<$name>`: ";
435 die "unknown style '$style'";
438 $res .= "`$type_text` " if $type_text;
440 if (defined(my $dv = $phash->{default})) {
441 $res .= "('default =' `$dv`)";
444 if ($style eq 'config-sub') {
452 $wdescr =~ s/^$/+/mg;
454 $res .= $wdescr . "\n";
456 if (my $req = $phash->{requires
}) {
457 my $tmp .= ref($req) ?
join(', ', @$req) : $req;
458 $res .= "+\nNOTE: Requires option(s): `$tmp`\n";
462 } elsif ($format eq 'short' || $format eq 'long' || $format eq 'full') {
465 if (defined(my $dv = $phash->{default})) {
466 $defaulttxt = " (default=$dv)";
470 if ($style eq 'config') {
471 $display_name = "$name:";
472 } elsif ($style eq 'arg') {
473 $display_name = "-$name";
474 } elsif ($style eq 'fixed') {
475 $display_name = "<$name>";
477 die "unknown style '$style'";
480 my $tmp = sprintf " %-10s %s$defaulttxt\n", $display_name, "$type_text";
483 $res .= Text
::Wrap
::wrap
('', $indend, ($tmp));
485 $res .= Text
::Wrap
::wrap
($indend, $indend, ($descr)) . "\n\n";
487 if (my $req = $phash->{requires
}) {
488 my $tmp = "Requires option(s): ";
489 $tmp .= ref($req) ?
join(', ', @$req) : $req;
490 $res .= Text
::Wrap
::wrap
($indend, $indend, ($tmp)). "\n\n";
494 die "unknown format '$format'";
500 # translate parameter mapping definition
501 # $mapping_array is a array which can contain:
502 # strings ... in that case we assume it is a parameter name, and
503 # we want to load that parameter from a file
504 # [ param_name, func, desc] ... allows you to specify a arbitrary
505 # mapping func for any param
507 # Returns: a hash indexed by parameter_name,
508 # i.e. { param_name => { func => .., desc => ... } }
509 my $compute_param_mapping_hash = sub {
510 my ($mapping_array) = @_;
514 return $res if !defined($mapping_array);
516 foreach my $item (@$mapping_array) {
517 my ($name, $func, $desc);
518 if (ref($item) eq 'ARRAY') {
519 ($name, $func, $desc) = @$item;
522 $func = sub { return PVE
::Tools
::file_get_contents
($_[0]) };
524 $desc //= '<filepath>';
525 $res->{$name} = { desc
=> $desc, func
=> $func };
531 # generate usage information for command line tools
533 # $name ... the name of the method
534 # $prefix ... usually something like "$exename $cmd" ('pvesm add')
535 # $arg_param ... list of parameters we want to get as ordered arguments
536 # on the command line (or single parameter name for lists)
537 # $fixed_param ... do not generate and info about those parameters
539 # 'long' ... default (text, list all options)
540 # 'short' ... command line only (text, one line)
541 # 'full' ... text, include description
542 # 'asciidoc' ... generate asciidoc for man pages (like 'full')
543 # $hidepw ... hide password option (use this if you provide a read passwork callback)
544 # $param_mapping_func ... mapping for string parameters to file path parameters
546 my ($self, $name, $prefix, $arg_param, $fixed_param, $format, $hidepw, $param_mapping_func) = @_;
548 $format = 'long' if !$format;
550 my $info = $self->map_method_by_name($name);
551 my $schema = $info->{parameters
};
552 my $prop = $schema->{properties
};
560 $arg_param = [ $arg_param ] if $arg_param && !ref($arg_param);
562 foreach my $p (@$arg_param) {
563 next if !$prop->{$p}; # just to be sure
564 my $pd = $prop->{$p};
567 $args .= " " if $args;
568 if ($pd->{format
} && $pd->{format
} =~ m/-list/) {
571 $args .= $pd->{optional
} ?
"[<$p>]" : "<$p>";
576 foreach my $k (@$arg_param) {
577 next if defined($fixed_param->{$k}); # just to be sure
578 next if !$prop->{$k}; # just to be sure
579 $argdescr .= &$get_property_description($k, 'fixed', $prop->{$k}, $format, 0);
582 my $idx_param = {}; # -vlan\d+ -scsi\d+
585 foreach my $k (sort keys %$prop) {
586 next if $arg_hash->{$k};
587 next if defined($fixed_param->{$k});
589 my $type_text = $prop->{$k}->{type
} || 'string';
591 next if $hidepw && ($k eq 'password') && !$prop->{$k}->{optional
};
594 if ($k =~ m/^([a-z]+)(\d+)$/) {
595 my ($name, $idx) = ($1, $2);
596 next if $idx_param->{$name};
597 if ($idx == 0 && defined($prop->{"${name}1"})) {
598 $idx_param->{$name} = 1;
599 $base = "${name}[n]";
603 my $param_mapping_hash = $compute_param_mapping_hash->(&$param_mapping_func($name))
604 if $param_mapping_func;
606 $opts .= &$get_property_description($base, 'arg', $prop->{$k}, $format,
607 $hidepw, $param_mapping_hash->{$k});
609 if (!$prop->{$k}->{optional
}) {
610 $args .= " " if $args;
611 $args .= "--$base <$type_text>"
615 if ($format eq 'asciidoc') {
616 $out .= "*${prefix}*";
617 $out .= " `$args`" if $args;
618 $out .= $opts ?
" `[OPTIONS]`\n" : "\n";
620 $out .= "USAGE: " if $format ne 'short';
621 $out .= "$prefix $args";
622 $out .= $opts ?
" [OPTIONS]\n" : "\n";
625 return $out if $format eq 'short';
627 if ($info->{description
}) {
628 if ($format eq 'asciidoc') {
629 my $desc = Text
::Wrap
::wrap
('', '', ($info->{description
}));
630 $out .= "\n$desc\n\n";
631 } elsif ($format eq 'full') {
632 my $desc = Text
::Wrap
::wrap
(' ', ' ', ($info->{description
}));
633 $out .= "\n$desc\n\n";
637 $out .= $argdescr if $argdescr;
639 $out .= $opts if $opts;
644 # generate docs from JSON schema properties
645 sub dump_properties
{
646 my ($prop, $format, $style, $filterFn) = @_;
652 my $idx_param = {}; # -vlan\d+ -scsi\d+
654 foreach my $k (sort keys %$prop) {
655 my $phash = $prop->{$k};
657 next if defined($filterFn) && &$filterFn($k, $phash);
658 next if $phash->{alias
};
661 if ($k =~ m/^([a-z]+)(\d+)$/) {
662 my ($name, $idx) = ($1, $2);
663 next if $idx_param->{$name};
664 if ($idx == 0 && defined($prop->{"${name}1"})) {
665 $idx_param->{$name} = 1;
666 $base = "${name}[n]";
670 $raw .= &$get_property_description($base, $style, $phash, $format, 0);
672 next if $style ne 'config';
674 my $prop_fmt = $phash->{format
};
677 if (ref($prop_fmt) ne 'HASH') {
678 $prop_fmt = PVE
::JSONSchema
::get_format
($prop_fmt);
681 next if !(ref($prop_fmt) && (ref($prop_fmt) eq 'HASH'));
683 $raw .= dump_properties
($prop_fmt, $format, 'config-sub')
690 my $replace_file_names_with_contents = sub {
691 my ($param, $param_mapping_hash) = @_;
693 while (my ($k, $d) = each %$param_mapping_hash) {
694 $param->{$k} = $d->{func
}->($param->{$k})
695 if defined($param->{$k});
702 my ($self, $prefix, $name, $args, $arg_param, $fixed_param, $read_password_func, $param_mapping_func) = @_;
704 my $info = $self->map_method_by_name($name);
708 my $param = PVE
::JSONSchema
::get_options
($info->{parameters
}, $args, $arg_param, $fixed_param, $read_password_func);
710 if (defined($param_mapping_func)) {
711 my $param_mapping_hash = $compute_param_mapping_hash->(&$param_mapping_func($name));
712 &$replace_file_names_with_contents($param, $param_mapping_hash);
715 $res = $self->handle($info, $param);
720 die $err if !$ec || $ec ne "PVE::Exception" || !$err->is_param_exc();
722 $err->{usage
} = $self->usage_str($name, $prefix, $arg_param, $fixed_param, 'short', $read_password_func, $param_mapping_func);
731 # note: this modifies the original hash by adding the id property
733 my ($hash, $idprop) = @_;
736 return $res if !$hash;
738 foreach my $k (keys %$hash) {
739 $hash->{$k}->{$idprop} = $k;
740 push @$res, $hash->{$k};