Commit 9dcf6297 authored by Russ Fish's avatar Russ Fish

Move editimageid page form logic to a backend Perl script.

     www/editimageid.php3 - The reworked PHP page.
     www/imageid_defs.php - Add an Experiment::EditImageid class method
                            bridging to the script via XML.
     backend/{editimageid,GNUmakefile}.in configure configure.in - New backend script.
     db/Image.pm.in - Add an EditImageid worker class method for script arg checking.
     sql/database-fill.sql - Add to the table_regex 'images' checking patterns.
parent a35e40cb
......@@ -12,8 +12,8 @@ UNIFIED = @UNIFIED_BOSS_AND_OPS@
include $(OBJDIR)/Makeconf
BIN_SCRIPTS = moduserinfo newgroup newmmlist editexp
WEB_BIN_SCRIPTS = webmoduserinfo webnewgroup webnewmmlist webeditexp
BIN_SCRIPTS = moduserinfo newgroup newmmlist editexp editimageid
WEB_BIN_SCRIPTS = webmoduserinfo webnewgroup webnewmmlist webeditimageid
WEB_SBIN_SCRIPTS=
LIBEXEC_SCRIPTS = $(WEB_BIN_SCRIPTS) $(WEB_SBIN_SCRIPTS)
......
#!/usr/bin/perl -wT
#
# EMULAB-COPYRIGHT
# Copyright (c) 2000-2007 University of Utah and the Flux Group.
# All rights reserved.
#
use English;
use strict;
use Getopt::Std;
use XML::Simple;
use Data::Dumper;
#
# Back-end script to edit image descriptor.
#
sub usage()
{
print("Usage: editimageid [-v] <xmlfile>\n");
exit(-1);
}
my $optlist = "dv";
my $debug = 0;
my $verify = 0; # Check data and return status only.
#
# Configure variables
#
my $TB = "@prefix@";
my $TBOPS = "@TBOPSEMAIL@";
my $TBAUDIT = "@TBAUDITEMAIL@";
my $TBGROUP_DIR = "@GROUPSROOT_DIR@";
my $TBPROJ_DIR = "@PROJROOT_DIR@";
#
# 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;
use Image;
# 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;
}
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!");
}
# You don't need admin privileges to edit image descriptor.
}
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.
my $translated = `realpath $xmlfile`;
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!");
}
}
my $isadmin = $this_user->IsAdmin();
#
# 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
("imageid" => ["imageid", $SLOT_REQUIRED],
# The rest are optional, so we can skip passing ones that are not changing.
"description" => ["description", $SLOT_OPTIONAL],
"path" => ["path", $SLOT_OPTIONAL],
"load_address" => ["load_address", $SLOT_ADMINONLY],
"frisbee_pid" => ["frisbee_pid", $SLOT_ADMINONLY]);
# The "mtype_$type" node type booleans are handled below...
#
# Need a list of node types. We join this over the nodes table so that
# we get a list of just the nodes that are currently in the testbed, not
# just in the node_types table.
#
my $types_result =
DBQueryFatal("select distinct n.type from nodes as n ".
"left join node_type_attributes as a on a.type=n.type ".
"where a.attrkey='imageable' and ".
" a.attrvalue!='0'");
# Save the valid types in a new array for later.
my @mtypes_array;
while (my ($type) = $types_result->fetchrow_array()) {
push(@mtypes_array, $type);
$xmlfields{"mtype_$type"} = ["mtype", $SLOT_OPTIONAL];
}
## printf "%s mtypes\n", $#mtypes_array + 1;
## foreach my $x (@mtypes_array) { printf "%s\n", $x; }
## print "\n";
#
# 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));
#
# We build up an array of arguments to pass to Image->EditImageid() as we check
# the attributes.
#
my %editimageid_args = ();
my $foo;
foreach $key (keys(%{ $xmlparse->{'attribute'} })) {
my $value = $xmlparse->{'attribute'}->{"$key"}->{'value'};
if ($debug) {
print STDERR "User attribute: '$key' -> '$value'\n";
}
# XXX Special for mtype_* args, since the keys are dynamically generated.
if ($key =~ /^mtype_[\w]+$/) {
print STDERR "mtype: '$key' -> '$value'\n"
if ($debug);
my $type = $key;
$type =~ s/^mtype_//;
my $match = grep(/^${type}$/, @mtypes_array);
$errors{$key} = "Illegal node type."
if ($match == 0);
$errors{$key} = "Illegal characters in boolean value"
if ($value ne "0" && $value ne "1");
$editimageid_args{$key} = $value;
next;
}
$errors{$key} = "Unknown attribute"
if (!exists($xmlfields{$key}));
my ($dbslot, $required, $default) = @{$xmlfields{$key}};
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.
if (! TBcheck_dbslot($value, "images", $dbslot, TBDB_CHECKDBSLOT_ERROR)) {
$errors{$key} = TBFieldErrorString();
next;
}
$editimageid_args{$dbslot} = $value;
}
UserError()
if (keys(%errors));
#
# Now do special checks.
#
my $image = Image->Lookup($editimageid_args{"imageid"});
if (!defined($image)) {
UserError("Image: No such image");
}
if (!$image->AccessCheck($this_user, TB_IMAGEID_MODIFYINFO())) {
UserError("Image: Not enough permission");
}
#
# Description must not be blank.
#
if ((exists($editimageid_args{"description"}) ?
$editimageid_args{"description"} eq "" :
$image->description() eq "")) {
UserError("Description: Missing Field");
}
if (exists($editimageid_args{"description"})) {
$editimageid_args{"description"} =
escapeshellarg($editimageid_args{"description"});
}
#
# Path must not be blank.
#
if ((exists($editimageid_args{"path"}) ?
$editimageid_args{"path"} eq "" :
$image->path() eq "")) {
UserError("Path: Missing Field");
}
# Admins can put an image wherever they want.
if (!$isadmin && exists($editimageid_args{"path"})) {
my $pdef = "";
my $shared = $image->shared();
my $pid = $image->pid();
my $gid = $image->gid();
if (!$shared && $gid ne $pid) {
$pdef = "$TBGROUP_DIR/" . $pid . "/" . $gid . "/";
}
else {
$pdef = "$TBPROJ_DIR/" . $pid . "/";
}
if (index($editimageid_args{"path"}, $pdef) < 0) {
UserError("Path: Must reside in $pdef");
}
}
#
# See what node types this image will work on. Must be at least one!
if ($#mtypes_array < 0) {
UserError("Node Types: Must select at least one type");
}
my $typeclause = join(" or ", map("type='$_'", @mtypes_array));
#
# Only admins can edit the load_address or the frisbee pid.
#
if ($isadmin) {
if (exists($editimageid_args{"load_address"}) &&
$editimageid_args{"load_address"} ne "") {
$foo = escapeshellarg($editimageid_args{"load_address"});
if ($editimageid_args{"load_address"} ne $foo) {
UserError("Load Address: Contains illegal characters!");
}
}
# Frisbee_pid has already been checked to be a valid int coming from XML.
}
else { # Not isadmin.
if (exists($editimageid_args{"load_address"}) &&
$editimageid_args{"load_address"} ne $image->load_address()) {
UserError("Load Address: No permission, admin-only");
}
if (exists($editimageid_args{"frisbee_pid"}) &&
$editimageid_args{"frisbee_pid"} ne $image->frisbee_pid()) {
UserError("Frisbee PID: No permission, admin-only");
}
}
#
# Mereusers are not allowed to create more than one osid/imageid mapping
# for each machinetype. They cannot actually do that through the EZ form
# since the osid/imageid has to be unique, but it can happen by mixed
# use of the long form and the short form, or with multiple uses of the
# long form.
#
my $osidclause;
for (my $i = 1; $i <= 4; $i++) {
# Local variable dynamically created.
$foo = $image->field("part${i}_osid");
if (defined($foo)) {
$osidclause .= " or "
if (defined($osidclause));
$osidclause .= "osid='$foo'";
}
}
DBQueryFatal("lock tables images write, os_info write, osidtoimageid write");
my $imageid = $image->imageid();
my $query_result =
DBQueryFatal("select osidtoimageid.*,images.pid,images.imagename ".
" from osidtoimageid ".
"left join images on ".
" images.imageid=osidtoimageid.imageid ".
"where ($osidclause) and ($typeclause) and ".
" images.imageid!='$imageid'");
DBQueryFatal("unlock tables");
if ($query_result->numrows) {
my $msg =
"There are other image descriptors that specify the same OS".
"descriptors for the same node types. There must be a unique".
"mapping of OS descriptor to Image descriptor for each node type!".
"Perhaps you need to delete one of the images below, or create a".
"new OS descriptor to use in this new Image descriptor. \n\n";
my $fmt = "%-10s %-15s %-15s %s\n";
$msg .= sprintf($fmt, "Image", "OSID", "Type", "ImageID");
$msg .= sprintf($fmt, "=====", "====", "====", "=======");
while (my ($imageid, $osid, $type, $imagename) =
$query_result->fetchrow_array()) {
$msg .= sprintf($fmt, $imageid, $osid, $type, $imagename);
}
UserError("Conflict: Please check the other Image descriptors".
" and make the necessary changes!\n $msg");
}
exit(0)
if ($verify);
#
# Now safe to edit image descriptor.
#
# We pass the imageid along as an argument to EditImageid(), so remove it from
# the argument array.
#
delete($editimageid_args{"imageid"});
my $usrerr;
my $editimageid_val = Image->EditImageid($image,
\%editimageid_args, \$usrerr);
UserError($usrerr)
if (defined($usrerr));
fatal("Could not create new Image!")
if (!defined($editimageid_val));
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;
}
......@@ -2428,7 +2428,7 @@ outfiles="$outfiles Makeconf GNUmakefile \
account/addpubkey account/addsfskey account/genpubkeys \
account/quotamail account/mkusercert account/newproj account/newuser \
backend/GNUmakefile backend/moduserinfo backend/newgroup \
backend/newmmlist backend/editexp \
backend/newmmlist backend/editexp backend/editimageid \
tbsetup/GNUmakefile tbsetup/console_setup tbsetup/spewlogfile \
tbsetup/spewrpmtar tbsetup/gentopofile tbsetup/power_sgmote.pm \
tbsetup/console_reset tbsetup/bwconfig tbsetup/power_rpc27.pm \
......
......@@ -808,7 +808,7 @@ outfiles="$outfiles Makeconf GNUmakefile \
account/addpubkey account/addsfskey account/genpubkeys \
account/quotamail account/mkusercert account/newproj account/newuser \
backend/GNUmakefile backend/moduserinfo backend/newgroup \
backend/newmmlist backend/editexp \
backend/newmmlist backend/editexp backend/editimageid \
tbsetup/GNUmakefile tbsetup/console_setup tbsetup/spewlogfile \
tbsetup/spewrpmtar tbsetup/gentopofile tbsetup/power_sgmote.pm \
tbsetup/console_reset tbsetup/bwconfig tbsetup/power_rpc27.pm \
......
......@@ -164,6 +164,116 @@ sub Refresh($)
return 0;
}
#
# Worker class method to edit image descriptor.
# Assumes most argument checking was done elsewhere.
#
sub EditImageid($$$$)
{
my ($class, $image, $argref, $usrerr_ref) = @_;
my %mods;
my $noreport;
my $imageid = $image->imageid();
#
# Now update the rest of the information in the DB.
# (Others above already did their own updates.)
#
my %updates;
foreach my $col ("description", "path", "load_address", "frisbee_pid" ) {
# Copy args we want so that others can't get through.
if (exists($argref->{$col})) {
$updates{$col} = $mods{$col} = $argref->{$col};
}
}
# See mtype_$type args below.
#
# Need a list of node types. We join this over the nodes table so that
# we get a list of just the nodes that are currently in the testbed, not
# just in the node_types table.
#
my $types_result =
DBQueryFatal("select distinct n.type from nodes as n ".
"left join node_type_attributes as a on a.type=n.type ".
"where a.attrkey='imageable' and ".
" a.attrvalue!='0'");
my @mtypes_array;
my @map_updates;
my $redo_map = 0;
while (my ($type) = $types_result->fetchrow_array()) {
push(@mtypes_array, $type);
# Remember when we get one of the mtype_$type args. These aren't DB
# columns to update, but instead control re-creating the rows in the
# osidtoimageid table for this imageid, below.
my $mtype = "mtype_$type";
if (exists($argref->{$mtype})) {
my $value = $argref->{$mtype};
##printf "argref->{$mtype} %s\n", $value;
$mods{$mtype} = $value;
if ($value eq "1") {
push(@map_updates, $type);
$redo_map = 1;
}
}
}
if (!keys %mods) {
if (!$noreport) {
# Warn the user that the submit button was pressed with no effect.
$$usrerr_ref = "Submit: Nothing changed";
return undef;
}
}
if (keys %updates || $redo_map) {
DBQueryFatal("lock tables images write, os_info write, ".
"osidtoimageid write");
}
if (keys %updates) {
if ($image->Update(\%updates)) {
$$usrerr_ref = "DB: Error updating the images table";
DBQueryFatal("unlock tables");
return undef;
}
}
if ($redo_map) {
#
# Update the osidtoimageid table too.
#
# Must delete old entries first.
DBQueryFatal("delete from osidtoimageid ".
"where imageid='$imageid'");
my @osid_array;
for (my $i = 1; $i <= 4; $i++) {
my $foo = $image->field("part${i}_osid");
if (defined($foo)) {
push(@osid_array, $foo);
}
}
for (my $i = 0; $i <= $#map_updates; $i++) {
for (my $j = 0; $j <= $#osid_array; $j++) {
my $query = "REPLACE INTO osidtoimageid ".
" (osid, type, imageid) ".
"VALUES ('$osid_array[$j]', ".
" '$map_updates[$i]', ".
" '$imageid')";
##print "$query\n";
DBQueryFatal($query);
}
}
}
if (keys %updates || $redo_map) {
DBQueryFatal("unlock tables");
}
return 1;
}
#
# Stringify for output.
#
......
......@@ -788,8 +788,16 @@ REPLACE INTO table_regex VALUES ('virt_nodes','plab_role','text','regex','^(plc|
REPLACE INTO table_regex VALUES ('experiments','elab_in_elab','int','redirect','default:boolean',0,0,NULL);
REPLACE INTO table_regex VALUES ('experiments','elabinelab_singlenet','int','redirect','default:boolean',0,0,NULL);
REPLACE INTO table_regex VALUES ('experiments','elabinelab_cvstag','text','regex','^[-\\w\\@\\/\\.]+$',0,0,NULL);
REPLACE INTO table_regex VALUES ('images','imageid','text','regex','^[a-zA-Z0-9][-\\w\\.+]+$',0,45,NULL);
REPLACE INTO table_regex VALUES ('images','imageid','text','redirect','default:int',0,100000000,NULL);
REPLACE INTO table_regex VALUES ('images','imagename','text','regex','^[a-zA-Z0-9][-\\w\\.+]+$',2,30,NULL);
REPLACE INTO table_regex VALUES ('images','description','text','regex','^[\\040-\\176\\012\\015\\011]*$',1,256,NULL);
REPLACE INTO table_regex VALUES ('images','path','text','regex','^[-_\\w\\.\\/:+]*$',1,256,NULL);
REPLACE INTO table_regex VALUES ('images','mtype','text','redirect','default:boolean',0,0,NULL);
REPLACE INTO table_regex VALUES ('images','osid','text','redirect','os_info:osid',0,0,NULL);
REPLACE INTO table_regex VALUES ('images','load_address','text','redirect','default:text',0,0,NULL);
REPLACE INTO table_regex VALUES ('images','frisbee_pid','text','redirect','default:int',0,0,NULL);
REPLACE INTO table_regex VALUES ('experiments','security_level','int','redirect','default:tinyuint',0,4,NULL);
REPLACE INTO table_regex VALUES ('experiments','elabinelab_eid','text','redirect','experiments:eid',0,0,NULL);
REPLACE INTO table_regex VALUES ('virt_node_startloc','pid','text','redirect','projects:pid',0,0,NULL);
......
......@@ -15,7 +15,7 @@ include_once("osinfo_defs.php");
PAGEHEADER("Edit Image Descriptor");
#
# Only known and logged in users!
# Only known and logged in users.
#
$this_user = CheckLoginOrDie();
$uid = $this_user->uid();
......@@ -50,11 +50,11 @@ $types_result =
" a.attrvalue!='0'");
#
# Spit the form out using the array of data.
#
# Spit the form out using the array of data.
#
function SPITFORM($image, $formfields, $errors)
{
global $uid, $isadmin, $types_result;
global $uid, $isadmin, $types_result, $defaults;
global $TBDB_IMAGEID_IMAGENAMELEN, $TBDB_NODEIDLEN;
if ($errors) {
......@@ -84,14 +84,14 @@ function SPITFORM($image, $formfields, $errors)
$url = CreateURL("editimageid", $image);
echo "<br>
<table align=center border=1>
<form action='$url' method=post name=idform>\n";
<form action='$url' method=post>\n";
#
# Imagename
#
echo "<tr>
<td>ImageID:</td>
<td class=left>" . $formfields["imagename"] . "</td>
<td class=left>" . $defaults["imagename"] . "</td>
</tr>\n";
#
......@@ -99,7 +99,7 @@ function SPITFORM($image, $formfields, $errors)
#
echo "<tr>
<td>Project:</td>
<td class=left>" . $formfields["pid"] . "</td>
<td class=left>" . $defaults["pid"] . "</td>
</tr>\n";
#
......@@ -107,7 +107,7 @@ function SPITFORM($image, $formfields, $errors)
#
echo "<tr>
<td>Group:</td>
<td class=left>" . $formfields["gid"] . "</td>
<td class=left>" . $defaults["gid"] . "</td>
</tr>\n";
#
......@@ -115,7 +115,7 @@ function SPITFORM($image, $formfields, $errors)
#
echo "<tr>
<td>Descriptor Name:</td>
<td class=left>" . $formfields["imagename"] . "</td>
<td class=left>" . $defaults["imagename"] . "</td>
</tr>\n";
#
......@@ -136,7 +136,7 @@ function SPITFORM($image, $formfields, $errors)
#
echo "<tr>
<td>Load Partition:</td>
<td class=left>" . $formfields["loadpart"] . "</td>
<td class=left>" . $defaults["loadpart"] . "</td>
</tr>\n";
#
......@@ -144,14 +144,14 @@ function SPITFORM($image, $formfields, $errors)
#
echo "<tr>
<td>Load Partition:</td>
<td class=left>" . $formfields["loadlength"] . "</td>
<td class=left>" . $defaults["loadlength"] . "</td>
</tr>\n";
echo "<tr>
<td>Partition 1 OS: </td>
<td class=\"left\">";
if (isset($formfields["part1_osid"]))
SpitOSIDLink($formfields["part1_osid"]);
if (isset($defaults["part1_osid"]))
SpitOSIDLink($defaults["part1_osid"]);
else
echo "No OS";
echo " </td>
......@@ -160,8 +160,8 @@ function SPITFORM($image, $formfields, $errors)
echo "<tr>
<td>Partition 2 OS: </td>
<td class=\"left\">";
if (isset($formfields["part2_osid"]))
SpitOSIDLink($formfields["part2_osid"]);
if (isset($defaults["part2_osid"]))
SpitOSIDLink($defaults["part2_osid"]);
else
echo "No OS";
echo " </td>
......@@ -170,8 +170,8 @@ function SPITFORM($image, $formfields, $errors)
echo "<tr>
<td>Partition 3 OS: </td>
<td class=\"left\">";
if (isset($formfields["part3_osid"]))
SpitOSIDLink($formfields["part3_osid"]);
if (isset($defaults["part3_osid"]))
SpitOSIDLink($defaults["part3_osid"]);
else
echo "No OS";
echo " </td>
......@@ -180,8 +180,8 @@ function SPITFORM($image, $formfields, $errors)
echo "<tr>
<td>Partition 4 OS: </td>
<td class=\"left\">";
if (isset($formfields["part4_osid"]))
SpitOSIDLink($formfields["part4_osid"]);
if (isset($defaults["part4_osid"]))