addpubkey.in 16.8 KB
Newer Older
1 2 3
#!/usr/bin/perl -wT
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2000-2012 University of Utah and the Flux Group.
5 6 7 8
# All rights reserved.
#
use English;
use Getopt::Std;
9
use XML::Simple;
10 11 12 13 14 15 16 17 18 19

#
# Parse ssh public keys and enter into the DB. The default format is
# openssh, but if the key is not in that format, then use ssh-keygen
# to see if it can be converted from either SSH2 or SECSH format into
# openssh format. This gets called from the webpage to parse keys
# uploaded by users.
#
sub usage()
{
Russ Fish's avatar
Russ Fish committed
20 21 22
    print "Usage: addpubkeys [-d] [-k | -f] [-n | -u <user>] [<keyfile> | <key>]\n";
    print "       addpubkeys [-d] -X <xmlfile>\n";
    print "       addpubkeys [-d] [-i [-r] | -w] <user>\n";
23
    print "Options:\n";
Russ Fish's avatar
Russ Fish committed
24
    print " -d      Turn on debugging\n";
25
    print " -k      Indicates that key was passed in on the command line\n";
26
    print " -f      Indicates that key was passed in as a filename\n";
27
    print " -n      Verify key format only; do not enter into into DB\n";
28
    print " -X      Get args from an XML file: verify, user, keyfile.\n";
29 30
    print " -w      Generate new authkeys (protocol 1 and 2) file for user\n";
    print " -i      Initialize mode; generate initial key for user\n";
31
    print " -r      Force a regenerate of initial key for user\n";
32 33
    exit(-1);
}
34
my $optlist   = "dkniwfu:rX:sRNC:S:";
35 36
my $iskey     = 0;
my $verify    = 0;
37
my $initmode  = 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
38
my $force     = 0;
39 40 41
my $genmode   = 0;
my $nobody    = 0;
my $noemail   = 0;
42 43 44
my $remove    = 0;
my $nodelete  = 0;
my $Comment;
45
my $xmlfile;
46 47 48 49 50 51 52

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
my $TBAUDIT     = "@TBAUDITEMAIL@";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
53
my $OURDOMAIN   = "@OURDOMAIN@";
54 55 56 57 58
my $KEYGEN	= "/usr/bin/ssh-keygen";
my $USERUID;

# Locals
my $user;
59 60
my $this_user;
my $target_user;
61 62 63 64 65 66
my $keyfile;
my $keyline;
my $key;
my $comment;
my $user_name;
my $user_email;
67 68
my $user_dbid;
my $user_uid;
Russ Fish's avatar
Russ Fish committed
69
my $debug = 0;
70 71 72 73 74

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
75
use libaudit;
76 77
use libdb;
use libtestbed;
78
use User;
79

80 81 82 83 84
#
# Function prototypes
#
sub ParseKey($);
sub InitUser();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
85
sub GenerateKeyFile();
Russ Fish's avatar
Russ Fish committed
86
sub ParseXmlArgs($$$$$$);
87 88
sub fatal($);

89 90
my $HOMEDIR = USERROOT();

91 92 93 94 95 96 97 98 99 100 101 102
#
# 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.
my %xmlfields =
    # XML Field Name        DB slot name         Flags             Default
    ("verify"		=> ["verify",		$SLOT_OPTIONAL,	   0],
     "user"		=> ["user",		$SLOT_OPTIONAL],
     "keyfile"		=> ["keyfile",		$SLOT_REQUIRED]);

103 104 105 106 107 108 109 110 111 112 113
#
# Turn off line buffering on output
#
$| = 1;

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

114 115 116 117 118 119 120 121
#
# We don't want to run this script unless its the real version.
#
if ($EUID != 0) {
    die("*** $0:\n".
	"    Must be setuid! Maybe its a development version?\n");
}

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
#
# Please do not run it as root. Hard to track what has happened.
# 
if ($UID == 0) {
    die("*** $0:\n".
	"    Please do not run this as root!\n");
}

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
Russ Fish's avatar
Russ Fish committed
138 139 140
if (defined($options{"d"})) {
    $debug = 1;
}
141 142 143
if (defined($options{"k"})) {
    $iskey = 1;
}
144 145 146
if (defined($options{"f"})) {
    $iskey = 0;
}
147 148 149
if (defined($options{"n"})) {
    $verify = 1;
}
150 151 152
if (defined($options{"i"})) {
    $initmode = 1;
}
153 154 155
if (defined($options{"N"})) {
    $nodelete = 1;
}
156
if (defined($options{"r"})) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
157 158
    $force = 1;
}
159 160 161
if (defined($options{"R"})) {
    $remove = 1;
}
162 163 164
if (defined($options{"s"})) {
    $noemail = 1;
}
165 166
if (defined($options{"w"})) {
    $genmode = 1;
167
}
168 169 170
if (defined($options{"u"})) {
    $user = $options{"u"};
}
171 172 173
if (defined($options{"C"})) {
    $Comment = $options{"C"};
}
174 175 176 177 178
if (defined($options{"X"})) {
    $xmlfile = $options{"X"};

    my %xmlargs = (); 
    my %errors = ();
Russ Fish's avatar
Russ Fish committed
179 180
    ParseXmlArgs($xmlfile, "user_pubkeys", \%xmlfields, $debug,
		 \%xmlargs, \%errors);
181 182 183 184 185 186 187 188 189 190 191 192 193 194
    if (keys(%errors)) {
	foreach my $key (keys(%errors)) {
	    my $val = $errors{$key};
	    print "${key}: $val\n";
	}
	fatal("XML arg error");
    }

    $verify = $xmlargs{"verify"};
    $user = $xmlargs{"user"}
	if (exists($xmlargs{"user"}));
    $ARGV[0] = $xmlargs{"keyfile"};
}

195
if ($verify && $genmode) {
196 197
    usage();
}
198
if ($initmode || $genmode) {
199 200 201 202
    usage()
	if (@ARGV != 1);

    $user = $ARGV[0];
203 204
}
else {
205 206 207 208 209 210 211
    usage()
	if (@ARGV != 1);
    usage()
	if (!$verify && !defined($user));
    
    $keyfile = $ARGV[0];
}
212 213 214 215

#
# Untaint the arguments.
#
216
if (defined($user)) {
217
    if ($user =~ /^([-\w]+)$/i) {
218 219 220 221 222
	$user = $1;
    }
    else {
	fatal("Tainted username: $user");
    }
223 224 225 226 227 228 229 230 231 232
    # Map user to object.
    $target_user = User->Lookup($user);
    if (! defined($target_user)) {
	fatal("$user does not exist!")
    }

    $user_name  = $target_user->name();
    $user_email = $target_user->email();
    $user_dbid  = $target_user->dbid();
    $user_uid   = $target_user->uid();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
233
    $USERUID    = $target_user->unix_uid();
234 235 236
}

#
237 238 239
# If invoked as "nobody" we came from the web interface. We have to have
# a credential in the environment, unless its just a key verification
# operation, which anyone can do. 
240 241
# 
if (getpwuid($UID) eq "nobody") {
242 243 244 245
    $this_user = User->ImpliedUser();
    
    if (($initmode || $genmode || !$verify) && !defined($this_user)) {
	fatal("Bad usage from web interface");
246 247 248 249
    }
    $nobody = 1;
}
else {
250 251
    # From the command line; map invoking user to object.
    $this_user = User->ThisUser();
252 253 254 255

    if (! defined($this_user)) {
	fatal("You ($UID) do not exist!");
    }
256 257 258
}

#
259 260
# Initmode or genmode, do it and exit. Eventually get rid of the switch
# to the target user.
261 262 263
#
if ($initmode) {
    # Drop root privs, switch to target user.
264
    $EUID = $UID = $USERUID;
265 266 267 268
    exit InitUser();
}
if ($genmode) {
    # Drop root privs, switch to target user.
269
    $EUID = $UID = $USERUID;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
270
    exit GenerateKeyFile();
271 272 273
}

# Else, key parse mode ...
274 275 276 277 278 279 280 281 282 283 284 285
if ($iskey) {
    if ($keyfile =~ /^([-\w\s\.\@\+\/\=]*)$/) {
	$keyfile = $1;
    }
    else {
	fatal("Tainted key: $keyfile");
    }
    $keyline = $keyfile;
}
else {
    if ($keyfile =~ /^([-\w\.\/]+)$/) {
	$keyfile = $1;
286
     }
287 288 289 290
    else {
	fatal("Tainted filename: $keyfile");
    }
    if (! -e $keyfile) {
291
	fatal("No such file: $keyfile\n");
292 293 294 295 296
    }
    $keyline = `head -1 $keyfile`;
}

#
297
# Check user
298
#
299
if (!$verify) {
300 301 302 303
    # If its the user himself, then we can generate a new authkeys file.
    # Assume nodelete option comes from internal script, so do not worry.
    if (!$target_user->SameUser($this_user) && !$this_user->IsAdmin() &&
	!$nodelete) {
304
	fatal("You are not allowed to set pubkeys for $target_user\n");
305
    }
306
    if (-d "$HOMEDIR/$user_uid/.ssh") {
307 308
	# Drop root privs, switch to target user.
	$EUID = $UID = $USERUID;
309 310
	$genmode = 1;
    }
311
    
312 313 314 315 316 317
    #
    # This script is audited when not in verify mode. Since all keys are first
    # checked with verify mode, this should not cause any extra email from bad
    # keys.
    #
    AuditStart(0);
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
#
# Grab the first line of the file. Parse it to see if its in the
# format we like (openssh), either protocol 1 or 2.
#
if (ParseKey($keyline)) {
    exit 0;
}
# If the key was entered on the command line, then nothing more to do.
if ($iskey) {
    exit 1;
}

#
# Run ssh-keygen over it and see if it can convert it. 
#
if (! open(KEYGEN, "ssh-keygen -i -f $keyfile 2>/dev/null |")) {
    fatal("*** $0:\n".
	  "    Could not start ssh-keygen\n");
}
$keyline = <KEYGEN>;
if (close(KEYGEN) && ParseKey($keyline)) {
    exit 0;
}
exit 1;

sub ParseKey($) {
    my ($keyline) = @_;
347

348
    # Remove trailing newlines which screws the patterns below.
349 350
    # First convert dos newlines since many people upload from windoze.
    $keyline =~ s/\r/\n/g;
351 352
    $keyline =~ s/\n//g;

353 354 355 356 357 358
    # Enforce a reasonable length on the key.
    if (length($keyline) > 4096) {
	print "Key is too long!\n";
	print "Key: $keyline\n";
	return 0;
    }
359
    
360
    if ($keyline =~ /^(\d*\s\d*\s[0-9a-zA-Z]*) ([-\w\@\.\ ]*)\s*$/) {
361 362 363 364 365 366 367 368 369 370 371
        # Protocol 1
	$type    = "ssh-rsa1";
	$key     = $1;
	$comment = $2;
    }
    elsif ($keyline =~ /^(\d*\s\d*\s[0-9a-zA-Z]*)\s*$/) {
        # Protocol 1 but no comment field.
	$type    = "ssh-rsa1";
	$key     = $1;
    }
    elsif ($keyline =~
372
	   /^(ssh-rsa|ssh-dss) ([-\w\.\@\+\/\=]*) ([-\w\@\.\ ]*)$/) {
373 374 375 376 377 378 379 380 381 382 383 384
        # Protocol 2
	$type    = $1;
	$key     = "$1 $2";
	$comment = $3;
    }
    elsif ($keyline =~ /^(ssh-rsa|ssh-dss) ([-\w\.\@\+\/\=]*)$/) {
        # Protocol 2 but no comment field
	$type    = $1;
	$key     = "$1 $2";
    }

    if (!defined($key)) {
385 386
	print "Key cannot be parsed!\n";
	print "Key: $keyline\n";
387 388
	return 0;
    }
389

390 391
    # Do not enter into DB if in verify mode.
    if ($verify) {
392
	print "Key was good: $type\n";
393 394 395 396
	return 1;
    }

    #
397
    # Make up a comment field for the DB. 
398 399
    #
    if (!defined($comment)) {
400
	$comment = (defined($Comment) ? $Comment : "$type-${user_email}");
401 402
    }
    $key = "$key $comment";
403 404
    my $safe_key = DBQuoteSpecial($key);
    my $safe_comment = DBQuoteSpecial($comment);
405

406 407 408 409 410 411 412 413 414
    if ($remove) {
	DBQueryFatal("delete from user_pubkeys ".
		     "where uid_idx='$user_dbid' and comment=$safe_comment");
    }
    DBQueryFatal("replace into user_pubkeys set ".
		 " uid='$user_uid', uid_idx='$user_dbid', ".
		 " internal='0', nodelete='$nodelete', ".
		 " idx=NULL, stamp=now(), ".
		 " pubkey=$safe_key, comment=$safe_comment");
415

416 417 418
    #
    # Mark user record as modified so nodes are updated.
    #
419
    TBNodeUpdateAccountsByUID($user_uid);
420

421 422 423 424 425 426 427 428
    my $chunked = "";

    while (length($key)) {
	$chunked .= substr($key, 0, 65, "");
	if (length($key)) {
	    $chunked .= "\n";
	}
    }
429 430
    print "SSH Public Key for '$user' added:\n";
    print "$chunked\n";
431
    
432 433
    # Generate new auth keys file. 
    if ($genmode) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
434
	GenerateKeyFile();
435 436 437 438
    }

    if (! $noemail) {
	SENDMAIL("$user_name <$user_email>",
439 440
		 "SSH Public Key for '$user_uid' Added",
		 "SSH Public Key for '$user_uid' added:\n".
441 442 443 444 445
		 "\n".
		 "$chunked\n",
		 "$TBOPS");
    }
    return 1;
446 447
}

448 449 450 451 452 453
#
# Init function for new users. Generate the first key for the user (which
# is loaded into the DB), and then generate the keyfiles. Note that the
# user might have preloaded personal keys.
#
sub InitUser()
454
{
455
    my $sshdir  = "$HOMEDIR/$user_uid/.ssh";
456 457

    #
458
    # Set up the ssh key, but only if not done so already.
459
    #
460 461 462 463
    if (! -e "$sshdir") {
	mkdir("$sshdir", 0700) or
	    fatal("Could not mkdir $sshdir: $!");
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
464 465
    if (! -e "$sshdir/identity" || $force) {
	print "Creating ssh protocol 1 key for $user.\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
466

Leigh B. Stoller's avatar
Leigh B. Stoller committed
467 468 469 470 471 472 473 474
	#
	# Want to delete existing key from DB.
	#
	if (-e "$sshdir/identity") {
	    my $ident = `cat $sshdir/identity.pub`;

	    if ($ident =~ /(\d*\s\d*\s[0-9a-zA-Z]*)\s([-\w\@\.]*)/) {
		DBQueryFatal("delete from user_pubkeys ".
475
			     "where uid_idx='$user_dbid' and pubkey='$1 $2'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
476 477 478
	    }
	    unlink("$sshdir/identity");
	}
479

Leigh B. Stoller's avatar
Leigh B. Stoller committed
480
	# Hmm, need to use -C option so comment field makes sense.
481
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
482 483 484
	if (system("$KEYGEN -t rsa1 -P '' ".
		   "-C '${user}" . "\@" . ${OURDOMAIN} . "' ".
		   "-f $sshdir/identity")) {
485 486 487 488 489 490 491 492
	    fatal("Failure in ssh-keygen!");
	}

	#
	# Grab a copy for the DB.
	# 
	my $ident = `cat $sshdir/identity.pub`;

Leigh B. Stoller's avatar
Leigh B. Stoller committed
493
	if ($ident =~ /(\d*\s\d*\s[0-9a-zA-Z]*)\s([-\w\@\.]*)/) {
494 495 496 497
	    DBQueryFatal("replace into user_pubkeys set ".
			 " uid='$user_uid', uid_idx='$user_dbid', ".
			 " internal='1', nodelete='1', idx=NULL, stamp=now(), ".
			 " pubkey='$1 $2', comment='$2'");
498 499
	}
	else {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
500
	    fatal("Bad protocol 1 public key: $ident\n");
501 502
	}
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
503 504 505 506 507
    #
    # Moving to V2 keys ...
    #
    if (! -e "$sshdir/id_rsa" || $force) {
	print "Creating ssh protocol 2 key for $user.\n";
508

Leigh B. Stoller's avatar
Leigh B. Stoller committed
509 510 511 512 513 514 515 516 517
	#
	# Want to delete existing key from DB.
	#
	if (-e "$sshdir/id_rsa") {
	    my $ident = `cat $sshdir/id_rsa.pub`;

	    if ($ident =~
		/^(ssh-rsa [-\w\.\@\+\/\=]*) ([-\w\@\.\ ]*)$/) {
		DBQueryFatal("delete from user_pubkeys ".
518
			     "where uid_idx='$user_dbid' and pubkey='$1 $2'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
519 520 521 522 523
	    }
	    unlink("$sshdir/id_rsa");
	}

	# Hmm, need to use -C option so comment field makes sense.
524
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
525 526 527 528 529
	if (system("$KEYGEN -t rsa -P '' ".
		   "-C '${user}" . "\@" . ${OURDOMAIN} . "' ".
		   "-f $sshdir/id_rsa")) {
	    fatal("Failure in ssh-keygen!");
	}
530

Leigh B. Stoller's avatar
Leigh B. Stoller committed
531 532 533 534
	#
	# Grab a copy for the DB.
	# 
	my $ident = `cat $sshdir/id_rsa.pub`;
535

Leigh B. Stoller's avatar
Leigh B. Stoller committed
536 537
	if ($ident =~
	    /^(ssh-rsa [-\w\.\@\+\/\=]*) ([-\w\@\.\ ]*)$/) {
538 539 540 541
	    DBQueryFatal("replace into user_pubkeys set ".
			 " uid='$user_uid', uid_idx='$user_dbid', ".
			 " internal='1', nodelete='1', idx=NULL, stamp=now(), ".
			 " pubkey='$1 $2', comment='$2'");
542 543
	}
	else {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
544
	    fatal("Bad protocol 2 public key: $ident\n");
545 546
	}
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
547
    return GenerateKeyFile();
548 549 550 551 552 553
}

#
# Generate ssh authorized_keys files. Either protocol 1 or 2.
# Returns 0 on success, -1 on failure.
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
554
sub GenerateKeyFile()
555
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
556
    my @pkeys   = ();
557
    my $sshdir  = "$HOMEDIR/$user_uid/.ssh";
558 559 560 561 562 563 564 565
    my $keyfile = "$sshdir/authorized_keys";
	
    if (! -e $sshdir) {
	if (! mkdir($sshdir, 0700)) {
	    warn("*** WARNING: Could not mkdir $sshdir: $!\n");
	    return -1;
	}
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
566
    my $query_result =
567 568
	DBQueryFatal("select pubkey from user_pubkeys ".
		     "where uid_idx='$user_dbid'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
569 570 571

    while (my ($key) = $query_result->fetchrow_array()) {
	push(@pkeys, $key);
572
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
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
    print "Generating $keyfile ...\n";

    if (!open(AUTHKEYS, "> ${keyfile}.new")) {
	warn("*** WARNING: Could not open ${keyfile}.new: $!\n");
	return -1;
    }
    print AUTHKEYS "#\n";
    print AUTHKEYS "# DO NOT EDIT! This file auto generated by ".
	"Emulab.Net account software.\n";
    print AUTHKEYS "#\n";
    print AUTHKEYS "# Please use the web interface to edit your ".
	"public key list.\n";
    print AUTHKEYS "#\n";
    
    foreach my $key (@pkeys) {
	print AUTHKEYS "$key\n";
    }
    close(AUTHKEYS);

    if (!chmod(0600, "${keyfile}.new")) {
	warn("*** WARNING: Could not chmod ${keyfile}.new: $!\n");
	return -1;
    }
    if (-e "${keyfile}") {
	if (system("cp -p -f ${keyfile} ${keyfile}.old")) {
	    warn("*** Could not save off ${keyfile}: $!\n");
	    return -1;
	}
	if (!chmod(0600, "${keyfile}.old")) {
	    warn("*** Could not chmod ${keyfile}.old: $!\n");
	}
    }
    if (system("mv -f ${keyfile}.new ${keyfile}")) {
	warn("*** Could not mv ${keyfile} to ${keyfile}.new: $!\n");
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
609 610 611 612 613 614
    elsif (-e "$sshdir/authorized_keys2") {
	#
	# Save to remove deprecated authorized_keys2 file at this point.
	#
	unlink("$sshdir/authorized_keys2");
    }
615 616 617
    return 0;
}

Russ Fish's avatar
Russ Fish committed
618 619 620
sub ParseXmlArgs($$$$$$) {
    my ($xmlfile, $table_name, $fields_ref, $debug,
	$args_ref, $errs_ref) = @_;
621 622 623 624 625
    #
    # Input args:
    #  $xmlfile	   - XML file path.
    #  $table_name - table_regex table_name for low-level checking patterns.
    #  $fields_ref - xmlfields specification (hash reference.)
Russ Fish's avatar
Russ Fish committed
626
    #  $debug
627 628 629 630 631
    #
    # Output args:
    #  $args_ref   - Parsed argument values (hash reference.)
    #  $errs_ref   - Error messages on failure (hash reference.)

Leigh B. Stoller's avatar
Leigh B. Stoller committed
632
    $debug = 0;
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

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

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

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

    foreach $key (keys(%{ $xmlparse->{'attribute'} })) {
	my $value = $xmlparse->{'attribute'}->{"$key"}->{'value'};
662 663 664
	if (!defined($value)) {	# Empty string comes from XML as an undef value.
	    $xmlparse->{'attribute'}->{"$key"}->{'value'} = $value = "";
	}
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703

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

	$errs_ref->{$key} = "Unknown attribute"
	    if (!exists($fields_ref->{$key}));

	my ($dbslot, $required, $default) = @{$fields_ref->{$key}};

	if ($required & $SLOT_REQUIRED) {
	    # A slot that must be provided, so do not allow a null value.
	    if (!defined($value)) {
		$errs_ref->{$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.
	    $errs_ref->{$key} = "Administrators only"
		if (! $this_user->IsAdmin());
	}

	# Now check that the value is legal.
	if (! TBcheck_dbslot($value, $table_name, $dbslot, 
			     TBDB_CHECKDBSLOT_ERROR)) {
	    $errs_ref->{$key} = TBFieldErrorString();
	    next;
	}

Russ Fish's avatar
Russ Fish committed
704
	$args_ref->{$key} = $value;
705 706 707
    }
}

708 709 710 711 712 713
sub fatal($) {
    my($mesg) = $_[0];

    die("*** $0:\n".
	"    $mesg\n");
}