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 = {};
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) ? 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) = @_;
163 if ($info->{subclass
}) {
164 $errprefix = "register subclass $info->{subclass} at ${self}/$info->{path} -";
165 $method = 'SUBCLASS';
167 $errprefix = "register method ${self}/$info->{path} -";
168 $info->{method} = 'GET' if !$info->{method};
169 $method = $info->{method};
172 $method_path_lookup->{$self} = {} if !defined($method_path_lookup->{$self});
173 my $path_lookup = $method_path_lookup->{$self};
175 die "$errprefix no path" if !defined($info->{path
});
177 foreach my $comp (split(/\/+/, $info->{path
})) {
178 die "$errprefix path compoment has zero length\n" if $comp eq '';
180 if ($comp =~ m/^\{(\w+)(:(.*))?\}$/) {
182 $regex = $3 ?
$3 : '\S+';
183 push @$match_re, $regex;
184 push @$match_name, $name;
187 push @$match_re, $name;
188 push @$match_name, undef;
192 $path_lookup->{regex
} = {} if !defined($path_lookup->{regex
});
194 my $old_name = $path_lookup->{regex
}->{match_name
};
195 die "$errprefix found changed regex match name\n"
196 if defined($old_name) && ($old_name ne $name);
197 my $old_re = $path_lookup->{regex
}->{match_re
};
198 die "$errprefix found changed regex\n"
199 if defined($old_re) && ($old_re ne $regex);
200 $path_lookup->{regex
}->{match_name
} = $name;
201 $path_lookup->{regex
}->{match_re
} = $regex;
203 die "$errprefix path match error - regex and fixed items\n"
204 if defined($path_lookup->{folders
});
206 $path_lookup = $path_lookup->{regex
};
209 $path_lookup->{folders
}->{$name} = {} if !defined($path_lookup->{folders
}->{$name});
211 die "$errprefix path match error - regex and fixed items\n"
212 if defined($path_lookup->{regex
});
214 $path_lookup = $path_lookup->{folders
}->{$name};
218 die "$errprefix duplicate method definition\n"
219 if defined($path_lookup->{$method});
221 $path_lookup->{$method} = $info;
223 $info->{match_re
} = $match_re;
224 $info->{match_name
} = $match_name;
226 $method_by_name->{$self} = {} if !defined($method_by_name->{$self});
229 die "$errprefix method name already defined\n"
230 if defined($method_by_name->{$self}->{$info->{name
}});
232 $method_by_name->{$self}->{$info->{name
}} = $info;
235 push @{$method_registry->{$self}}, $info;
241 # also see "man perldiag"
244 (my $method = $sub) =~ s/.*:://;
248 my $info = $this->map_method_by_name($method);
252 return $self->handle($info, @_);
257 sub method_attributes
{
260 return $method_registry->{$self};
263 sub map_method_by_name
{
264 my ($self, $name) = @_;
266 my $info = $method_by_name->{$self}->{$name};
267 die "no such method '${self}::$name'\n" if !$info;
272 sub map_path_to_methods
{
273 my ($class, $stack, $uri_param) = @_;
275 my $path_lookup = $method_path_lookup->{$class};
277 while (defined(my $comp = shift @$stack)) {
278 return undef if !$path_lookup; # not registerd?
279 if ($path_lookup->{regex
}) {
280 my $name = $path_lookup->{regex
}->{match_name
};
281 my $regex = $path_lookup->{regex
}->{match_re
};
283 return undef if $comp !~ m/^($regex)$/;
284 $uri_param->{$name} = $1;
285 $path_lookup = $path_lookup->{regex
};
286 } elsif ($path_lookup->{folders
}) {
287 $path_lookup = $path_lookup->{folders
}->{$comp};
289 die "internal error";
292 return undef if !$path_lookup;
294 if (my $info = $path_lookup->{SUBCLASS
}) {
295 $class = $info->{subclass
};
297 my $fd = $info->{fragmentDelimiter
};
300 # we only support the empty string '' (match whole URI)
301 die "unsupported fragmentDelimiter '$fd'"
304 $stack = [ join ('/', @$stack) ] if scalar(@$stack) > 1;
306 $path_lookup = $method_path_lookup->{$class};
310 return undef if !$path_lookup;
312 return ($class, $path_lookup);
316 my ($class, $method, $path, $uri_param) = @_;
318 my $stack = [ grep { length($_) > 0 } split('\/+' , $path)]; # skip empty fragments
320 my ($handler_class, $path_info);
322 ($handler_class, $path_info) = $class->map_path_to_methods($stack, $uri_param);
325 syslog
('err', $err) if $err;
327 return undef if !($handler_class && $path_info);
329 my $method_info = $path_info->{$method};
331 return undef if !$method_info;
333 return ($handler_class, $method_info);
337 my ($self, $info, $param) = @_;
339 my $func = $info->{code
};
341 if (!($info->{name
} && $func)) {
342 raise
("Method lookup failed ('$info->{name}')\n",
343 code
=> HTTP_INTERNAL_SERVER_ERROR
);
346 if (my $schema = $info->{parameters
}) {
347 # warn "validate ". Dumper($param}) . "\n" . Dumper($schema);
348 PVE
::JSONSchema
::validate
($param, $schema);
349 # untaint data (already validated)
350 while (my ($key, $val) = each %$param) {
351 ($param->{$key}) = $val =~ /^(.*)$/s;
355 my $result = &$func($param);
357 # todo: this is only to be safe - disable?
358 if (my $schema = $info->{returns
}) {
359 PVE
::JSONSchema
::validate
($result, $schema, "Result verification vailed\n");
365 # generate usage information for command line tools
367 # $name ... the name of the method
368 # $prefix ... usually something like "$exename $cmd" ('pvesm add')
369 # $arg_param ... list of parameters we want to get as ordered arguments
370 # on the command line (or single parameter name for lists)
371 # $fixed_param ... do not generate and info about those parameters
373 # 'long' ... default (list all options)
374 # 'short' ... command line only (one line)
375 # 'full' ... also include description
376 # $hidepw ... hide password option (use this if you provide a read passwork callback)
378 my ($self, $name, $prefix, $arg_param, $fixed_param, $format, $hidepw) = @_;
380 $format = 'long' if !$format;
382 my $info = $self->map_method_by_name($name);
383 my $schema = $info->{parameters
};
384 my $prop = $schema->{properties
};
392 $arg_param = [ $arg_param ] if $arg_param && !ref($arg_param);
394 foreach my $p (@$arg_param) {
395 next if !$prop->{$p}; # just to be sure
396 my $pd = $prop->{$p};
399 $args .= " " if $args;
400 if ($pd->{format
} && $pd->{format
} =~ m/-list/) {
403 $args .= $pd->{optional
} ?
"[<$p>]" : "<$p>";
407 my $get_prop_descr = sub {
408 my ($k, $display_name) = @_;
410 my $phash = $prop->{$k};
414 my $descr = $phash->{description
} || "no description available";
417 my $type = PVE
::PodParser
::schema_get_type_text
($phash);
419 if ($hidepw && $k eq 'password') {
424 if (defined(my $dv = $phash->{default})) {
425 $defaulttxt = " (default=$dv)";
427 my $tmp = sprintf " %-10s %s$defaulttxt\n", $display_name, "$type";
430 $res .= Text
::Wrap
::wrap
('', $indend, ($tmp));
432 $res .= Text
::Wrap
::wrap
($indend, $indend, ($descr)) . "\n\n";
434 if (my $req = $phash->{requires
}) {
435 my $tmp = "Requires option(s): ";
436 $tmp .= ref($req) ?
join(', ', @$req) : $req;
437 $res .= Text
::Wrap
::wrap
($indend, $indend, ($tmp)). "\n\n";
444 foreach my $k (@$arg_param) {
445 next if defined($fixed_param->{$k}); # just to be sure
446 next if !$prop->{$k}; # just to be sure
447 $argdescr .= &$get_prop_descr($k, "<$k>");
450 my $idx_param = {}; # -vlan\d+ -scsi\d+
453 foreach my $k (sort keys %$prop) {
454 next if $arg_hash->{$k};
455 next if defined($fixed_param->{$k});
457 my $type = $prop->{$k}->{type
} || 'string';
459 next if $hidepw && ($k eq 'password') && !$prop->{$k}->{optional
};
462 if ($k =~ m/^([a-z]+)(\d+)$/) {
464 next if $idx_param->{$name};
465 $idx_param->{$name} = 1;
466 $base = "${name}[n]";
469 $opts .= &$get_prop_descr($k, "-$base");
471 if (!$prop->{$k}->{optional
}) {
472 $args .= " " if $args;
473 $args .= "-$base <$type>"
477 $out .= "USAGE: " if $format ne 'short';
479 $out .= "$prefix $args";
481 $out .= $opts ?
" [OPTIONS]\n" : "\n";
483 return $out if $format eq 'short';
485 if ($info->{description
} && $format eq 'full') {
486 my $desc = Text
::Wrap
::wrap
(' ', ' ', ($info->{description
}));
487 $out .= "\n$desc\n\n";
490 $out .= $argdescr if $argdescr;
492 $out .= $opts if $opts;
498 my ($self, $prefix, $name, $args, $arg_param, $fixed_param, $pwcallback) = @_;
500 my $info = $self->map_method_by_name($name);
504 my $param = PVE
::JSONSchema
::get_options
($info->{parameters
}, $args, $arg_param, $fixed_param, $pwcallback);
505 $res = $self->handle($info, $param);
510 die $err if !$ec || $ec ne "PVE::Exception" || !$err->is_param_exc();
512 $err->{usage
} = $self->usage_str($name, $prefix, $arg_param, $fixed_param, 'short', $pwcallback);
521 # note: this modifies the original hash by adding the id property
523 my ($hash, $idprop) = @_;
526 return $res if !$hash;
528 foreach my $k (keys %$hash) {
529 $hash->{$k}->{$idprop} = $k;
530 push @$res, $hash->{$k};