xmlconvert.in 24.3 KB
Newer Older
1
#!/usr/bin/perl -w
2 3

#
4
# Copyright (c) 2000-2012, 2018 University of Utah and the Flux Group.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# 
# {{{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/>.
# 
# }}}
24 25 26 27
#

use English;
use Getopt::Std;
28
use XML::Parser;
29

30 31 32 33
#
# Convert between XML and DB representation of a virtual experiment.
# Very simple, no DTDs, DOMs, XSLs, etc. Just the facts ...
#
34 35 36 37
# XXX We do not regex the data carefully enough before inserting it into
# the DB. We run quotemeta() over it, but we should be more careful about
# per-slot checks.
#
38 39
sub usage()
{
40
    print STDOUT "Usage: xmlconvert [-x <xmlfile> [-n] [-p]] [-d] pid eid\n";
41 42 43
 
    exit(-1);
}
44
my $optlist  = "x:ndsp";
45
my $fromxml  = 0;
46
my $fromparser = 0;
47
my $impotent = 0;
48
my $debug    = 0;
49 50 51
# Results of parsing nse specifications. Therefore different treatment.
# In particular, we don't expect updates to the experiments table
my $simparse = 0;
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67

#
# Configure variables
#
my $TB       = "@prefix@";
my $TBOPS    = "@TBOPSEMAIL@";

# Locals
my $xmlfile;
my $pid;
my $eid;

# This goes at the beginning of the output.
my $XMLHEADER = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";

#
68 69 70 71 72
# These are the virtual tables that make up an experiment.  Each one
# could have multiple rows, each of which will be a hash table.
#
my %virtual_tables = 
    ("experiments"		=> { rows  => undef, 
73 74
				     tag   => "settings",
				     # Indicates a single row.
75
				     row   => undef},
76 77
     "virt_nodes"		=> { rows  => undef, 
				     tag   => "nodes",
78
				     row   => "node"},
79
     "virt_lans"		=> { rows  => undef, 
80
				     tag   => "lan_members",
81
				     row   => "lan_member"},
82
     "virt_lan_lans"		=> { rows  => undef, 
83
				     tag   => "lans",
84
				     row   => "lan"},
85 86
     "virt_lan_settings"	=> { rows  => undef, 
				     tag   => "lan_settings",
87
				     row   => "lan_setting"},
88 89
     "virt_lan_member_settings" => { rows  => undef, 
				     tag   => "lan_member_settings",
90
				     row   => "lan_member_setting"},
91 92
     "virt_trafgens"		=> { rows  => undef, 
				     tag   => "trafgens",
93
				     row   => "trafgen"},
94 95
     "virt_agents"		=> { rows  => undef, 
				     tag   => "agents",
96
				     row   => "agent"},
97 98
     "virt_node_desires"	=> { rows  => undef, 
				     tag   => "node_desires",
99
				     row   => "node_desire"},
Timothy Stack's avatar
Timothy Stack committed
100 101
     "virt_node_startloc"	=> { rows  => undef, 
				     tag   => "node_startlocs",
102
				     row   => "node_startloc"},
103 104
     "virt_routes"		=> { rows  => undef, 
				     tag   => "routes",
105
				     row   => "route"},
106 107
     "virt_vtypes"		=> { rows  => undef, 
				     tag   => "vtypes",
108
				     row   => "vtype"},
109 110
     "virt_programs"		=> { rows  => undef, 
				     tag   => "programs",
111
				     row   => "program"},
112 113 114
     "virt_node_attributes"	=> { rows  => undef, 
				     tag   => "virt_node_attributes",
				     row   => "virt_node_attribute"},
115 116 117
     "virt_node_disks"      	=> { rows  => undef, 
				     tag   => "virt_node_disks",
				     row   => "virt_node_disk"},
Timothy Stack's avatar
Timothy Stack committed
118 119
     "virt_user_environment"	=> { rows  => undef, 
				     tag   => "user_environments",
120
				     row   => "user_environment"},
121 122
     "nseconfigs"		=> { rows  => undef, 
				     tag   => "nseconfigs",
123
				     row   => "nseconfig"},
124 125
     "eventlist"		=> { rows  => undef, 
				     tag   => "events",
126
				     row   => "event"},
127 128
     "event_groups"		=> { rows  => undef, 
				     tag   => "event_groups",
129
				     row   => "event_group"},
130 131
     "virt_firewalls"		=> { rows  => undef, 
				     tag   => "virt_firewalls",
132
				     row   => "virt_firewall"},
133 134
     "firewall_rules"		=> { rows  => undef, 
				     tag   => "firewall_rules",
135
				     row   => "firewall_rule"},
136 137 138
     "elabinelab_attributes"	=> { rows  => undef, 
				     tag   => "elabinelab_attributes",
				     row   => "attribute"},
Timothy Stack's avatar
Timothy Stack committed
139 140
     "virt_tiptunnels"		=> { rows  => undef, 
				     tag   => "tiptunnels",
141
				     row   => "tiptunnel"},
142 143 144 145 146 147
     "virt_parameters"          => { rows  => undef, 
				     tag   => "parameters",
				     row   => "parameter"},
     "virt_paths"               => { rows  => undef,
				     tag   => "path_members",
				     row   => "path_member"},
148 149 150
     "virt_bridges"             => { rows  => undef,
				     tag   => "bridge_members",
				     row   => "bridge_member"},
151 152 153
     "experiment_blobs"         => { rows => undef,
				     tag   => "blobs",
				     row   => "blob"},
154 155 156 157 158 159 160 161 162 163 164 165
     "virt_blobs"               => { rows => undef,
				     tag   => "virt_blobs",
				     row   => "virt_blob"},
     "virt_client_service_ctl"  => { rows => undef,
				     tag   => "virt_client_service_ctl",
				     row   => "virt_client_service_ctlrow"},
     "virt_client_service_hooks"=> { rows => undef,
				     tag   => "virt_client_service_hooks",
				     row   => "virt_client_service_hook"},
     "virt_client_service_opts" => { rows => undef,
				     tag   => "virt_client_service_opts",
				     row   => "virt_client_service_opt"},
166 167 168 169 170 171
     "virt_blockstores"		=> { rows  => undef,
				     tag   => "blockstores",
				     row   => "blockstore"},
     "virt_blockstore_attributes" => { rows  => undef,
				       tag   => "virt_blockstore_attributes",
				       row   => "virt_blockstore_attribute"},
172 173 174
     "virt_address_allocation"  => { rows  => undef,
				     tag   => "virt_address_allocation",
				     row   => "virt_address_allocation"},
175

176 177 178
     # This is a fake table. See below. If we add more, lets generalize.
     "external_sourcefiles"	=> { rows  => undef, 
				     tag   => "nsfiles",
179
				     row   => "nsfiles"},
180
     );
181

182 183 184 185 186 187 188 189
# New parsing code state machine control.
my $PARSING_NOTYET	= 0;
my $PARSING_EXPERIMENT	= 1;
my $PARSING_TABLE	= 2;
my $PARSING_ROW		= 3;
my $PARSING_SLOT	= 4;
my $parserstate		= $PARSING_NOTYET;

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
#
# Turn off line buffering on output
#
$| = 1;

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

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
207
use libArchive;
208
use Experiment;
209
use VirtExperiment;
210

211 212
sub fatal($);

213 214 215 216 217 218 219 220 221 222 223
#
# Parse command arguments. Once we return from getopts, all that should
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
224 225 226
if (defined($options{"p"})) {
    $fromparser = 1;
}
227 228 229
if (defined($options{"s"})) {
    $simparse = 1;
}
230 231 232 233 234 235 236 237 238 239 240
if (defined($options{"x"})) {
    $fromxml = 1;
    $xmlfile = $options{"x"};

    if ($xmlfile =~ /^([-\w\/\.]+)$/) {
	$xmlfile = $1;
    }
    else {
	fatal("Bad data in argument: $xmlfile.");
    }
    if (defined($options{"n"})) {
241
	$impotent = 1;
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
    }    
}
if (@ARGV != 2) {
    usage();
}
$pid   = $ARGV[0];
$eid   = $ARGV[1];

# Taint Check.
if ($pid =~ /^([-\w]+)$/) {
    $pid = $1;
}
else {
    fatal("Bad data in argument: $pid.");
}
if ($eid =~ /^([-\w]+)$/) {
    $eid = $1;
}
else {
    fatal("Bad data in argument: $eid.");
}

264 265 266 267 268 269 270
my $experiment = Experiment->Lookup($pid, $eid);
if (!defined($experiment)) {
    die("*** $0:\n",
	"    Experiment $pid/$eid is not a current experiment!\n");
}
my $exptidx = $experiment->idx();

271
# Do it
272
sub readXML($$$$$);
273 274
sub writeXML_XML($$);

275
if ($fromxml) {
276
    readXML($exptidx, $pid, $eid, $xmlfile, $fromparser);
277 278
}
else {
279
    writeXML_XML($pid, $eid);
280 281 282 283 284 285 286 287
}
exit(0);

#
# Read in XML and convert to DB representation, doing lots of checks!
# This code is silly. Overly stylized (one tag per line!). Should
# use the XML::Parser package instead. But this was easy and fun for a
# first cut. 
288 289 290 291 292 293 294 295
#
# State variables for parsing code below.
my $current_expt;
my $current_table;
my $current_row;
my $current_slot;
my $current_data;

296 297
sub readXML($$$$$) {
    my ($exptidx, $pid, $eid, $xmlfile, $fromparser) = @_;
298 299 300 301 302 303 304
    my %experiment;

    if ($xmlfile ne "-") {
	open(STDIN, "< $xmlfile")
	    or fatal("opening $xmlfile for STDIN: $!");
    }

305
    if ($fromparser) {
306 307 308 309 310 311 312 313 314 315 316 317
	my $line = <STDIN>;
	
	# Scan for the beginning marker or EOF.
	while ($line && ($line ne "#### BEGIN XML ####\n")) {
	    print "$line"; # Print it out for the user.
	    $line = <STDIN>;
	}
	
	if (!$line) {
	    fatal("NS script never reached \"\$ns run\"");
	}
	
318 319 320 321
	#
	# Create a parser.
	#
	my $parser = new XML::Parser(Style => 'Tree');
322 323
	$parser->setHandlers('Start'   => \&StartElement_FromParser,
			     'End'     => \&EndElement_FromParser,
324 325 326 327 328 329 330
			     'Char'    => \&ProcessElement);

	fatal($@)
	    if (eval { $parser->parse(*STDIN); return 1; } != 1);
    }
    else {
	#
331
	# Create a parser.
332
	#
333 334 335 336
	my $parser = new XML::Parser(Style => 'Tree');
	$parser->setHandlers('Start'   => \&StartElement,
			     'End'     => \&EndElement,
			     'Char'    => \&ProcessElement);
337

338 339
	fatal($@)
	    if (eval { $parser->parse(*STDIN); return 1; } != 1);
340
    }
341

342 343 344 345 346 347 348 349
    #
    # Create a virt topology object. We do not load the current tables
    # since that is a waste of work.
    #
    my $virtexperiment = VirtExperiment->CreateNew($experiment);
    fatal("Could not create virtual experiment object")
	if (!defined($virtexperiment));

350
    # If these are the results of parsing the nse specifications,
351
    # we do not expect to get updates to the experiments table.
352 353 354 355 356 357 358 359
    if ( ! $simparse ) {
	#
	# Verify. 
	#
	# Must be exactly one experiments table row, and we prune out lots
	# of stuff that is not allowed. Note that we never insert a
	# experiment, but only allow updates of certain values. 
	#
360
	if (scalar(@{ $virtual_tables{"experiments"}->{"rows"} }) != 1) {
361 362
	    fatal("Must be exactly one experiments table row!");
	}
363 364 365 366 367 368 369 370
    }

    #
    # Okay, a hokey DoS check. Do not allow more than 10000 total rows!
    # Why so many? Well, Rob likes to generate lots of events!
    #
    my $count = 0;
    foreach my $table (keys(%virtual_tables)) {
371 372
	$count += scalar(@{$virtual_tables{$table}->{"rows"}})
	    if (defined($virtual_tables{$table}->{"rows"}));
373
    }
374
    if ($count > 100000) {
375 376 377 378 379
	fatal("Too many rows of data!");
    }

    #
    # Okay, thats all the checking we do! There is not much that can
380
    # screw up the DB just by inserting rows into the allowed set of
381 382
    # virtual experiment tables, since we ignore dangerous fields in
    # the xml.
383
    #
384
    # First update the experiments table part of the virt experiment.
385
    #
386 387
    if (!$simparse) {
	my %table = %{@{$virtual_tables{"experiments"}->{"rows"}}[0]};
388

389 390
	foreach my $key (keys(%table)) {
	    my $val = $table{$key};
391

392 393 394
	    # Extra safety.
	    next
		if (!exists($VirtExperiment::experiment_fields{$key}));
395

396
	    $virtexperiment->$key($val);
397 398 399 400
	}
    }

    #
401
    # Now all the other tables.
402 403
    #
    foreach my $table (keys(%virtual_tables)) {
404
	# Don't want to muck with this table. Done above. 
405 406 407
	next
	    if ($table eq "experiments");

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
	#
	# The external_sourcefiles table is treated special. Might
	# become a real table later, once we decide if its useful.
	# 
	if ($table eq "external_sourcefiles") {
	    foreach my $rowref (@{$virtual_tables{$table}->{"rows"}}) {
		my %rowhash = %{ $rowref };

		# If no actual rows, then skip. Might happen.
		last
		    if (! scalar(keys(%rowhash)));

		if (exists($rowhash{'pathname'}) &&
		    defined($rowhash{'pathname'})) {
		    my $pathname = $rowhash{'pathname'};

424 425
		    $experiment->AddInputFile($pathname) == 0
			or fatal("Failed to add input file $pathname!");
426 427 428 429 430
		}
	    }
	    next;
	}

431
	next
432
	    if (!defined($virtual_tables{$table}->{"rows"}));
433

434
	foreach my $rowref (@{$virtual_tables{$table}->{"rows"}}) {
435 436
	    my %rowhash = %{ $rowref };

437
	    # If no actual data, then skip. Might happen.
438 439 440
	    last
		if (! scalar(keys(%rowhash)));

441 442 443 444
	    # New table row for data.
	    my $tablerow = $virtexperiment->NewTableRow($table, \%rowhash);
	    if (!defined($tablerow)) {
		fatal("Could not add new tablerow");
445 446 447
	    }
	}
    }
448 449 450 451 452 453 454 455 456 457 458 459 460
    $virtexperiment->Dump()
	if ($debug > 1);
	
    # Now store it.
    my $flags = 0;
    $flags |= $VirtExperiment::STORE_FLAGS_DEBUG
	if ($debug);
    $flags |= $VirtExperiment::STORE_FLAGS_IMPOTENT
	if ($impotent);
    $flags |= $VirtExperiment::STORE_FLAGS_SIMPARSE
	if ($simparse);
    $virtexperiment->Store($flags) == 0
	or fatal("Could not store new experiment topology");
461 462 463
    return 0;
}

464 465 466 467 468 469
#
# XML::Parser routines.
#
#
# Start an element.
# 
470
sub StartElement_FromParser ($$$)
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
{
    my ($expat, $element, %attrs) = @_;

    if ($element eq "virtual_experiment") {
	fatal("Out of sync at experiment start: $element")
	    if (defined($current_expt) ||
		defined($current_table) ||
		defined($current_row) ||
		defined($current_slot));
	$current_expt = "$pid/$eid";
	
	#
	# Sanity check pid/eid.
	#
	if ((exists($attrs{'pid'}) && $attrs{'pid'} ne $pid) ||
	    (exists($attrs{'eid'}) && $attrs{'eid'} ne $eid)) {
	    fatal("pid/eid mismatch!");
	}
    }
    elsif (exists($virtual_tables{$element})) {
	#
	# A new table start.
	#
	fatal("Out of sync at element start: $element")
	    if (!defined($current_expt) ||
		defined($current_table) ||
		defined($current_row) ||
		defined($current_slot));
	$current_table = $element;

501 502
	if (! defined($virtual_tables{$element}->{"rows"})) {
	    $virtual_tables{$element}->{"rows"} = [];
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
	}
	print "Starting new table: $element\n"
	    if ($debug);
    }
    elsif ($element eq "row") {
	fatal("Out of sync at row start: $element")
	    if (!defined($current_expt) ||
		!defined($current_table) ||
		defined($current_row) ||
		defined($current_slot));
	$current_row = {};
    }
    else {
	fatal("Out of sync at slot start: $element")
	    if (!defined($current_expt) ||
		!defined($current_table) ||
		!defined($current_row) ||
		defined($current_slot));
	$current_slot = $element;
	$current_data = "";
    }
}

#
# End an element.
# 
529
sub EndElement_FromParser ($$)
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
{
    my ($expat, $element) = @_;

    if ($element eq "virtual_experiment") {
	fatal("Out of sync at experiment start: $element")
	    if (!defined($current_expt) ||
		defined($current_table) ||
		defined($current_row) ||
		defined($current_slot));
	undef($current_expt);
    }
    elsif (exists($virtual_tables{$element})) {
	#
	# A table termination.
	#
	fatal("Out of sync at element end: $element")
	    if (!defined($current_expt) ||
		!defined($current_table) ||
		defined($current_row) ||
		defined($current_slot));
	undef($current_table);
    }
    elsif ($element eq "row") {
	fatal("Out of sync at row end: $element")
	    if (!defined($current_expt) ||
		!defined($current_table) ||
		!defined($current_row) ||
		defined($current_slot));

	print "Adding new row to table $current_table\n"
	    if ($debug);
	
562
	push(@{ $virtual_tables{$current_table}->{"rows"} }, $current_row);
563 564 565 566 567 568 569 570 571 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
	undef($current_row);
    }
    else {
	fatal("Out of sync at slot end: $element")
	    if (!defined($current_expt) ||
		!defined($current_table) ||
		!defined($current_row) ||
		!defined($current_slot));
    
	#
	# Always ignore pid/eid.
	#
	if ($current_slot ne "pid" && $current_slot ne "eid") {
	    print "    Entering new slot: $current_slot: $current_data\n"
		if ($debug);
	    $current_row->{$current_slot} = $current_data;
	}
	undef($current_slot);
	undef($current_data);
    }
}

#
# Process stuff inside a slot.
# 
sub ProcessElement ($$)
{
    my ($expat, $string) = @_;

    if (defined($current_slot)) {
	$current_data .= xmldecode($string);
    }
}

597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 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 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
#
# Start an element.
#
sub StartElement ($$$)
{
    my ($expat, $element, %attrs) = @_;

    #
    # First element must be the experiment tag; It starts the process.
    #
    if ($parserstate == $PARSING_NOTYET) {
	fatal("Must start with an experiment tag!")
	    if ($element ne "experiment");

	fatal("Out of sync at experiment start: $element")
	    if (defined($current_expt) ||
		defined($current_table) ||
		defined($current_row) ||
		defined($current_slot));
	$current_expt = "$pid/$eid";
	
	#
	# Sanity check pid/eid.
	#
	if ((exists($attrs{'pid'}) && $attrs{'pid'} ne $pid) ||
	    (exists($attrs{'eid'}) && $attrs{'eid'} ne $eid)) {
	    fatal("pid/eid mismatch!");
	}
	print "Starting new experiment $pid/$eid\n"
	    if ($debug);
	
	$parserstate = $PARSING_EXPERIMENT;
    }
    elsif ($parserstate == $PARSING_EXPERIMENT) {
	#
	# Need to find the right table.
	#
	my $table;
	
	foreach my $key (keys(%virtual_tables)) {
	    if ($virtual_tables{$key}->{"tag"} eq $element) {
		$table = $key;
		last;
	    }
	}
	fatal("Unknown table: $element")
	    if (!defined($table));

	fatal("Out of sync at table start: $element")
	    if (!defined($current_expt) ||
		defined($current_table) ||
		defined($current_row) ||
		defined($current_slot));
	
	if (! defined($virtual_tables{$table}->{"rows"})) {
	    $virtual_tables{$table}->{"rows"} = [];
	}
	$current_table = $table;
	$parserstate   = $PARSING_TABLE;

	print "Starting new table: $table\n"
	    if ($debug);

	# Skip to parsing a row.
	if (!defined($virtual_tables{$current_table}->{"row"})) {
	    $current_row = {};
	    $parserstate = $PARSING_ROW;
	}
    }
    elsif ($parserstate == $PARSING_TABLE) {
	#
	# A row in a table. row tag must match table tag.
	#
	fatal("Out of sync at row start: $element")
	    if ((!defined($current_expt) ||
		 !defined($current_table) ||
		 defined($current_row) ||
		 defined($current_slot)) ||
		$virtual_tables{$current_table}->{"row"} ne $element);

	print "Starting new row at $element in table: $current_table\n"
	    if ($debug);
	
	$current_row = {};
	$parserstate = $PARSING_ROW;
    }
    elsif ($parserstate == $PARSING_ROW) {
	#
	# A slot in a row.
	# 
	fatal("Out of sync at slot start: $element")
	    if (!defined($current_expt) ||
		!defined($current_table) ||
		!defined($current_row) ||
		defined($current_slot));

	print "Starting new slot $element in table: $current_table\n"
	    if ($debug);
	
	$parserstate  = $PARSING_SLOT;
	$current_slot = $element;
	$current_data = "";
    }
    else {
	fatal("Out of sync at element: $element");
    }
}

#
# End an element.
# 
sub EndElement ($$)
{
    my ($expat, $element) = @_;

    if ($parserstate == $PARSING_EXPERIMENT) {
	fatal("Out of sync at experiment start: $element")
	    if ($element ne "experiment" ||
		(!defined($current_expt) ||
		 defined($current_table) ||
		 defined($current_row) ||
		 defined($current_slot)));
	undef($current_expt);
	$parserstate = $PARSING_NOTYET;
    }
    elsif ($parserstate == $PARSING_TABLE) {
	#
	# A table termination.
	#
	fatal("Out of sync at element end: $element")
	    if ((!defined($current_expt) ||
		 !defined($current_table) ||
		 defined($current_row) ||
		 defined($current_slot)) ||
		$element ne $virtual_tables{$current_table}->{"tag"});
	undef($current_table);
	$parserstate = $PARSING_EXPERIMENT;
    }
    elsif ($parserstate == $PARSING_ROW) {
	#
	# A row termination.
	# 
	fatal("Out of sync at row end: $element")
	    if ((!defined($current_expt) ||
		 !defined($current_table) ||
		 !defined($current_row) ||
		 defined($current_slot)) ||
		(defined($virtual_tables{$current_table}->{"row"}) &&
		 $element ne $virtual_tables{$current_table}->{"row"}));
		
	print "Adding new row $element to table $current_table\n"
	    if ($debug);
	
	push(@{ $virtual_tables{$current_table}->{"rows"} }, $current_row);
	undef($current_row);
	$parserstate = $PARSING_TABLE;

	# Skip to parsing an experiment
	if (!defined($virtual_tables{$current_table}->{"row"})) {
	    undef($current_table);
	    $parserstate = $PARSING_EXPERIMENT;
	}
    }
    elsif ($parserstate == $PARSING_SLOT) {
	#
	# A slot termination.
	# 
	fatal("Out of sync at slot end: $element")
	    if (!defined($current_expt) ||
		!defined($current_table) ||
		!defined($current_row) ||
		!defined($current_slot));
    
	#
	# Always ignore pid/eid.
	#
	if ($current_slot ne "pid" && $current_slot ne "eid") {
	    print "    Entering new slot: $current_slot: $current_data\n"
		if ($debug);
	    $current_row->{$current_slot} =
		($current_data ne "__NULL__" ? $current_data : undef);
	}
	undef($current_slot);
	undef($current_data);
	$parserstate = $PARSING_ROW;
    }
}

785 786 787 788
#
# Convert a virtual experiment representation into XML and spit it out.
# The DB holds the data of course.
#
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
sub writeXML_XML($$) {
    my ($pid, $eid) = @_;

    my $query_result =
	DBQueryFatal("select * from experiments ".
		     "where eid='$eid' and pid='$pid'");

    if (! $query_result->numrows) {
	fatal("No such experiment $pid/$eid exists!");
    }

    spitxml_header();
    spitxml_opentag("experiment pid='$pid' eid='$eid'", 0);
    spitxml_opentag("settings", 1);
    spitxml_spaces(2);
    
    my $settings = $query_result->fetchrow_hashref();

    foreach my $key (keys(%{ $settings })) {
	my $data = $settings->{$key};
	
	spitxml_entity($key, $data, 0);
    }
    spitxml_closetag("settings", 1);

    #
    # Read in a set of tables that live at top level.
    # 
    foreach my $table (keys(%virtual_tables)) {
	next
819
	    if ($table eq "experiments" || $table eq "external_sourcefiles");
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
	
	my $tabletag = $virtual_tables{$table}->{"tag"};
	my $rowtag   = $virtual_tables{$table}->{"row"};

	$query_result =
	    DBQueryFatal("select * from $table ".
			 "where eid='$eid' and pid='$pid'");

	next
	    if (! $query_result->numrows);

	spitxml_opentag($tabletag, 1);
	
	while (my $rowref = $query_result->fetchrow_hashref()) {
	    spitxml_opentag($rowtag, 2);
	    spitxml_spaces(3);

	    foreach my $key (keys(%{ $rowref })) {
		my $data = $rowref->{$key};

		next
		    if ($key eq "pid" || $key eq "eid");

		spitxml_entity($key, $data, 0);
	    }
	    print "\n";
	    spitxml_closetag($rowtag, 2);
	}
	spitxml_closetag($tabletag, 1);
    }

    spitxml_closetag("experiment", 0);
    return 0;
}

#
# This is the old version; I will eventually remove it. 
#
sub writeXML_RPC($$) {
859 860 861 862 863 864 865 866 867
    my ($pid, $eid) = @_;

    my $query_result =
	DBQueryFatal("select * from experiments ".
		     "where eid='$eid' and pid='$pid'");

    if (! $query_result->numrows) {
	fatal("No such experiment $pid/$eid exists!");
    }
868 869
    my $exp = {};
    $exp->{"experiment"}->{"settings"} = $query_result->fetchrow_hashref();
870

871 872 873
    foreach my $key (keys(%{ $exp->{"experiment"}->{"settings"} })) {
	$exp->{"experiment"}->{"settings"}->{$key} = ""
	    if (!defined($exp->{"experiment"}->{"settings"}->{$key}));
874 875
    }

876 877 878 879 880 881 882 883
    #
    # Read in a set of tables that live at top level.
    # 
    foreach my $table (keys(%virtual_tables)) {
	next
	    if ($table eq "experiments");
	
	my $tag = $virtual_tables{$table}{"tag"};
884

885 886 887 888 889 890 891 892 893 894 895 896 897 898
	if (!exists($exp->{"experiment"}->{$tag})) {
	    $exp->{"experiment"}->{$tag} = [];
	}
	$query_result =
	    DBQueryFatal("select * from $table ".
			 "where eid='$eid' and pid='$pid'");

	while (my $rowref = $query_result->fetchrow_hashref()) {
	    foreach my $key (keys(%{ $rowref })) {
		$rowref->{$key} = ""
		    if (!defined($rowref->{$key}));
	    }
	    push(@{ $exp->{"experiment"}->{$tag} }, $rowref);
	}
899 900
    }

901 902
    my $foo = new RPC::XML::response($exp);
    print $foo->as_string();
903
    
904
    return 0;
905 906
}

907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
#
# Utility functions to pretty print XML output, with specified indentation.
#
sub spitxml_spaces($)
{
    my ($level) = @_;

    my $spaces = $level * 1;

    printf("%${spaces}s", "");
}
    
sub spitxml_opentag($$)
{
    my ($tag, $level) = @_;

    spitxml_spaces($level);
    print "<${tag}>\n";
}

sub spitxml_closetag($$)
{
    my ($tag, $level) = @_;

    spitxml_spaces($level);
    print "</${tag}>\n";
}

sub spitxml_header()
{
    print "$XMLHEADER\n";
}

sub spitxml_entity($$$)
{
    my ($tag, $data, $level) = @_;

    $data = "__NULL__"
	if (!defined($data));

    spitxml_spaces($level)
	if ($level);

    if ($data eq "") {
	print "<${tag}/>";
    }
    else {
	print "<${tag}>" . xmlencode($data) . "</${tag}>";
    }
}

958 959 960 961 962 963 964 965 966 967
#
# Convert from/to XML special chars. Not many of them ...
# 
sub xmlencode($)
{
    my ($string) = @_;

    my %specialchars = ('&' => '&amp;',
			'<' => '&lt;',
			'>' => '&gt;',
968 969 970
			"'" => '&#39;',
			"]" => '&#93;',
			'"' => '&#34;');
971 972 973 974 975 976 977 978 979 980 981 982

    $string =~ s/([&<>"'])/$specialchars{$1}/ge;
    return $string;
}

sub xmldecode($)
{
    my ($string) = @_;

    my %specialchars = ('&amp;'  => '&',
			'&lt;'   => '<',
			'&gt;'   => '>',
983 984 985
			'&#39;'  => "'",
			'&#93;'  => ']',
			'&#34;'  => '"');
986 987 988 989 990 991 992 993 994 995 996 997 998

    $string =~ s/(&\w+;)/$specialchars{$1}/ge;
    return $string;
}

# Die
sub fatal($)
{
    my ($msg) = @_;

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