editnodetype.in 18.9 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2000-2017 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
23 24 25 26 27 28
#
use English;
use strict;
use Getopt::Std;
use XML::Simple;
use Data::Dumper;
29
use Cwd qw(realpath);
30 31 32 33 34 35

#
# Back-end script to create or edit a nodetype.
#
sub usage()
{
36
    print("Usage: editnodetype [-v] [-p] <xmlfile>\n");
37 38
    exit(-1);
}
39 40 41 42
my $optlist  = "dvp";
my $restrict = 0;
my $debug    = 0;
my $verify   = 0;	# Check data and return status only. 
43 44 45 46 47 48 49

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
my $TBAUDIT	= "@TBAUDITEMAIL@";
50
my $UPDATEPERMS = "$TB/sbin/update_permissions";
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

#
# Untaint the path
#
$ENV{'PATH'} = "$TB/bin:$TB/sbin:/bin:/usr/bin:/usr/bin:/usr/sbin";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Turn off line buffering on output
#
$| = 1;

#
# Load the Testbed support stuff.
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
use User;
use Project;

# Protos
sub fatal($);
sub UserError(;$);
sub escapeshellarg($);

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
if (defined($options{"v"})) {
    $verify = 1;
}
91 92 93
if (defined($options{"p"})) {
    $restrict = 1;
}
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
if (@ARGV != 1) {
    usage();
}
my $xmlfile  = shift(@ARGV);

#
# Map invoking user to object. 
# If invoked as "nobody" we are coming from the web interface and the
# current user context is "implied" (see tbauth.php3).
#
my $this_user;

if (getpwuid($UID) ne "nobody") {
    $this_user = User->ThisUser();

    if (! defined($this_user)) {
	fatal("You ($UID) do not exist!");
    }
    fatal("You must have admin privledges to ...")
	if (!$this_user->IsAdmin());
}
else {
    #
    # Check the filename when invoked from the web interface; must be a
    # file in /tmp.
    #
    if ($xmlfile =~ /^([-\w\.\/]+)$/) {
	$xmlfile = $1;
    }
    else {
	fatal("Bad data in pathname: $xmlfile");
    }

    # Use realpath to resolve any symlinks.
128
    my $translated = realpath($xmlfile);
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
    if ($translated =~ /^(\/tmp\/[-\w\.\/]+)$/) {
	$xmlfile = $1;
    }
    else {
	fatal("Bad data in translated pathname: $xmlfile");
    }

    # The web interface (and in the future the xmlrpc interface) sets this.
    $this_user = User->ImpliedUser();

    if (! defined($this_user)) {
	fatal("Cannot determine implied user!");
    }
}

#
# These are the fields that we allow to come in from the XMLfile.
#
my $SLOT_OPTIONAL	= 0x1;	# The field is not required.
my $SLOT_REQUIRED	= 0x2;  # The field is required and must be non-null.
my $SLOT_ADMINONLY	= 0x4;  # Only admins can set this field.
#
# XXX We should encode all of this in the DB so that we can generate the
# forms on the fly, as well as this checking code.
#
my %xmlfields =
    # XML Field Name        DB slot name         Flags             Default
    ("node_type"	=> ["node_type",	$SLOT_REQUIRED],

     # Presence of new_type commands creation of a new nodetype.
     "new_type"		=> ["attr_boolean",	$SLOT_OPTIONAL],

     # Class may only be changed while making a new class. 
     "class"		=> ["class",		$SLOT_OPTIONAL],
163 164
     
     "architecture"	=> ["architecture",	$SLOT_OPTIONAL],
165 166

     # Fixed attributes.
167 168 169 170 171 172 173
     "isvirtnode"	=> ["isvirtnode",	$SLOT_OPTIONAL],
     "isjailed"		=> ["isjailed",		$SLOT_OPTIONAL],
     "isdynamic"	=> ["isdynamic",	$SLOT_OPTIONAL],
     "isremotenode"	=> ["isremotenode",	$SLOT_OPTIONAL],
     "issubnode"	=> ["issubnode",	$SLOT_OPTIONAL],
     "isplabdslice"	=> ["isplabdslice",	$SLOT_OPTIONAL],
     "issimnode"	=> ["issimnode",	$SLOT_OPTIONAL],
174 175
     "isgeninode"	=> ["isgeninode",	$SLOT_OPTIONAL],
     "isfednode"	=> ["isfednode",	$SLOT_OPTIONAL],
176
     "isswitch"		=> ["isswitch",		$SLOT_OPTIONAL],
177 178 179

     # Dynamic attributes with wildcards.
     "attr_boolean_*"	=> ["attr_boolean",	$SLOT_OPTIONAL],
180
     "attr_integer_*"	=> ["attr_integer",	$SLOT_OPTIONAL],
181 182 183
     "attr_float_*"	=> ["attr_float",	$SLOT_OPTIONAL],
     "attr_string_*"	=> ["attr_string",	$SLOT_OPTIONAL],

184 185 186
     # OS and Image ID's, referenced by their integer index.
     "attr_integer_*_osid"   => ["attr_osid",	$SLOT_OPTIONAL],
     "attr_integer_*_imageid"=> ["attr_imageid",$SLOT_OPTIONAL],
187

188 189 190 191
     # OS and Image ID's, referenced by their pid,name 
     "attr_string_*_osid"   => ["attr_string",	$SLOT_OPTIONAL],
     "attr_string_*_imageid"=> ["attr_string", $SLOT_OPTIONAL],

192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
     # The name of a single attribute to add to the list.
     "new_attr"		=> ["attr_name",	$SLOT_OPTIONAL],
     # Multiple attributes can be deleted from the list.
     "delete_*"		=> ["attr_boolean",	$SLOT_OPTIONAL]);

#
# Must wrap the parser in eval since it exits on error.
#
my $xmlparse = eval { XMLin($xmlfile,
			    VarAttr => 'name',
			    ContentKey => '-content',
			    SuppressEmpty => undef); };
fatal($@)
    if ($@);

#
# Process and dump the errors (formatted for the web interface).
# We should probably XML format the errors instead but not sure I want
# to go there yet.
#
my %errors = ();

#
# Make sure all the required arguments were provided.
#
my $key;
foreach $key (keys(%xmlfields)) {
    my (undef, $required, undef) = @{$xmlfields{$key}};

    $errors{$key} = "Required value not provided"
	if ($required & $SLOT_REQUIRED  &&
	    ! exists($xmlparse->{'attribute'}->{"$key"}));
}
UserError()
    if (keys(%errors));

#
Russ Fish's avatar
Russ Fish committed
229
# We build up an array of arguments to reference as we check
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
# the attributes.
#
my %editnodetype_args = ();

#
# Wildcard keys have one or more *'s in them like simple glob patterns.
# This allows multiple key instances for categories of attributes, and
# putting a "type signature" in the key for arg checking, as well.
#
# Wildcards are made into regex's by anchoring the ends and changing each * to
# a "word" (group of alphahumeric.)  A tail * means "the rest", allowing
# multiple words separated by underscores or dashes.
#
my $wordpat = '[a-zA-Z0-9]+';
my $tailpat = '[-\w]+';
my %wildcards;
foreach $key (keys(%xmlfields)) {
    if (index($key, "*") >= 0) {
	my $regex = '^' . $key . '$';
	$regex =~ s/\*\$$/$tailpat/;
	$regex =~ s/\*/$wordpat/g;
	$wildcards{$key} = $regex;
    }
}
# Key ordering is lost in a hash.
# Put longer matching wildcard keys before their prefix.
my @wildkeys = reverse(sort(keys(%wildcards)));

foreach $key (keys(%{ $xmlparse->{'attribute'} })) {
    my $value = $xmlparse->{'attribute'}->{"$key"}->{'value'};
260 261 262
    if (!defined($value)) {	# Empty string comes from XML as an undef value.
	$xmlparse->{'attribute'}->{"$key"}->{'value'} = $value = "";
    }
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311

    print STDERR "User attribute: '$key' -> '$value'\n"
	if ($debug);

    my $field = $key;
    my $wild;
    if (!exists($xmlfields{$key})) {

	# Not a regular key; look for a wildcard regex match.
        foreach my $wildkey (@wildkeys) {
	    my $regex = $wildcards{$wildkey};
	    if ($wild = $key =~ /$regex/) {
		$field = $wildkey;
		print STDERR "Wildcard: '$key' matches '$wildkey'\n"
		    if ($debug);
		last; # foreach $wildkey
	    }
	}
	if (!$wild) {
	    $errors{$key} = "Unknown attribute";
	    next; # foreach $key
	}
    }

    my ($dbslot, $required, $default) = @{$xmlfields{$field}};

    if ($required & $SLOT_REQUIRED) {
	# A slot that must be provided, so do not allow a null value.
	if (!defined($value)) {
	    $errors{$key} = "Must provide a non-null value";
	    next;
	}
    }
    if ($required & $SLOT_OPTIONAL) {
	# Optional slot. If value is null skip it. Might not be the correct
	# thing to do all the time?
	if (!defined($value)) {
	    next
		if (!defined($default));
	    $value = $default;
	}
    }
    if ($required & $SLOT_ADMINONLY) {
	# Admin implies optional, but thats probably not correct approach.
	$errors{$key} = "Administrators only"
	    if (! $this_user->IsAdmin());
    }
	
    # Now check that the value is legal.
312 313
    if (! TBcheck_dbslot($value, "node_types",
			 $dbslot, TBDB_CHECKDBSLOT_ERROR)) {
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
	$errors{$key} = TBFieldErrorString();
	next;
    }

    $editnodetype_args{$key} = $value;
}
UserError()
    if (keys(%errors));

#
# Now do special checks.
#
my $query_result;
my $node_type = $editnodetype_args{'node_type'};
my $new_type = exists($editnodetype_args{"new_type"});

#
# Check whether the node type already exists.
#
$query_result =
    DBQueryFatal("select * from node_types where type='$node_type'");
my $node_type_exists = $query_result->numrows;
my $prev_nodetype_data;
if ($new_type) {

    # Found.  But it's supposed to be new.
    UserError("New NodeType: $node_type is already used!")
	if ($node_type_exists);
}
else {
    # Not found, but it was supposed to be old.
    UserError("NodeType: $node_type is not a valid nodetype!")
	if (!$node_type_exists);

    # Found an existing one, grab its data.
    $prev_nodetype_data = $query_result->fetchrow_hashref();
}

#
# Check attributes of the node type, building an insert list as we go.
#
my @nodetype_data;

# First check fixed (non-attr*) attributes that are in the node_types table.
# Class may only be set while making a new nodetype.
my $class;
if (exists($editnodetype_args{"class"})) {
    my $newclass = $editnodetype_args{"class"};
    if ($new_type) {
	$class = $newclass;
	if ($class eq "") {
	    $class = "pc";	# Default to pc class.
	}
	push(@nodetype_data, "class='$class'");
    }
    else {
	$class = $prev_nodetype_data->{"class"};

	# It's okay to specify it to be the same as it was before.
	UserError("NodeType: Can't change class ($class) of existing node.")
	    if ($class ne $newclass);
    }
}

378 379 380
if (exists($editnodetype_args{"architecture"})) {
    my $architecture = $editnodetype_args{"architecture"};
    
381 382 383 384 385 386
    if ($architecture eq "") {
	push(@nodetype_data, "architecture=NULL");
    }
    else {
	push(@nodetype_data, "architecture='$architecture'");
    }
387 388
}

389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
# The rest of them all have names starting with "is" at present.
my @fixed_args   = grep(/^is/, keys(%editnodetype_args));
foreach my $name (@fixed_args) {
    if (exists($editnodetype_args{$name})) {
	my $value = $editnodetype_args{$name};
	push(@nodetype_data, "$name='$value'");
    }
}
# Needed below.
my $isremotenode = exists($editnodetype_args{"isremotenode"}) ?
    $editnodetype_args{"isremotenode"} : 
    $prev_nodetype_data->{"isremotenode"};

# Get previous dynamic attrs from the node_type_attributes table.
$query_result =
    DBQueryFatal("select * from node_type_attributes ".
		 "where type='$node_type'");
my $prev_attrs = $query_result->fetchall_hashref("attrkey");

# Dynamic attributes to be changed or deleted.  Possibly one new one added.
my $new_attr_name = "";
if (my $new_attr = exists($editnodetype_args{'new_attr'})) {
    $new_attr_name = $editnodetype_args{'new_attr'};

    # The new attr must not already exist.
    UserError("New NodeType Attr: $new_attr_name is already used!")
	if (exists($prev_attrs->{$new_attr_name}));
}

418 419 420 421 422 423
my %osids     = ();
my %mfsosids  = ();
my %osidmap   = ();
my %imageids  = ();
my %imagemap  = ();

424 425
# Get lists of ids for checking the special "attr_*_*id" attributes.
$query_result =
Leigh Stoller's avatar
Leigh Stoller committed
426 427
    DBQueryFatal("select o.osid,o.osname,o.pid from os_info as o ".
		 "left join os_info_versions as v on ".
Leigh Stoller's avatar
Leigh Stoller committed
428
		 "     v.osid=o.osid and v.vers=o.version ".
Leigh Stoller's avatar
Leigh Stoller committed
429 430
		 "where (v.path='' or v.path is NULL) ".
		 "order by o.pid,o.osname");
431 432 433 434 435
while (my ($osid,$osname,$pid) = $query_result->fetchrow_array()) {
    $osids{$osid} = "$pid,$osname";
    $osidmap{"$pid,$osname"} = $osid;
}
    
436
$query_result =
Leigh Stoller's avatar
Leigh Stoller committed
437 438
    DBQueryFatal("select o.osid,o.osname,o.pid from os_info as o ".
		 "left join os_info_versions as v on ".
Leigh Stoller's avatar
Leigh Stoller committed
439
		 "     v.osid=o.osid and v.vers=o.version ".
Leigh Stoller's avatar
Leigh Stoller committed
440 441
		 "where (v.path is not NULL and v.path!='') ".
		 "order by o.pid,o.osname");
442 443 444 445 446
while (my ($osid,$osname,$pid) = $query_result->fetchrow_array()) {
    $mfsosids{$osid} = "$pid,$osname";
    $osidmap{"$pid,$osname"} = $osid;
}

447 448 449
$query_result =
    DBQueryFatal("select imageid,imagename,pid from images ".
		 "order by pid,imagename");
450 451 452 453
while (my ($imageid,$imagename,$pid) = $query_result->fetchrow_array()) {
    $imageids{$imageid} = "$pid,$imagename";
    $imagemap{"$pid,$imagename"} = $imageid;
}
454 455 456 457 458 459 460 461 462 463

# Separate out the attr types and names from the other argument keys.
my ($attr_name, $attr_type, $attr_value);
my (@attr_names, %attr_types, %attr_values, %attr_dels);
foreach my $argkey (keys(%editnodetype_args)) {
    next
	if (!($argkey =~ /^attr_/));

    $attr_name = $attr_type = $argkey;
    $attr_name =~ s/^attr_${wordpat}_(.*)$/$1/;
464 465 466 467 468
    if ($argkey =~ /_default_imageid$/) {
	# hack, now a comma seperated list, assume valid
	$attr_type = "imageids";
    } 
    elsif ($argkey =~ /_(osid|imageid)$/) {
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
	# Special case: the type is the LAST part of the name for ID attrs.
	$attr_type = $1;
    }
    else {
	# Normal ones are like "attr_type_name".
	$attr_type =~ s/^attr_($wordpat)_.*$/$1/;
    }
    $attr_value = $editnodetype_args{$argkey};

    if ($debug) {
	print STDERR "Dynamic attr: $attr_name($attr_type) = '$attr_value'\n";
    }

    push(@attr_names, $attr_name);
    $attr_types{$attr_name} = $attr_type;
    $attr_values{$attr_name} = $attr_value;
}

# Check all of the dynamic attrs that are to be set.
foreach $attr_name (@attr_names) {
    
    # Skip checks on attrs that are scheduled for deletion anyway.
    my $del = $attr_dels{$attr_name} = 
	exists($editnodetype_args{"delete_${attr_name}"}) &&
	    $editnodetype_args{"delete_${attr_name}"} eq "1";
    next
	if $del;

    $attr_type = $attr_types{$attr_name};
    $attr_value = $attr_values{$attr_name};

    # Check the osid and imageid attribute values against the id lists.
    # Under the web page interface, these come to us from selectors.
    if ($attr_type eq "osid") {
503 504 505 506 507 508 509 510 511 512 513 514 515 516
	if ($attr_value =~ /^([^,]+),([^,]+)$/) {
	    if (!exists($osidmap{"$1,$2"})) {
		UserError("NodeType OSID Attr: $attr_name is not an osid.")
	    }
	    my $new_attr_value = $osidmap{"$1,$2"};
	    print STDERR "Mapping $attr_name: $attr_value -> $new_attr_value\n"
		if ($debug);
	    
	    $attr_value = $new_attr_value;
	    $attr_values{$attr_name} = $attr_value;
	}
	elsif (! ($attr_value =~ /^(\d*)$/)) {
	    UserError("Invalid osid value for $attr_name");
	}
517
	if ($attr_name =~ /mfs/) {
518
	    UserError("NodeType MFS OSID Attr: $attr_name is not an mfs_osid.")
519
		if (!exists($mfsosids{$attr_value}));
520 521 522
	}
	else {
	    UserError("NodeType OSID Attr: $attr_name is not an osid.")
523
		if (!exists($osids{$attr_value}));
524
	}
525
	$attr_types{$attr_name} = "integer"; # An idx is an integer attr.
526 527
    }
    elsif ($attr_type eq "imageid") {
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
	if ($attr_value =~ /^([^,]+),([^,]+)$/) {
	    if (!exists($imagemap{"$1,$2"})) {
		UserError("NodeType Image ID Attr: $attr_name is not an imageid.")
	    }
	    my $new_attr_value = $imagemap{"$1,$2"};
	    print STDERR "Mapping $attr_name: $attr_value -> $new_attr_value\n"
		if ($debug);

	    $attr_value = $new_attr_value;
	    $attr_values{$attr_name} = $attr_value;
	}
	elsif (! ($attr_value =~ /^(\d*)$/)) {
	    UserError("Invalid image id value for $attr_name");
	}
	
543
	UserError("NodeType Image ID Attr: $attr_name is not an imageid.")
544
	    if (!exists($imageids{$attr_value}));
545
	$attr_types{$attr_name} = "integer"; # An idx is an integer attr.
546
    }
547
    elsif ($attr_type eq "imageids") {
548 549
	my @newvals = ();
	    
550
	foreach my $k (split /,/, $attr_value) {
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
	    if ($k =~ /^([^:]+):([^:]+)$/) {
		if (!exists($imagemap{"$1,$2"})) {
		    UserError("NodeType Image ID Attr: $attr_name is not an imageid.")
		}
		my $new_k = $imagemap{"$1,$2"};
		print STDERR "Mapping $attr_name: $attr_value -> $new_k\n"
		    if ($debug);
		$k = $new_k;
	    }
	    elsif (! ($k =~ /^(\d*)$/)) {
		UserError("Invalid image id value for $attr_name");
	    }
	    push(@newvals, $k);
	    
	    UserError("NodeType Image ID Attr: ".
		      "$attr_name contains an invalid imageid.")
		if (!exists($imageids{$k}));
568
	}
569
	$attr_values{$attr_name} = join(",", @newvals);
570 571
	$attr_types{$attr_name} = "string"; # really a comma seperated list
    }
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
}

exit(0)
    if ($verify);

#
# Now safe to put the nodetype info into the DB.
#
my ($type, $value);
if ($new_type) {
    DBQueryFatal("insert into node_types set type='$node_type', ".
		 join(",", @nodetype_data));

    if ($class eq "pc" || $isremotenode eq "1") {
	my $vnode_type = $node_type;
	$vnode_type =~ s/pc/pcvm/;
	if ($vnode_type eq $node_type) {
	    $vnode_type = "$vnode_type-vm";
	}
	my $pcvmtype = ($isremotenode eq "1" ? "pcvwa" : "pcvm");

	DBQueryFatal("insert into node_types_auxtypes set " .
		     "  auxtype='$vnode_type', type='$pcvmtype'");
    }

    foreach $attr_name (@attr_names) {
	# Skip adding an attr if it is also scheduled for deletion.
	next
	    if ($attr_dels{$attr_name});

	$key   = escapeshellarg($attr_name);
	$type  = escapeshellarg($attr_types{$attr_name});
	$value = escapeshellarg($attr_values{$attr_name});

	DBQueryFatal("insert into node_type_attributes set ".
		     "   type='$node_type', ".
		     "   attrkey='$key', attrtype='$type', ".
		     "   attrvalue='$value' ");
    }
Leigh Stoller's avatar
Leigh Stoller committed
611

612 613 614 615 616 617 618 619 620 621 622
    if ($restrict) {
	# And a group policy that prevents new type from being used.
	DBQueryFatal("replace into group_policies ".
		     "(pid_idx, gid_idx, pid, gid, policy, auxdata, count) ".
		     "values (0, 0, '-', '-', 'type', '$node_type', 0)");

        #
        # Now update the permissions table. 
        #
	system($UPDATEPERMS);
    }
623 624 625 626
}
else {
    DBQueryFatal("update node_types set ".
		 join(",", @nodetype_data) . " ".
Leigh Stoller's avatar
Leigh Stoller committed
627 628
		 "where type='$node_type'")
	if (@nodetype_data);
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684

    foreach $attr_name (@attr_names) {
	$key   = escapeshellarg($attr_name);
	$type  = escapeshellarg($attr_types{$attr_name});
	$value = escapeshellarg($attr_values{$attr_name});

	# Remove an attr from the DB if scheduled for deletion.
	if ($attr_dels{$attr_name}) {
	    DBQueryFatal("delete from node_type_attributes ".
			 "where type='$node_type' and attrkey='$key'");
	}
	else {
	    DBQueryFatal("replace into node_type_attributes set ".
			 "   type='$node_type', ".
			 "   attrkey='$key', attrtype='$type', ".
			 "   attrvalue='$value' ");
	}
    }
}

exit(0);

sub fatal($)
{
    my ($mesg) = @_;

    print STDERR "*** $0:\n".
	         "    $mesg\n";
    # Exit with negative status so web interface treats it as system error.
    exit(-1);
}

sub UserError(;$)
{
    my ($mesg) = @_;

    if (keys(%errors)) {
	foreach my $key (keys(%errors)) {
	    my $val = $errors{$key};
	    print "${key}: $val\n";
	}
    }
    print "$mesg\n"
	if (defined($mesg));

    # Exit with positive status so web interface treats it as user error.
    exit(1);
}

sub escapeshellarg($)
{
    my ($str) = @_;

    $str =~ s/[^-_[:alnum:]]/\\$&/g;
    return $str;
}