1 package PVE
::RESTHandler
;
4 no strict
'refs'; # our autoload requires this
8 use PVE
::Exception
qw(raise raise_param_exc);
11 use HTTP
::Status
qw(:constants :is status_message);
13 use Storable
qw(dclone);
15 my $method_registry = {};
16 my $method_by_name = {};
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) ? dclone
($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+)$/) {
43 $res->{$k}->{$p} = ref($pd) ? dclone
($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) ? dclone
($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) = @_;
160 foreach my $comp (split(/\/+/, $info->{path
})) {
161 die "path compoment has zero length" if $comp eq '';
162 if ($comp =~ m/^\{(\w+)(:(.*))?\}$/) {
164 push @$match_re, $3 ?
$3 : '\S+';
165 push @$match_name, $1;
167 push @$match_re, $comp;
168 push @$match_name, undef;
172 $info->{match_re
} = $match_re;
173 $info->{match_name
} = $match_name;
175 $method_by_name->{$self} = {} if !defined($method_by_name->{$self});
178 die "method '${self}::$info->{name}' already defined\n"
179 if defined($method_by_name->{$self}->{$info->{name
}});
181 $method_by_name->{$self}->{$info->{name
}} = $info;
184 push @{$method_registry->{$self}}, $info;
190 # also see "man perldiag"
193 (my $method = $sub) =~ s/.*:://;
197 my $info = $this->map_method_by_name($method);
201 return $self->handle($info, @_);
206 sub method_attributes
{
209 return $method_registry->{$self};
212 sub map_method_by_name
{
213 my ($self, $name) = @_;
215 my $info = $method_by_name->{$self}->{$name};
216 die "no such method '${self}::$name'\n" if !$info;
222 my ($self, $stack, $method, $uri_param) = @_;
224 my $ma = $method_registry->{$self};
226 my $stacklen = scalar(@$stack);
228 #syslog ('info', "MAPTEST:$method:$self: " . join ('/', @$stack));
230 foreach my $info (@$ma) {
231 #syslog ('info', "TEST0 " . Dumper($info));
232 next if !($info->{subclass
} || ($info->{method} eq $method));
233 my $regexlen = scalar(@{$info->{match_re
}});
234 if ($info->{subclass
}) {
235 next if $stacklen < $regexlen;
237 next if $stacklen != $regexlen;
240 #syslog ('info', "TEST1 " . Dumper($info));
244 for (; $i < $regexlen; $i++) {
245 my $comp = $stack->[$i];
246 my $re = $info->{match_re
}->[$i];
247 #print "COMPARE $comp $info->{match_re}->[$i]\n";
248 my ($match) = $stack->[$i] =~ m/^($re)$/;
249 last if !defined($match);
250 if (my $name = $info->{match_name
}->[$i]) {
251 $param->{$name} = $match;
255 next if $i != $regexlen;
257 #print "MATCH $info->{name}\n";
259 foreach my $p (keys %$param) {
260 $uri_param->{$p} = $param->{$p};
267 sub __find_handler_full
{
268 my ($class, $method, $stack, $uri_param, $pathmatchref) = @_;
272 $info = $class->map_method($stack, $method, $uri_param);
274 syslog
('err', $@) if $@;
276 return undef if !$info;
278 $$pathmatchref .= '/' . $info->{path
};
280 if (my $subh = $info->{subclass
}) {
282 my $matchlen = scalar(@{$info->{match_re
}});
284 for (my $i = 0; $i < $matchlen; $i++) {
285 shift @$stack; # pop from stack
288 my $fd = $info->{fragmentDelimiter
};
292 # we only support the empty string '' (match whole URI)
293 die "unsupported fragmentDelimiter '$fd'"
296 $stack = [ join ('/', @$stack) ] if scalar(@$stack) > 1;
299 return $subh->__find_handler_full($method, $stack, $uri_param, $pathmatchref);
302 return ($class, $info, $$pathmatchref);
306 my ($class, $method, $path, $uri_param) = @_;
308 my $stack = [ grep { length($_) > 0 } split('\/+' , $path)]; # skip empty fragments
311 return $class->__find_handler_full($method, $stack, $uri_param, \
$pathmatch);
315 my ($self, $info, $param) = @_;
317 my $func = $info->{code
};
319 if (!($info->{name
} && $func)) {
320 raise
("Method lookup failed ('$info->{name}')\n",
321 code
=> HTTP_INTERNAL_SERVER_ERROR
);
324 if (my $schema = $info->{parameters
}) {
325 # warn "validate ". Dumper($param}) . "\n" . Dumper($schema);
326 PVE
::JSONSchema
::validate
($param, $schema);
327 # untaint data (already validated)
328 while (my ($key, $val) = each %$param) {
329 ($param->{$key}) = $val =~ /^(.*)$/s;
333 my $result = &$func($param);
335 # todo: this is only to be safe - disable?
336 if (my $schema = $info->{returns
}) {
337 PVE
::JSONSchema
::validate
($result, $schema, "Result verification vailed\n");
343 # generate usage information for command line tools
345 # $name ... the name of the method
346 # $prefix ... usually something like "$exename $cmd" ('pvesm add')
347 # $arg_param ... list of parameters we want to get as ordered arguments
348 # on the command line (or single parameter name for lists)
349 # $fixed_param ... do not generate and info about those parameters
351 # 'long' ... default (list all options)
352 # 'short' ... command line only (one line)
353 # 'full' ... also include description
354 # $hidepw ... hide password option (use this if you provide a read passwork callback)
356 my ($self, $name, $prefix, $arg_param, $fixed_param, $format, $hidepw) = @_;
358 $format = 'long' if !$format;
360 my $info = $self->map_method_by_name($name);
361 my $schema = $info->{parameters
};
362 my $prop = $schema->{properties
};
370 $arg_param = [ $arg_param ] if $arg_param && !ref($arg_param);
372 foreach my $p (@$arg_param) {
373 next if !$prop->{$p}; # just to be sure
374 my $pd = $prop->{$p};
377 $args .= " " if $args;
378 if ($pd->{format
} && $pd->{format
} =~ m/-list/) {
381 $args .= $pd->{optional
} ?
"[<$p>]" : "<$p>";
385 my $get_prop_descr = sub {
386 my ($k, $display_name) = @_;
388 my $phash = $prop->{$k};
392 my $descr = $phash->{description
} || "no description available";
395 my $type = PVE
::PodParser
::schema_get_type_text
($phash);
397 if ($hidepw && $k eq 'password') {
402 if (defined(my $dv = $phash->{default})) {
403 $defaulttxt = " (default=$dv)";
405 my $tmp = sprintf " %-10s %s$defaulttxt\n", $display_name, "$type";
408 $res .= Text
::Wrap
::wrap
('', $indend, ($tmp));
410 $res .= Text
::Wrap
::wrap
($indend, $indend, ($descr)) . "\n\n";
412 if (my $req = $phash->{requires
}) {
413 my $tmp = "Requires option(s): ";
414 $tmp .= ref($req) ?
join(', ', @$req) : $req;
415 $res .= Text
::Wrap
::wrap
($indend, $indend, ($tmp)). "\n\n";
422 foreach my $k (@$arg_param) {
423 next if defined($fixed_param->{$k}); # just to be sure
424 next if !$prop->{$k}; # just to be sure
425 $argdescr .= &$get_prop_descr($k, "<$k>");
428 my $idx_param = {}; # -vlan\d+ -scsi\d+
431 foreach my $k (sort keys %$prop) {
432 next if $arg_hash->{$k};
433 next if defined($fixed_param->{$k});
435 my $type = $prop->{$k}->{type
} || 'string';
437 next if $hidepw && ($k eq 'password') && !$prop->{$k}->{optional
};
440 if ($k =~ m/^([a-z]+)(\d+)$/) {
442 next if $idx_param->{$name};
443 $idx_param->{$name} = 1;
444 $base = "${name}[n]";
447 $opts .= &$get_prop_descr($k, "-$base");
449 if (!$prop->{$k}->{optional
}) {
450 $args .= " " if $args;
451 $args .= "-$base <$type>"
455 $out .= "USAGE: " if $format ne 'short';
457 $out .= "$prefix $args";
459 $out .= $opts ?
" [OPTIONS]\n" : "\n";
461 return $out if $format eq 'short';
463 if ($info->{description
} && $format eq 'full') {
464 my $desc = Text
::Wrap
::wrap
(' ', ' ', ($info->{description
}));
465 $out .= "\n$desc\n\n";
468 $out .= $argdescr if $argdescr;
470 $out .= $opts if $opts;
476 my ($self, $prefix, $name, $args, $arg_param, $fixed_param, $pwcallback) = @_;
478 my $info = $self->map_method_by_name($name);
481 foreach my $p (keys %$fixed_param) {
482 $param->{$p} = $fixed_param->{$p};
487 if (ref($arg_param)) {
488 foreach my $p (@$arg_param) {
489 $param->{$p} = shift @$args if $args->[0] && $args->[0] !~ m/^-/;
492 my $pd = $info->{parameters
}->{properties
}->{$arg_param};
493 die "expected list format $pd->{format}"
494 if !($pd && $pd->{format
} && $pd->{format
} =~ m/-list/);
495 $list_param = $arg_param;
501 my $param = PVE
::JSONSchema
::get_options
($info->{parameters
}, $args, $param, $pwcallback, $list_param);
503 $res = $self->handle($info, $param);
508 die $err if !$ec || $ec ne "PVE::Exception" || !$err->is_param_exc();
510 $err->{usage
} = $self->usage_str($name, $prefix, $arg_param, $fixed_param, 'short', $pwcallback);
519 # note: this modifies the original hash by adding the id property
521 my ($hash, $idprop) = @_;
524 return $res if !$hash;
526 foreach my $k (keys %$hash) {
527 $hash->{$k}->{$idprop} = $k;
528 push @$res, $hash->{$k};