]> git.proxmox.com Git - pve-common.git/blame_incremental - data/PVE/JSONSchema.pm
update version to 1.0-7
[pve-common.git] / data / PVE / JSONSchema.pm
... / ...
CommitLineData
1package PVE::JSONSchema;
2
3use warnings;
4use strict;
5use Storable; # for dclone
6use Getopt::Long;
7use Devel::Cycle -quiet; # todo: remove?
8use PVE::Tools qw(split_list);
9use PVE::Exception qw(raise);
10use HTTP::Status qw(:constants);
11
12use base 'Exporter';
13
14our @EXPORT_OK = qw(
15register_standard_option
16get_standard_option
17);
18
19# Note: This class implements something similar to JSON schema, but it is not 100% complete.
20# see: http://tools.ietf.org/html/draft-zyp-json-schema-02
21# see: http://json-schema.org/
22
23# the code is similar to the javascript parser from http://code.google.com/p/jsonschema/
24
25my $standard_options = {};
26sub register_standard_option {
27 my ($name, $schema) = @_;
28
29 die "standard option '$name' already registered\n"
30 if $standard_options->{$name};
31
32 $standard_options->{$name} = $schema;
33}
34
35sub get_standard_option {
36 my ($name, $base) = @_;
37
38 my $std = $standard_options->{$name};
39 die "no such standard option\n" if !$std;
40
41 my $res = $base || {};
42
43 foreach my $opt (keys %$std) {
44 next if $res->{$opt};
45 $res->{$opt} = $std->{$opt};
46 }
47
48 return $res;
49};
50
51register_standard_option('pve-vmid', {
52 description => "The (unique) ID of the VM.",
53 type => 'integer', format => 'pve-vmid',
54 minimum => 1
55});
56
57register_standard_option('pve-node', {
58 description => "The cluster node name.",
59 type => 'string', format => 'pve-node',
60});
61
62register_standard_option('pve-node-list', {
63 description => "List of cluster node names.",
64 type => 'string', format => 'pve-node-list',
65});
66
67register_standard_option('pve-iface', {
68 description => "Network interface name.",
69 type => 'string', format => 'pve-iface',
70 minLength => 2, maxLength => 20,
71});
72
73my $format_list = {};
74
75sub register_format {
76 my ($format, $code) = @_;
77
78 die "JSON schema format '$format' already registered\n"
79 if $format_list->{$format};
80
81 $format_list->{$format} = $code;
82}
83
84# register some common type for pve
85
86register_format('string', sub {}); # allow format => 'string-list'
87
88register_format('pve-configid', \&pve_verify_configid);
89sub pve_verify_configid {
90 my ($id, $noerr) = @_;
91
92 if ($id !~ m/^[a-z][a-z0-9_]+$/i) {
93 return undef if $noerr;
94 die "invalid cofiguration ID '$id'\n";
95 }
96 return $id;
97}
98
99register_format('pve-vmid', \&pve_verify_vmid);
100sub pve_verify_vmid {
101 my ($vmid, $noerr) = @_;
102
103 if ($vmid !~ m/^[1-9][0-9]+$/) {
104 return undef if $noerr;
105 die "value does not look like a valid VM ID\n";
106 }
107 return $vmid;
108}
109
110register_format('pve-node', \&pve_verify_node_name);
111sub pve_verify_node_name {
112 my ($node, $noerr) = @_;
113
114 # todo: use better regex ?
115 if ($node !~ m/^[A-Za-z][[:alnum:]\-]*[[:alnum:]]+$/) {
116 return undef if $noerr;
117 die "value does not look like a valid node name\n";
118 }
119 return $node;
120}
121
122register_format('ipv4', \&pve_verify_ipv4);
123sub pve_verify_ipv4 {
124 my ($ipv4, $noerr) = @_;
125
126 if ($ipv4 !~ m/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/ ||
127 !(($1 > 0) && ($1 < 255) &&
128 ($2 <= 255) && ($3 <= 255) &&
129 ($4 > 0) && ($4 < 255))) {
130 return undef if $noerr;
131 die "value does not look like a valid IP address\n";
132 }
133 return $ipv4;
134}
135register_format('ipv4mask', \&pve_verify_ipv4mask);
136sub pve_verify_ipv4mask {
137 my ($mask, $noerr) = @_;
138
139 if ($mask !~ m/^255\.255\.(\d{1,3})\.(\d{1,3})$/ ||
140 !(($1 <= 255) && ($2 <= 255))) {
141 return undef if $noerr;
142 die "value does not look like a valid IP netmask\n";
143 }
144 return $mask;
145}
146
147register_format('email', \&pve_verify_email);
148sub pve_verify_email {
149 my ($email, $noerr) = @_;
150
151 # we use same regex as extjs Ext.form.VTypes.email
152 if ($email !~ /^(\w+)([\-+.][\w]+)*@(\w[\-\w]*\.){1,5}([A-Za-z]){2,6}$/) {
153 return undef if $noerr;
154 die "value does not look like a valid email address\n";
155 }
156 return $email;
157}
158
159# network interface name
160register_format('pve-iface', \&pve_verify_iface);
161sub pve_verify_iface {
162 my ($id, $noerr) = @_;
163
164 if ($id !~ m/^[a-z][a-z0-9_]{1,20}([:\.]\d+)?$/i) {
165 return undef if $noerr;
166 die "invalid network interface name '$id'\n";
167 }
168 return $id;
169}
170
171sub check_format {
172 my ($format, $value) = @_;
173
174 return if $format eq 'regex';
175
176 if ($format =~ m/^(.*)-a?list$/) {
177
178 my $code = $format_list->{$1};
179
180 die "undefined format '$format'\n" if !$code;
181
182 # Note: we allow empty lists
183 foreach my $v (split_list($value)) {
184 &$code($v);
185 }
186
187 } elsif ($format =~ m/^(.*)-opt$/) {
188
189 my $code = $format_list->{$1};
190
191 die "undefined format '$format'\n" if !$code;
192
193 return if !$value; # allow empty string
194
195 &$code($value);
196
197 } else {
198
199 my $code = $format_list->{$format};
200
201 die "undefined format '$format'\n" if !$code;
202
203 &$code($value);
204 }
205}
206
207sub add_error {
208 my ($errors, $path, $msg) = @_;
209
210 $path = '_root' if !$path;
211
212 if ($errors->{$path}) {
213 $errors->{$path} = join ('\n', $errors->{$path}, $msg);
214 } else {
215 $errors->{$path} = $msg;
216 }
217}
218
219sub is_number {
220 my $value = shift;
221
222 # see 'man perlretut'
223 return $value =~ /^[+-]?(\d+\.\d+|\d+\.|\.\d+|\d+)([eE][+-]?\d+)?$/;
224}
225
226sub is_integer {
227 my $value = shift;
228
229 return $value =~ m/^[+-]?\d+$/;
230}
231
232sub check_type {
233 my ($path, $type, $value, $errors) = @_;
234
235 return 1 if !$type;
236
237 if (!defined($value)) {
238 return 1 if $type eq 'null';
239 die "internal error"
240 }
241
242 if (my $tt = ref($type)) {
243 if ($tt eq 'ARRAY') {
244 foreach my $t (@$type) {
245 my $tmperr = {};
246 check_type($path, $t, $value, $tmperr);
247 return 1 if !scalar(%$tmperr);
248 }
249 my $ttext = join ('|', @$type);
250 add_error($errors, $path, "type check ('$ttext') failed");
251 return undef;
252 } elsif ($tt eq 'HASH') {
253 my $tmperr = {};
254 check_prop($value, $type, $path, $tmperr);
255 return 1 if !scalar(%$tmperr);
256 add_error($errors, $path, "type check failed");
257 return undef;
258 } else {
259 die "internal error - got reference type '$tt'";
260 }
261
262 } else {
263
264 return 1 if $type eq 'any';
265
266 if ($type eq 'null') {
267 if (defined($value)) {
268 add_error($errors, $path, "type check ('$type') failed - value is not null");
269 return undef;
270 }
271 return 1;
272 }
273
274 my $vt = ref($value);
275
276 if ($type eq 'array') {
277 if (!$vt || $vt ne 'ARRAY') {
278 add_error($errors, $path, "type check ('$type') failed");
279 return undef;
280 }
281 return 1;
282 } elsif ($type eq 'object') {
283 if (!$vt || $vt ne 'HASH') {
284 add_error($errors, $path, "type check ('$type') failed");
285 return undef;
286 }
287 return 1;
288 } elsif ($type eq 'coderef') {
289 if (!$vt || $vt ne 'CODE') {
290 add_error($errors, $path, "type check ('$type') failed");
291 return undef;
292 }
293 return 1;
294 } else {
295 if ($vt) {
296 add_error($errors, $path, "type check ('$type') failed - got $vt");
297 return undef;
298 } else {
299 if ($type eq 'string') {
300 return 1; # nothing to check ?
301 } elsif ($type eq 'boolean') {
302 #if ($value =~ m/^(1|true|yes|on)$/i) {
303 if ($value eq '1') {
304 return 1;
305 #} elsif ($value =~ m/^(0|false|no|off)$/i) {
306 } elsif ($value eq '0') {
307 return 0;
308 } else {
309 add_error($errors, $path, "type check ('$type') failed - got '$value'");
310 return undef;
311 }
312 } elsif ($type eq 'integer') {
313 if (!is_integer($value)) {
314 add_error($errors, $path, "type check ('$type') failed - got '$value'");
315 return undef;
316 }
317 return 1;
318 } elsif ($type eq 'number') {
319 if (!is_number($value)) {
320 add_error($errors, $path, "type check ('$type') failed - got '$value'");
321 return undef;
322 }
323 return 1;
324 } else {
325 return 1; # no need to verify unknown types
326 }
327 }
328 }
329 }
330
331 return undef;
332}
333
334sub check_object {
335 my ($path, $schema, $value, $additional_properties, $errors) = @_;
336
337 # print "Check Object " . Dumper($value) . "\nSchema: " . Dumper($schema);
338
339 my $st = ref($schema);
340 if (!$st || $st ne 'HASH') {
341 add_error($errors, $path, "Invalid schema definition.");
342 return;
343 }
344
345 my $vt = ref($value);
346 if (!$vt || $vt ne 'HASH') {
347 add_error($errors, $path, "an object is required");
348 return;
349 }
350
351 foreach my $k (keys %$schema) {
352 check_prop($value->{$k}, $schema->{$k}, $path ? "$path.$k" : $k, $errors);
353 }
354
355 foreach my $k (keys %$value) {
356
357 my $newpath = $path ? "$path.$k" : $k;
358
359 if (my $subschema = $schema->{$k}) {
360 if (my $requires = $subschema->{requires}) {
361 if (ref($requires)) {
362 #print "TEST: " . Dumper($value) . "\n", Dumper($requires) ;
363 check_prop($value, $requires, $path, $errors);
364 } elsif (!defined($value->{$requires})) {
365 add_error($errors, $path ? "$path.$requires" : $requires,
366 "missing property - '$newpath' requiers this property");
367 }
368 }
369
370 next; # value is already checked above
371 }
372
373 if (defined ($additional_properties) && !$additional_properties) {
374 add_error($errors, $newpath, "property is not defined in schema " .
375 "and the schema does not allow additional properties");
376 next;
377 }
378 check_prop($value->{$k}, $additional_properties, $newpath, $errors)
379 if ref($additional_properties);
380 }
381}
382
383sub check_prop {
384 my ($value, $schema, $path, $errors) = @_;
385
386 die "internal error - no schema" if !$schema;
387 die "internal error" if !$errors;
388
389 #print "check_prop $path\n" if $value;
390
391 my $st = ref($schema);
392 if (!$st || $st ne 'HASH') {
393 add_error($errors, $path, "Invalid schema definition.");
394 return;
395 }
396
397 # if it extends another schema, it must pass that schema as well
398 if($schema->{extends}) {
399 check_prop($value, $schema->{extends}, $path, $errors);
400 }
401
402 if (!defined ($value)) {
403 return if $schema->{type} && $schema->{type} eq 'null';
404 if (!$schema->{optional}) {
405 add_error($errors, $path, "property is missing and it is not optional");
406 }
407 return;
408 }
409
410 return if !check_type($path, $schema->{type}, $value, $errors);
411
412 if ($schema->{disallow}) {
413 my $tmperr = {};
414 if (check_type($path, $schema->{disallow}, $value, $tmperr)) {
415 add_error($errors, $path, "disallowed value was matched");
416 return;
417 }
418 }
419
420 if (my $vt = ref($value)) {
421
422 if ($vt eq 'ARRAY') {
423 if ($schema->{items}) {
424 my $it = ref($schema->{items});
425 if ($it && $it eq 'ARRAY') {
426 #die "implement me $path: $vt " . Dumper($schema) ."\n". Dumper($value);
427 die "not implemented";
428 } else {
429 my $ind = 0;
430 foreach my $el (@$value) {
431 check_prop($el, $schema->{items}, "${path}[$ind]", $errors);
432 $ind++;
433 }
434 }
435 }
436 return;
437 } elsif ($schema->{properties} || $schema->{additionalProperties}) {
438 check_object($path, defined($schema->{properties}) ? $schema->{properties} : {},
439 $value, $schema->{additionalProperties}, $errors);
440 return;
441 }
442
443 } else {
444
445 if (my $format = $schema->{format}) {
446 eval { check_format($format, $value); };
447 if ($@) {
448 add_error($errors, $path, "invalid format - $@");
449 return;
450 }
451 }
452
453 if (my $pattern = $schema->{pattern}) {
454 if ($value !~ m/^$pattern$/) {
455 add_error($errors, $path, "value does not match the regex pattern");
456 return;
457 }
458 }
459
460 if (defined (my $max = $schema->{maxLength})) {
461 if (length($value) > $max) {
462 add_error($errors, $path, "value may only be $max characters long");
463 return;
464 }
465 }
466
467 if (defined (my $min = $schema->{minLength})) {
468 if (length($value) < $min) {
469 add_error($errors, $path, "value must be at least $min characters long");
470 return;
471 }
472 }
473
474 if (is_number($value)) {
475 if (defined (my $max = $schema->{maximum})) {
476 if ($value > $max) {
477 add_error($errors, $path, "value must have a maximum value of $max");
478 return;
479 }
480 }
481
482 if (defined (my $min = $schema->{minimum})) {
483 if ($value < $min) {
484 add_error($errors, $path, "value must have a minimum value of $min");
485 return;
486 }
487 }
488 }
489
490 if (my $ea = $schema->{enum}) {
491
492 my $found;
493 foreach my $ev (@$ea) {
494 if ($ev eq $value) {
495 $found = 1;
496 last;
497 }
498 }
499 if (!$found) {
500 add_error($errors, $path, "value '$value' does not have a value in the enumeration '" .
501 join(", ", @$ea) . "'");
502 }
503 }
504 }
505}
506
507sub validate {
508 my ($instance, $schema, $errmsg) = @_;
509
510 my $errors = {};
511 $errmsg = "Parameter verification failed.\n" if !$errmsg;
512
513 # todo: cycle detection is only needed for debugging, I guess
514 # we can disable that in the final release
515 # todo: is there a better/faster way to detect cycles?
516 my $cycles = 0;
517 find_cycle($instance, sub { $cycles = 1 });
518 if ($cycles) {
519 add_error($errors, undef, "data structure contains recursive cycles");
520 } elsif ($schema) {
521 check_prop($instance, $schema, '', $errors);
522 }
523
524 if (scalar(%$errors)) {
525 raise $errmsg, code => HTTP_BAD_REQUEST, errors => $errors;
526 }
527
528 return 1;
529}
530
531my $schema_valid_types = ["string", "object", "coderef", "array", "boolean", "number", "integer", "null", "any"];
532my $default_schema_noref = {
533 description => "This is the JSON Schema for JSON Schemas.",
534 type => [ "object" ],
535 additionalProperties => 0,
536 properties => {
537 type => {
538 type => ["string", "array"],
539 description => "This is a type definition value. This can be a simple type, or a union type",
540 optional => 1,
541 default => "any",
542 items => {
543 type => "string",
544 enum => $schema_valid_types,
545 },
546 enum => $schema_valid_types,
547 },
548 optional => {
549 type => "boolean",
550 description => "This indicates that the instance property in the instance object is not required.",
551 optional => 1,
552 default => 0
553 },
554 properties => {
555 type => "object",
556 description => "This is a definition for the properties of an object value",
557 optional => 1,
558 default => {},
559 },
560 items => {
561 type => "object",
562 description => "When the value is an array, this indicates the schema to use to validate each item in an array",
563 optional => 1,
564 default => {},
565 },
566 additionalProperties => {
567 type => [ "boolean", "object"],
568 description => "This provides a default property definition for all properties that are not explicitly defined in an object type definition.",
569 optional => 1,
570 default => {},
571 },
572 minimum => {
573 type => "number",
574 optional => 1,
575 description => "This indicates the minimum value for the instance property when the type of the instance value is a number.",
576 },
577 maximum => {
578 type => "number",
579 optional => 1,
580 description => "This indicates the maximum value for the instance property when the type of the instance value is a number.",
581 },
582 minLength => {
583 type => "integer",
584 description => "When the instance value is a string, this indicates minimum length of the string",
585 optional => 1,
586 minimum => 0,
587 default => 0,
588 },
589 maxLength => {
590 type => "integer",
591 description => "When the instance value is a string, this indicates maximum length of the string.",
592 optional => 1,
593 },
594 typetext => {
595 type => "string",
596 optional => 1,
597 description => "A text representation of the type (used to generate documentation).",
598 },
599 pattern => {
600 type => "string",
601 format => "regex",
602 description => "When the instance value is a string, this provides a regular expression that a instance string value should match in order to be valid.",
603 optional => 1,
604 default => ".*",
605 },
606
607 enum => {
608 type => "array",
609 optional => 1,
610 description => "This provides an enumeration of possible values that are valid for the instance property.",
611 },
612 description => {
613 type => "string",
614 optional => 1,
615 description => "This provides a description of the purpose the instance property. The value can be a string or it can be an object with properties corresponding to various different instance languages (with an optional default property indicating the default description).",
616 },
617 title => {
618 type => "string",
619 optional => 1,
620 description => "This provides the title of the property",
621 },
622 requires => {
623 type => [ "string", "object" ],
624 optional => 1,
625 description => "indicates a required property or a schema that must be validated if this property is present",
626 },
627 format => {
628 type => "string",
629 optional => 1,
630 description => "This indicates what format the data is among some predefined formats which may include:\n\ndate - a string following the ISO format \naddress \nschema - a schema definition object \nperson \npage \nhtml - a string representing HTML",
631 },
632 default => {
633 type => "any",
634 optional => 1,
635 description => "This indicates the default for the instance property."
636 },
637 disallow => {
638 type => "object",
639 optional => 1,
640 description => "This attribute may take the same values as the \"type\" attribute, however if the instance matches the type or if this value is an array and the instance matches any type or schema in the array, than this instance is not valid.",
641 },
642 extends => {
643 type => "object",
644 optional => 1,
645 description => "This indicates the schema extends the given schema. All instances of this schema must be valid to by the extended schema also.",
646 default => {},
647 },
648 # this is from hyper schema
649 links => {
650 type => "array",
651 description => "This defines the link relations of the instance objects",
652 optional => 1,
653 items => {
654 type => "object",
655 properties => {
656 href => {
657 type => "string",
658 description => "This defines the target URL for the relation and can be parameterized using {propertyName} notation. It should be resolved as a URI-reference relative to the URI that was used to retrieve the instance document",
659 },
660 rel => {
661 type => "string",
662 description => "This is the name of the link relation",
663 optional => 1,
664 default => "full",
665 },
666 method => {
667 type => "string",
668 description => "For submission links, this defines the method that should be used to access the target resource",
669 optional => 1,
670 default => "GET",
671 },
672 },
673 },
674 },
675 }
676};
677
678my $default_schema = Storable::dclone($default_schema_noref);
679
680$default_schema->{properties}->{properties}->{additionalProperties} = $default_schema;
681$default_schema->{properties}->{additionalProperties}->{properties} = $default_schema->{properties};
682
683$default_schema->{properties}->{items}->{properties} = $default_schema->{properties};
684$default_schema->{properties}->{items}->{additionalProperties} = 0;
685
686$default_schema->{properties}->{disallow}->{properties} = $default_schema->{properties};
687$default_schema->{properties}->{disallow}->{additionalProperties} = 0;
688
689$default_schema->{properties}->{requires}->{properties} = $default_schema->{properties};
690$default_schema->{properties}->{requires}->{additionalProperties} = 0;
691
692$default_schema->{properties}->{extends}->{properties} = $default_schema->{properties};
693$default_schema->{properties}->{extends}->{additionalProperties} = 0;
694
695my $method_schema = {
696 type => "object",
697 additionalProperties => 0,
698 properties => {
699 description => {
700 description => "This a description of the method",
701 optional => 1,
702 },
703 name => {
704 type => 'string',
705 description => "This indicates the name of the function to call.",
706 optional => 1,
707 requires => {
708 additionalProperties => 1,
709 properties => {
710 name => {},
711 description => {},
712 code => {},
713 method => {},
714 parameters => {},
715 path => {},
716 parameters => {},
717 returns => {},
718 }
719 },
720 },
721 method => {
722 type => 'string',
723 description => "The HTTP method name.",
724 enum => [ 'GET', 'POST', 'PUT', 'DELETE' ],
725 optional => 1,
726 },
727 protected => {
728 type => 'boolean',
729 description => "Method needs special privileges - only pvedaemon can execute it",
730 optional => 1,
731 },
732 proxyto => {
733 type => 'string',
734 description => "A parameter name. If specified, all calls to this method are proxied to the host contained in that parameter.",
735 optional => 1,
736 },
737 permissions => {
738 type => 'object',
739 description => "Required access permissions. By default only 'root' is allowed to access this method.",
740 optional => 1,
741 additionalProperties => 0,
742 properties => {
743 user => {
744 description => "A simply way to allow access for 'all' users. The special value 'arg' allows access for the user specified in the 'username' parameter. This is useful to allow access to things owned by a user, like changing the user password. Value 'world' is used to allow access without credentials.",
745 type => 'string',
746 enum => ['all', 'arg', 'world'],
747 optional => 1,
748 },
749 path => { type => 'string', optional => 1, requires => 'privs' },
750 privs => { type => 'array', optional => 1, requires => 'path' },
751 },
752 },
753 match_name => {
754 description => "Used internally",
755 optional => 1,
756 },
757 match_re => {
758 description => "Used internally",
759 optional => 1,
760 },
761 path => {
762 type => 'string',
763 description => "path for URL matching (uri template)",
764 },
765 fragmentDelimiter => {
766 type => 'string',
767 description => "A ways to override the default fragment delimiter '/'. This onyl works on a whole sub-class. You can set this to the empty string to match the whole rest of the URI.",
768 optional => 1,
769 },
770 parameters => {
771 type => 'object',
772 description => "JSON Schema for parameters.",
773 optional => 1,
774 },
775 returns => {
776 type => 'object',
777 description => "JSON Schema for return value.",
778 optional => 1,
779 },
780 code => {
781 type => 'coderef',
782 description => "method implementaion (code reference)",
783 optional => 1,
784 },
785 subclass => {
786 type => 'string',
787 description => "Delegate call to this class (perl class string).",
788 optional => 1,
789 requires => {
790 additionalProperties => 0,
791 properties => {
792 subclass => {},
793 path => {},
794 match_name => {},
795 match_re => {},
796 fragmentDelimiter => { optional => 1 }
797 }
798 },
799 },
800 },
801
802};
803
804sub validate_schema {
805 my ($schema) = @_;
806
807 my $errmsg = "internal error - unable to verify schema\n";
808 validate($schema, $default_schema, $errmsg);
809}
810
811sub validate_method_info {
812 my $info = shift;
813
814 my $errmsg = "internal error - unable to verify method info\n";
815 validate($info, $method_schema, $errmsg);
816
817 validate_schema($info->{parameters}) if $info->{parameters};
818 validate_schema($info->{returns}) if $info->{returns};
819}
820
821# run a self test on load
822# make sure we can verify the default schema
823validate_schema($default_schema_noref);
824validate_schema($method_schema);
825
826# and now some utility methods (used by pve api)
827sub method_get_child_link {
828 my ($info) = @_;
829
830 return undef if !$info;
831
832 my $schema = $info->{returns};
833 return undef if !$schema || !$schema->{type} || $schema->{type} ne 'array';
834
835 my $links = $schema->{links};
836 return undef if !$links;
837
838 my $found;
839 foreach my $lnk (@$links) {
840 if ($lnk->{href} && $lnk->{rel} && ($lnk->{rel} eq 'child')) {
841 $found = $lnk;
842 last;
843 }
844 }
845
846 return $found;
847}
848
849# a way to parse command line parameters, using a
850# schema to configure Getopt::Long
851sub get_options {
852 my ($schema, $args, $uri_param, $pwcallback, $list_param) = @_;
853
854 if (!$schema || !$schema->{properties}) {
855 raise("too many arguments\n", code => HTTP_BAD_REQUEST)
856 if scalar(@$args) != 0;
857 return {};
858 }
859
860 my @getopt = ();
861 foreach my $prop (keys %{$schema->{properties}}) {
862 my $pd = $schema->{properties}->{$prop};
863 next if $list_param && $prop eq $list_param;
864 next if defined($uri_param->{$prop});
865
866 if ($prop eq 'password' && $pwcallback) {
867 # we do not accept plain password on input line, instead
868 # we turn this into a boolean option and ask for password below
869 # using $pwcallback() (for security reasons).
870 push @getopt, "$prop";
871 } elsif ($pd->{type} eq 'boolean') {
872 push @getopt, "$prop:s";
873 } else {
874 if ($pd->{format} && $pd->{format} =~ m/-a?list/) {
875 push @getopt, "$prop=s@";
876 } else {
877 push @getopt, "$prop=s";
878 }
879 }
880 }
881
882 my $opts = {};
883 raise("unable to parse option\n", code => HTTP_BAD_REQUEST)
884 if !Getopt::Long::GetOptionsFromArray($args, $opts, @getopt);
885
886 if ($list_param) {
887 my $pd = $schema->{properties}->{$list_param} ||
888 die "no schema for list_param";
889
890 $opts->{$list_param} = $args if scalar($args);
891 $args = [];
892 }
893
894 raise("too many arguments\n", code => HTTP_BAD_REQUEST)
895 if scalar(@$args) != 0;
896
897 if (my $pd = $schema->{properties}->{password}) {
898 if ($pd->{type} ne 'boolean' && $pwcallback) {
899 if ($opts->{password} || !$pd->{optional}) {
900 $opts->{password} = &$pwcallback();
901 }
902 }
903 }
904
905 foreach my $p (keys %$opts) {
906 if (my $pd = $schema->{properties}->{$p}) {
907 if ($pd->{type} eq 'boolean') {
908 if ($opts->{$p} eq '') {
909 $opts->{$p} = 1;
910 } elsif ($opts->{$p} =~ m/^(1|true|yes|on)$/i) {
911 $opts->{$p} = 1;
912 } elsif ($opts->{$p} =~ m/^(0|false|no|off)$/i) {
913 $opts->{$p} = 0;
914 } else {
915 raise("unable to parse boolean option\n", code => HTTP_BAD_REQUEST);
916 }
917 } elsif ($pd->{format}) {
918
919 if ($pd->{format} =~ m/-list/) {
920 # allow --vmid 100 --vmid 101 and --vmid 100,101
921 # allow --dow mon --dow fri and --dow mon,fri
922 $opts->{$p} = join(",", @{$opts->{$p}});
923 } elsif ($pd->{format} =~ m/-alist/) {
924 # we encode array as \0 separated strings
925 # Note: CGI.pm also use this encoding
926 if (scalar(@{$opts->{$p}}) != 1) {
927 $opts->{$p} = join("\0", @{$opts->{$p}});
928 } else {
929 # st that split_list knows it is \0 terminated
930 my $v = $opts->{$p}->[0];
931 $opts->{$p} = "$v\0";
932 }
933 }
934 }
935 }
936 }
937
938 foreach my $p (keys %$uri_param) {
939 $opts->{$p} = $uri_param->{$p};
940 }
941
942 return $opts;
943}
944
945# A way to parse configuration data by giving a json schema
946sub parse_config {
947 my ($schema, $filename, $raw) = @_;
948
949 # do fast check (avoid validate_schema($schema))
950 die "got strange schema" if !$schema->{type} ||
951 !$schema->{properties} || $schema->{type} ne 'object';
952
953 my $cfg = {};
954
955 while ($raw && $raw =~ s/^(.*?)(\n|$)//) {
956 my $line = $1;
957
958 next if $line =~ m/^\#/; # skip comment lines
959 next if $line =~ m/^\s*$/; # skip empty lines
960
961 if ($line =~ m/^(\S+):\s*(\S+)\s*$/) {
962 my $key = $1;
963 my $value = $2;
964 if ($schema->{properties}->{$key} &&
965 $schema->{properties}->{$key}->{type} eq 'boolean') {
966
967 $value = 1 if $value =~ m/^(1|on|yes|true)$/i;
968 $value = 0 if $value =~ m/^(0|off|no|false)$/i;
969 }
970 $cfg->{$key} = $value;
971 } else {
972 warn "ignore config line: $line\n"
973 }
974 }
975
976 my $errors = {};
977 check_prop($cfg, $schema, '', $errors);
978
979 foreach my $k (keys %$errors) {
980 warn "parse error in '$filename' - '$k': $errors->{$k}\n";
981 delete $cfg->{$k};
982 }
983
984 return $cfg;
985}
986
987# generate simple key/value file
988sub dump_config {
989 my ($schema, $filename, $cfg) = @_;
990
991 # do fast check (avoid validate_schema($schema))
992 die "got strange schema" if !$schema->{type} ||
993 !$schema->{properties} || $schema->{type} ne 'object';
994
995 validate($cfg, $schema, "validation error in '$filename'\n");
996
997 my $data = '';
998
999 foreach my $k (keys %$cfg) {
1000 $data .= "$k: $cfg->{$k}\n";
1001 }
1002
1003 return $data;
1004}
1005
10061;