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);
12 use Storable
qw(dclone);
14 my $method_registry = {};
15 my $method_by_name = {};
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) ? dclone
($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+)$/) {
42 $res->{$k}->{$p} = ref($pd) ? dclone
($pd) : $pd;
50 my ($tree, $index, $class, $prefix) = @_;
52 $prefix = '' if !$prefix;
54 my $ma = $method_registry->{$class};
56 foreach my $info (@$ma) {
58 my $path = "$prefix/$info->{path}";
61 if ($info->{subclass
}) {
62 api_dump_full
($tree, $index, $info->{subclass
}, $path);
66 # check if method is unique
68 $realpath =~ s/\{[^\}]+\}/\{\}/g;
69 my $fullpath = "$info->{method} $realpath";
70 die "duplicate path '$realpath'" if $index->{$fullpath};
71 $index->{$fullpath} = $info;
77 foreach my $dir (split('/', $path)) {
80 $res = (grep { $_->{text
} eq $dir } @$treedir)[0];
82 $res->{children
} = [] if !$res->{children
};
83 $treedir = $res->{children
};
91 $treedir = $res->{children
};
97 foreach my $k (keys %$info) {
98 next if $k eq 'code' || $k eq "match_name" || $k eq "match_re" ||
103 if ($k eq 'parameters') {
104 $data->{$k} = api_clone_schema
($d);
107 $data->{$k} = ref($d) ? dclone
($d) : $d;
110 $res->{info
}->{$info->{method}} = $data;
116 sub api_dump_cleanup_tree
{
119 foreach my $rec (@$tree) {
120 delete $rec->{children
} if $rec->{children
} && !scalar(@{$rec->{children
}});
121 if ($rec->{children
}) {
123 api_dump_cleanup_tree
($rec->{children
});
132 my ($class, $prefix) = @_;
137 api_dump_full
($tree, $index, $class);
138 api_dump_cleanup_tree
($tree);
142 sub validate_method_schemas
{
144 foreach my $class (keys %$method_registry) {
145 my $ma = $method_registry->{$class};
147 foreach my $info (@$ma) {
148 PVE
::JSONSchema
::validate_method_info
($info);
153 sub register_method
{
154 my ($self, $info) = @_;
159 foreach my $comp (split(/\/+/, $info->{path
})) {
160 die "path compoment has zero length" if $comp eq '';
161 if ($comp =~ m/^\{(\w+)(:(.*))?\}$/) {
163 push @$match_re, $3 ?
$3 : '\S+';
164 push @$match_name, $1;
166 push @$match_re, $comp;
167 push @$match_name, undef;
171 $info->{match_re
} = $match_re;
172 $info->{match_name
} = $match_name;
174 $method_by_name->{$self} = {} if !defined($method_by_name->{$self});
177 die "method '${self}::$info->{name}' already defined\n"
178 if defined($method_by_name->{$self}->{$info->{name
}});
180 $method_by_name->{$self}->{$info->{name
}} = $info;
183 push @{$method_registry->{$self}}, $info;
189 # also see "man perldiag"
192 (my $method = $sub) =~ s/.*:://;
196 my $info = $this->map_method_by_name($method);
200 return $self->handle($info, @_);
205 sub method_attributes
{
208 return $method_registry->{$self};
211 sub map_method_by_name
{
212 my ($self, $name) = @_;
214 my $info = $method_by_name->{$self}->{$name};
215 die "no such method '${self}::$name'\n" if !$info;
221 my ($self, $stack, $method, $uri_param) = @_;
223 my $ma = $method_registry->{$self};
225 my $stacklen = scalar(@$stack);
227 #syslog ('info', "MAPTEST:$method:$self: " . join ('/', @$stack));
229 foreach my $info (@$ma) {
230 #syslog ('info', "TEST0 " . Dumper($info));
231 next if !($info->{subclass
} || ($info->{method} eq $method));
232 my $regexlen = scalar(@{$info->{match_re
}});
233 if ($info->{subclass
}) {
234 next if $stacklen < $regexlen;
236 next if $stacklen != $regexlen;
239 #syslog ('info', "TEST1 " . Dumper($info));
243 for (; $i < $regexlen; $i++) {
244 my $comp = $stack->[$i];
245 my $re = $info->{match_re
}->[$i];
246 #print "COMPARE $comp $info->{match_re}->[$i]\n";
247 my ($match) = $stack->[$i] =~ m/^($re)$/;
248 last if !defined($match);
249 if (my $name = $info->{match_name
}->[$i]) {
250 $param->{$name} = $match;
254 next if $i != $regexlen;
256 #print "MATCH $info->{name}\n";
258 foreach my $p (keys %$param) {
259 $uri_param->{$p} = $param->{$p};
266 sub __find_handler_full
{
267 my ($class, $method, $stack, $uri_param, $pathmatchref) = @_;
271 $info = $class->map_method($stack, $method, $uri_param);
273 syslog
('err', $@) if $@;
275 return undef if !$info;
277 $$pathmatchref .= '/' . $info->{path
};
279 if (my $subh = $info->{subclass
}) {
281 my $matchlen = scalar(@{$info->{match_re
}});
283 for (my $i = 0; $i < $matchlen; $i++) {
284 shift @$stack; # pop from stack
287 my $fd = $info->{fragmentDelimiter
};
291 # we only support the empty string '' (match whole URI)
292 die "unsupported fragmentDelimiter '$fd'"
295 $stack = [ join ('/', @$stack) ] if scalar(@$stack) > 1;
298 return $subh->__find_handler_full($method, $stack, $uri_param, $pathmatchref);
301 return ($class, $info, $$pathmatchref);
305 my ($class, $method, $path, $uri_param) = @_;
307 my $stack = [ grep { length($_) > 0 } split('\/+' , $path)]; # skip empty fragments
310 return $class->__find_handler_full($method, $stack, $uri_param, \
$pathmatch);
314 my ($self, $info, $param) = @_;
316 my $func = $info->{code
};
318 if (!($info->{name
} && $func)) {
319 raise
("Method lookup failed ('$info->{name}')\n",
320 code
=> HTTP_INTERNAL_SERVER_ERROR
);
323 if (my $schema = $info->{parameters
}) {
324 # warn "validate ". Dumper($param}) . "\n" . Dumper($schema);
325 PVE
::JSONSchema
::validate
($param, $schema);
326 # untaint data (already validated)
327 while (my ($key, $val) = each %$param) {
328 ($param->{$key}) = $val =~ /^(.*)$/s;
332 my $result = &$func($param);
334 # todo: this is only to be safe - disable?
335 if (my $schema = $info->{returns
}) {
336 PVE
::JSONSchema
::validate
($result, $schema, "Result verification vailed\n");
342 # generate usage information for command line tools
344 # $name ... the name of the method
345 # $prefix ... usually something like "$exename $cmd" ('pvesm add')
346 # $arg_param ... list of parameters we want to get as ordered arguments
347 # on the command line (or single parameter name for lists)
348 # $fixed_param ... do not generate and info about those parameters
350 # 'long' ... default (list all options)
351 # 'short' ... command line only (one line)
352 # 'full' ... also include description
353 # $hidepw ... hide password option (use this if you provide a read passwork callback)
355 my ($self, $name, $prefix, $arg_param, $fixed_param, $format, $hidepw) = @_;
357 $format = 'long' if !$format;
359 my $info = $self->map_method_by_name($name);
360 my $schema = $info->{parameters
};
361 my $prop = $schema->{properties
};
369 $arg_param = [ $arg_param ] if $arg_param && !ref($arg_param);
371 foreach my $p (@$arg_param) {
372 next if !$prop->{$p}; # just to be sure
373 my $pd = $prop->{$p};
376 $args .= " " if $args;
377 if ($pd->{format
} && $pd->{format
} =~ m/-list/) {
380 $args .= $pd->{optional
} ?
"[<$p>]" : "<$p>";
384 my $get_prop_descr = sub {
385 my ($k, $display_name) = @_;
387 my $phash = $prop->{$k};
391 my $descr = $phash->{description
} || "no description available";
394 my $type = PVE
::PodParser
::schema_get_type_text
($phash);
396 if ($hidepw && $k eq 'password') {
401 if (defined(my $dv = $phash->{default})) {
402 $defaulttxt = " (default=$dv)";
404 my $tmp = sprintf " %-10s %s$defaulttxt\n", $display_name, "$type";
407 $res .= Text
::Wrap
::wrap
('', $indend, ($tmp));
409 $res .= Text
::Wrap
::wrap
($indend, $indend, ($descr)) . "\n\n";
411 if (my $req = $phash->{requires
}) {
412 my $tmp = "Requires option(s): ";
413 $tmp .= ref($req) ?
join(', ', @$req) : $req;
414 $res .= Text
::Wrap
::wrap
($indend, $indend, ($tmp)). "\n\n";
421 foreach my $k (@$arg_param) {
422 next if defined($fixed_param->{$k}); # just to be sure
423 next if !$prop->{$k}; # just to be sure
424 $argdescr .= &$get_prop_descr($k, "<$k>");
427 my $idx_param = {}; # -vlan\d+ -scsi\d+
430 foreach my $k (sort keys %$prop) {
431 next if $arg_hash->{$k};
432 next if defined($fixed_param->{$k});
434 my $type = $prop->{$k}->{type
} || 'string';
436 next if $hidepw && ($k eq 'password') && !$prop->{$k}->{optional
};
439 if ($k =~ m/^([a-z]+)(\d+)$/) {
441 next if $idx_param->{$name};
442 $idx_param->{$name} = 1;
443 $base = "${name}[n]";
446 $opts .= &$get_prop_descr($k, "-$base");
448 if (!$prop->{$k}->{optional
}) {
449 $args .= " " if $args;
450 $args .= "-$base <$type>"
454 $out .= "USAGE: " if $format ne 'short';
456 $out .= "$prefix $args";
458 $out .= $opts ?
" [OPTIONS]\n" : "\n";
460 return $out if $format eq 'short';
462 if ($info->{description
} && $format eq 'full') {
463 my $desc = Text
::Wrap
::wrap
(' ', ' ', ($info->{description
}));
464 $out .= "\n$desc\n\n";
467 $out .= $argdescr if $argdescr;
469 $out .= $opts if $opts;
475 my ($self, $prefix, $name, $args, $arg_param, $fixed_param, $pwcallback) = @_;
477 my $info = $self->map_method_by_name($name);
481 my $param = PVE
::JSONSchema
::get_options
($info->{parameters
}, $args, $arg_param, $fixed_param, $pwcallback);
482 $res = $self->handle($info, $param);
487 die $err if !$ec || $ec ne "PVE::Exception" || !$err->is_param_exc();
489 $err->{usage
} = $self->usage_str($name, $prefix, $arg_param, $fixed_param, 'short', $pwcallback);
498 # note: this modifies the original hash by adding the id property
500 my ($hash, $idprop) = @_;
503 return $res if !$hash;
505 foreach my $k (keys %$hash) {
506 $hash->{$k}->{$idprop} = $k;
507 push @$res, $hash->{$k};