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);
37 if ($idx == 0 && defined($d->{"${name}1"})) {
39 } elsif (defined($d->{"${name}0"})) {
40 next; # only handle once for -xx0, but only if -xx0 exists
43 my $tmp = ref($pd) ? clone
($pd) : $pd;
44 # NOTE: add typetext property for more complex types, to
45 # make the web api viewer code simpler
46 if (!(defined($tmp->{enum
}) || defined($tmp->{pattern
}))) {
47 my $typetext = PVE
::JSONSchema
::schema_get_type_text
($tmp);
48 if ($tmp->{type
} && ($tmp->{type
} ne $typetext)) {
49 $tmp->{typetext
} = $typetext;
52 $res->{$k}->{$p} = $tmp;
60 my ($tree, $index, $class, $prefix) = @_;
62 $prefix = '' if !$prefix;
64 my $ma = $method_registry->{$class};
66 foreach my $info (@$ma) {
68 my $path = "$prefix/$info->{path}";
71 if ($info->{subclass
}) {
72 api_dump_full
($tree, $index, $info->{subclass
}, $path);
76 # check if method is unique
78 $realpath =~ s/\{[^\}]+\}/\{\}/g;
79 my $fullpath = "$info->{method} $realpath";
80 die "duplicate path '$realpath'" if $index->{$fullpath};
81 $index->{$fullpath} = $info;
87 foreach my $dir (split('/', $path)) {
90 $res = (grep { $_->{text
} eq $dir } @$treedir)[0];
92 $res->{children
} = [] if !$res->{children
};
93 $treedir = $res->{children
};
100 push @$treedir, $res;
101 $treedir = $res->{children
};
107 foreach my $k (keys %$info) {
108 next if $k eq 'code' || $k eq "match_name" || $k eq "match_re" ||
113 if ($k eq 'parameters') {
114 $data->{$k} = api_clone_schema
($d);
117 $data->{$k} = ref($d) ? clone
($d) : $d;
120 $res->{info
}->{$info->{method}} = $data;
126 sub api_dump_cleanup_tree
{
129 foreach my $rec (@$tree) {
130 delete $rec->{children
} if $rec->{children
} && !scalar(@{$rec->{children
}});
131 if ($rec->{children
}) {
133 api_dump_cleanup_tree
($rec->{children
});
142 my ($class, $prefix) = @_;
147 api_dump_full
($tree, $index, $class);
148 api_dump_cleanup_tree
($tree);
152 sub validate_method_schemas
{
154 foreach my $class (keys %$method_registry) {
155 my $ma = $method_registry->{$class};
157 foreach my $info (@$ma) {
158 PVE
::JSONSchema
::validate_method_info
($info);
163 sub register_method
{
164 my ($self, $info) = @_;
172 if ($info->{subclass
}) {
173 $errprefix = "register subclass $info->{subclass} at ${self}/$info->{path} -";
174 $method = 'SUBCLASS';
176 $errprefix = "register method ${self}/$info->{path} -";
177 $info->{method} = 'GET' if !$info->{method};
178 $method = $info->{method};
181 $method_path_lookup->{$self} = {} if !defined($method_path_lookup->{$self});
182 my $path_lookup = $method_path_lookup->{$self};
184 die "$errprefix no path" if !defined($info->{path
});
186 foreach my $comp (split(/\/+/, $info->{path
})) {
187 die "$errprefix path compoment has zero length\n" if $comp eq '';
189 if ($comp =~ m/^\{(\w+)(:(.*))?\}$/) {
191 $regex = $3 ?
$3 : '\S+';
192 push @$match_re, $regex;
193 push @$match_name, $name;
196 push @$match_re, $name;
197 push @$match_name, undef;
201 $path_lookup->{regex
} = {} if !defined($path_lookup->{regex
});
203 my $old_name = $path_lookup->{regex
}->{match_name
};
204 die "$errprefix found changed regex match name\n"
205 if defined($old_name) && ($old_name ne $name);
206 my $old_re = $path_lookup->{regex
}->{match_re
};
207 die "$errprefix found changed regex\n"
208 if defined($old_re) && ($old_re ne $regex);
209 $path_lookup->{regex
}->{match_name
} = $name;
210 $path_lookup->{regex
}->{match_re
} = $regex;
212 die "$errprefix path match error - regex and fixed items\n"
213 if defined($path_lookup->{folders
});
215 $path_lookup = $path_lookup->{regex
};
218 $path_lookup->{folders
}->{$name} = {} if !defined($path_lookup->{folders
}->{$name});
220 die "$errprefix path match error - regex and fixed items\n"
221 if defined($path_lookup->{regex
});
223 $path_lookup = $path_lookup->{folders
}->{$name};
227 die "$errprefix duplicate method definition\n"
228 if defined($path_lookup->{$method});
230 if ($method eq 'SUBCLASS') {
231 foreach my $m (qw(GET PUT POST DELETE)) {
232 die "$errprefix duplicate method definition SUBCLASS and $m\n" if $path_lookup->{$m};
235 $path_lookup->{$method} = $info;
237 $info->{match_re
} = $match_re;
238 $info->{match_name
} = $match_name;
240 $method_by_name->{$self} = {} if !defined($method_by_name->{$self});
243 die "$errprefix method name already defined\n"
244 if defined($method_by_name->{$self}->{$info->{name
}});
246 $method_by_name->{$self}->{$info->{name
}} = $info;
249 push @{$method_registry->{$self}}, $info;
252 sub DESTROY
{}; # avoid problems with autoload
257 # also see "man perldiag"
260 (my $method = $sub) =~ s/.*:://;
262 my $info = $this->map_method_by_name($method);
266 return $self->handle($info, @_);
271 sub method_attributes
{
274 return $method_registry->{$self};
277 sub map_method_by_name
{
278 my ($self, $name) = @_;
280 my $info = $method_by_name->{$self}->{$name};
281 die "no such method '${self}::$name'\n" if !$info;
286 sub map_path_to_methods
{
287 my ($class, $stack, $uri_param, $pathmatchref) = @_;
289 my $path_lookup = $method_path_lookup->{$class};
291 # Note: $pathmatchref can be used to obtain path including
292 # uri patterns like '/cluster/firewall/groups/{group}'.
293 # Used by pvesh to display help
294 if (defined($pathmatchref)) {
295 $$pathmatchref = '' if !$$pathmatchref;
298 while (defined(my $comp = shift @$stack)) {
299 return undef if !$path_lookup; # not registerd?
300 if ($path_lookup->{regex
}) {
301 my $name = $path_lookup->{regex
}->{match_name
};
302 my $regex = $path_lookup->{regex
}->{match_re
};
304 return undef if $comp !~ m/^($regex)$/;
305 $uri_param->{$name} = $1;
306 $path_lookup = $path_lookup->{regex
};
307 $$pathmatchref .= '/{' . $name . '}' if defined($pathmatchref);
308 } elsif ($path_lookup->{folders
}) {
309 $path_lookup = $path_lookup->{folders
}->{$comp};
310 $$pathmatchref .= '/' . $comp if defined($pathmatchref);
312 die "internal error";
315 return undef if !$path_lookup;
317 if (my $info = $path_lookup->{SUBCLASS
}) {
318 $class = $info->{subclass
};
320 my $fd = $info->{fragmentDelimiter
};
323 # we only support the empty string '' (match whole URI)
324 die "unsupported fragmentDelimiter '$fd'"
327 $stack = [ join ('/', @$stack) ] if scalar(@$stack) > 1;
329 $path_lookup = $method_path_lookup->{$class};
333 return undef if !$path_lookup;
335 return ($class, $path_lookup);
339 my ($class, $method, $path, $uri_param, $pathmatchref) = @_;
341 my $stack = [ grep { length($_) > 0 } split('\/+' , $path)]; # skip empty fragments
343 my ($handler_class, $path_info);
345 ($handler_class, $path_info) = $class->map_path_to_methods($stack, $uri_param, $pathmatchref);
348 syslog
('err', $err) if $err;
350 return undef if !($handler_class && $path_info);
352 my $method_info = $path_info->{$method};
354 return undef if !$method_info;
356 return ($handler_class, $method_info);
360 my ($self, $info, $param) = @_;
362 my $func = $info->{code
};
364 if (!($info->{name
} && $func)) {
365 raise
("Method lookup failed ('$info->{name}')\n",
366 code
=> HTTP_INTERNAL_SERVER_ERROR
);
369 if (my $schema = $info->{parameters
}) {
370 # warn "validate ". Dumper($param}) . "\n" . Dumper($schema);
371 PVE
::JSONSchema
::validate
($param, $schema);
372 # untaint data (already validated)
373 my $extra = delete $param->{'extra-args'};
374 while (my ($key, $val) = each %$param) {
375 ($param->{$key}) = $val =~ /^(.*)$/s;
377 $param->{'extra-args'} = [map { /^(.*)$/ } @$extra] if $extra;
380 my $result = &$func($param);
382 # todo: this is only to be safe - disable?
383 if (my $schema = $info->{returns
}) {
384 PVE
::JSONSchema
::validate
($result, $schema, "Result verification failed\n");
390 # format option, display type and description
392 # $display_name: for example "-$name" of "<$name>", pass undef to use "$name:"
393 # $phash: json schema property hash
394 # $format: 'asciidoc', 'short', 'long' or 'full'
395 # $style: 'config', 'config-sub', 'arg' or 'fixed'
396 my $get_property_description = sub {
397 my ($name, $style, $phash, $format, $hidepw, $fileparams) = @_;
401 $format = 'asciidoc' if !defined($format);
403 my $descr = $phash->{description
} || "no description available";
405 if ($phash->{verbose_description
} &&
406 ($style eq 'config' || $style eq 'config-sub')) {
407 $descr = $phash->{verbose_description
};
412 my $type = PVE
::JSONSchema
::schema_get_type_text
($phash, $style);
414 if ($hidepw && $name eq 'password') {
418 if ($fileparams && $type eq 'string') {
419 foreach my $elem (@$fileparams) {
420 if ($name eq $elem) {
421 $type = '<filepath>';
427 if ($format eq 'asciidoc') {
429 if ($style eq 'config') {
431 } elsif ($style eq 'config-sub') {
433 } elsif ($style eq 'arg') {
435 } elsif ($style eq 'fixed') {
436 $res .= "`<$name>`: ";
438 die "unknown style '$style'";
441 $res .= "`$type` " if $type;
443 if (defined(my $dv = $phash->{default})) {
444 $res .= "('default =' `$dv`)";
447 if ($style eq 'config-sub') {
455 $wdescr =~ s/^$/+/mg;
457 $res .= $wdescr . "\n";
459 if (my $req = $phash->{requires
}) {
460 my $tmp .= ref($req) ?
join(', ', @$req) : $req;
461 $res .= "+\nNOTE: Requires option(s): `$tmp`\n";
465 } elsif ($format eq 'short' || $format eq 'long' || $format eq 'full') {
468 if (defined(my $dv = $phash->{default})) {
469 $defaulttxt = " (default=$dv)";
473 if ($style eq 'config') {
474 $display_name = "$name:";
475 } elsif ($style eq 'arg') {
476 $display_name = "-$name";
477 } elsif ($style eq 'fixed') {
478 $display_name = "<$name>";
480 die "unknown style '$style'";
483 my $tmp = sprintf " %-10s %s$defaulttxt\n", $display_name, "$type";
486 $res .= Text
::Wrap
::wrap
('', $indend, ($tmp));
488 $res .= Text
::Wrap
::wrap
($indend, $indend, ($descr)) . "\n\n";
490 if (my $req = $phash->{requires
}) {
491 my $tmp = "Requires option(s): ";
492 $tmp .= ref($req) ?
join(', ', @$req) : $req;
493 $res .= Text
::Wrap
::wrap
($indend, $indend, ($tmp)). "\n\n";
497 die "unknown format '$format'";
503 # generate usage information for command line tools
505 # $name ... the name of the method
506 # $prefix ... usually something like "$exename $cmd" ('pvesm add')
507 # $arg_param ... list of parameters we want to get as ordered arguments
508 # on the command line (or single parameter name for lists)
509 # $fixed_param ... do not generate and info about those parameters
511 # 'long' ... default (text, list all options)
512 # 'short' ... command line only (text, one line)
513 # 'full' ... text, include description
514 # 'asciidoc' ... generate asciidoc for man pages (like 'full')
515 # $hidepw ... hide password option (use this if you provide a read passwork callback)
516 # $stringfilemap ... mapping for string parameters to file path parameters
518 my ($self, $name, $prefix, $arg_param, $fixed_param, $format, $hidepw, $stringfilemap) = @_;
520 $format = 'long' if !$format;
522 my $info = $self->map_method_by_name($name);
523 my $schema = $info->{parameters
};
524 my $prop = $schema->{properties
};
532 $arg_param = [ $arg_param ] if $arg_param && !ref($arg_param);
534 foreach my $p (@$arg_param) {
535 next if !$prop->{$p}; # just to be sure
536 my $pd = $prop->{$p};
539 $args .= " " if $args;
540 if ($pd->{format
} && $pd->{format
} =~ m/-list/) {
543 $args .= $pd->{optional
} ?
"[<$p>]" : "<$p>";
548 foreach my $k (@$arg_param) {
549 next if defined($fixed_param->{$k}); # just to be sure
550 next if !$prop->{$k}; # just to be sure
551 $argdescr .= &$get_property_description($k, 'fixed', $prop->{$k}, $format, 0);
554 my $idx_param = {}; # -vlan\d+ -scsi\d+
557 foreach my $k (sort keys %$prop) {
558 next if $arg_hash->{$k};
559 next if defined($fixed_param->{$k});
561 my $type = $prop->{$k}->{type
} || 'string';
563 next if $hidepw && ($k eq 'password') && !$prop->{$k}->{optional
};
566 if ($k =~ m/^([a-z]+)(\d+)$/) {
567 my ($name, $idx) = ($1, $2);
568 next if $idx_param->{$name};
569 if ($idx == 0 && defined($prop->{"${name}1"})) {
570 $idx_param->{$name} = 1;
571 $base = "${name}[n]";
575 my $mapping = defined($stringfilemap) ?
&$stringfilemap($name) : undef;
576 $opts .= &$get_property_description($base, 'arg', $prop->{$k}, $format,
579 if (!$prop->{$k}->{optional
}) {
580 $args .= " " if $args;
581 $args .= "-$base <$type>"
585 if ($format eq 'asciidoc') {
586 $out .= "*${prefix}*";
587 $out .= " `$args`" if $args;
588 $out .= $opts ?
" `[OPTIONS]`\n" : "\n";
590 $out .= "USAGE: " if $format ne 'short';
591 $out .= "$prefix $args";
592 $out .= $opts ?
" [OPTIONS]\n" : "\n";
595 return $out if $format eq 'short';
597 if ($info->{description
}) {
598 if ($format eq 'asciidoc') {
599 my $desc = Text
::Wrap
::wrap
('', '', ($info->{description
}));
600 $out .= "\n$desc\n\n";
601 } elsif ($format eq 'full') {
602 my $desc = Text
::Wrap
::wrap
(' ', ' ', ($info->{description
}));
603 $out .= "\n$desc\n\n";
607 $out .= $argdescr if $argdescr;
609 $out .= $opts if $opts;
614 # generate docs from JSON schema properties
615 sub dump_properties
{
616 my ($prop, $format, $style, $filterFn) = @_;
622 my $idx_param = {}; # -vlan\d+ -scsi\d+
624 foreach my $k (sort keys %$prop) {
625 my $phash = $prop->{$k};
627 next if defined($filterFn) && &$filterFn($k, $phash);
628 next if $phash->{alias
};
631 if ($k =~ m/^([a-z]+)(\d+)$/) {
632 my ($name, $idx) = ($1, $2);
633 next if $idx_param->{$name};
634 if ($idx == 0 && defined($prop->{"${name}1"})) {
635 $idx_param->{$name} = 1;
636 $base = "${name}[n]";
640 $raw .= &$get_property_description($base, $style, $phash, $format, 0);
642 next if $style ne 'config';
644 my $prop_fmt = $phash->{format
};
647 if (ref($prop_fmt) ne 'HASH') {
648 $prop_fmt = PVE
::JSONSchema
::get_format
($prop_fmt);
651 next if !(ref($prop_fmt) && (ref($prop_fmt) eq 'HASH'));
653 $raw .= dump_properties
($prop_fmt, $format, 'config-sub')
660 my $replace_file_names_with_contents = sub {
661 my ($param, $mapping) = @_;
664 foreach my $elem ( @$mapping ) {
665 $param->{$elem} = PVE
::Tools
::file_get_contents
($param->{$elem})
666 if defined($param->{$elem});
674 my ($self, $prefix, $name, $args, $arg_param, $fixed_param, $pwcallback, $stringfilemap) = @_;
676 my $info = $self->map_method_by_name($name);
680 my $param = PVE
::JSONSchema
::get_options
($info->{parameters
}, $args, $arg_param, $fixed_param, $pwcallback);
681 &$replace_file_names_with_contents($param, &$stringfilemap($name))
682 if defined($stringfilemap);
683 $res = $self->handle($info, $param);
688 die $err if !$ec || $ec ne "PVE::Exception" || !$err->is_param_exc();
690 $err->{usage
} = $self->usage_str($name, $prefix, $arg_param, $fixed_param, 'short', $pwcallback, $stringfilemap);
699 # note: this modifies the original hash by adding the id property
701 my ($hash, $idprop) = @_;
704 return $res if !$hash;
706 foreach my $k (keys %$hash) {
707 $hash->{$k}->{$idprop} = $k;
708 push @$res, $hash->{$k};