instantiate.ajax 38.9 KB
Newer Older
1 2
<?php
#
3
# Copyright (c) 2000-2018 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 23 24 25 26 27
# 
# {{{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/>.
# 
# }}}
#
chdir("..");
include_once("webtask.php");
chdir("apt");
include_once("profile_defs.php");
28
include_once("instance_defs.php");
29

30 31 32
# Need to make non-hardcoded
$maxduration = 16;

33 34 35 36 37 38 39
#
# Return info about specific profile.
#
function Do_GetProfile()
{
    global $this_user;
    global $ajax_args;
40
    global $DEFAULT_AGGREGATE;
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
    
    if (!isset($ajax_args["uuid"])) {
	SPITAJAX_ERROR(1, "Missing profile uuid");
	return;
    }
    $uuid = $ajax_args["uuid"];
    if (!IsValidUUID($uuid)) {
	SPITAJAX_ERROR(1, "Not a valid UUID: $uuid");
	return;
    }
    $profile = Profile::Lookup($uuid);
    if (!$profile) {
	SPITAJAX_ERROR(1, "No such profile $uuid");
	return;
    }
56 57 58 59 60
    $amdefault = $DEFAULT_AGGREGATE;
    # Temporary override until constraint system in place.
    if ($profile->BestAggregate()) {
	$amdefault = $profile->BestAggregate();
    }
61
    $ispp = ($profile->isParameterized() ? 1 : 0);
62
    list ($lastused, $count) = $profile->UsageInfo($this_user);
63
    
64
    #
65 66
    # Knowing the UUID means the user can instantiate it,
    # so no permission checks on the profile. 
67 68
    #
    SPITAJAX_RESPONSE(array('rspec'       => $profile->rspec(),
69
			    'name'        => $profile->name(),
70
                            'pid'         => $profile->pid(),
71 72 73 74 75
                            'version'     => $profile->version(),
                            'lastused'    => $lastused,
                            'usecount'    => $count,
                            'creator'     => $profile->creator(),
                            'created'     => $profile->created(),
76
			    'ispprofile'  => $ispp,
77
                            'isscript'    => ($profile->script() ? 1 : 0),
78
                            'fromrepo'    => ($profile->repourl() ? 1 : 0),
79 80 81
                            'repohash'    => ($profile->repourl() ?
                                              substr($profile->repohash(),0,8)
                                              : ""),
82
			    'amdefault'   => $amdefault));
83
}
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

#
# Return parameter form fragment and default values.
#
function Do_GetParameters()
{
    global $this_user;
    global $ajax_args;
    global $suexec_output, $suexec_output_array;

    if (!isset($ajax_args["uuid"])) {
	SPITAJAX_ERROR(1, "Missing profile uuid");
	return;
    }
    $profile = Profile::Lookup($ajax_args["uuid"]);
    if (!$profile) {
	SPITAJAX_ERROR(1, "Unknown profile uuid");
	return;
    }
    if (!isset($this_user)) {
	if (!$profile->ispublic()) {
	    SPITAJAX_ERROR(1, "Not enough permission to instantiate profile");
	    return;
	}	    
    }
109
    elseif (! ($profile->CanInstantiate($this_user) || ISADMIN())) {
110 111 112
	SPITAJAX_ERROR(1, "Not enough permission to instantiate profile");
	return;
    }
113 114 115 116 117 118 119 120 121
    #
    # For a repo-based profile, the paramdefs will be passed in.
    # Note that different refspecs might be parameterized, but others not.
    #
    if ($profile->repourl() &&
        isset($ajax_args["paramdefs"]) && $ajax_args["paramdefs"] != "") {
        $paramdefs = $ajax_args["paramdefs"];
    }
    elseif (!$profile->isParameterized()) {
122 123 124
	SPITAJAX_ERROR(1, "Not a parameterized profile");
	return;
    }
125 126 127 128
    else {
        $paramdefs = $profile->paramdefs();
    }
    list ($formfrag, $defaults) = $profile->GenerateFormFragment($paramdefs);
129 130 131 132 133 134 135 136 137
    SPITAJAX_RESPONSE(array("formfrag" => htmlentities($formfrag),
			    "defaults" => $defaults));
}

#
# Instantiate profile (as the user)
#
function Do_Instantiate()
{
138 139
    SPITAJAX_ERROR(1, "This interface is deprecated");
    return;
140 141
}

142 143 144 145
function ImagesWhere($where, $dblink)
{
    $result = array();
    $query_result = DBQueryFatal(
146
      "select i.urn, v.description, v.version, v.deprecated is not NULL, v.deprecated_message, v.types_known_working from ".
147
      "image_versions as v left join images as i on ".
148
      "v.urn=i.urn ".$where." and (deprecated is NULL or deprecated_iserror=0)",
149 150 151 152 153
    $dblink);
    while ($row = mysql_fetch_array($query_result)) {
      array_push($result, array(
          'urn' => $row[0],
          'description' => $row[1],
154 155 156 157
          'version' => $row[2],
	  'deprecated' => $row[3],
	  'deprecated_messsage' => $row[4],
	  'types' => $row[5]));
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    }
    return $result;
}

function Do_GetImageList()
{
    global $this_user;
    global $ajax_args;
    $dblink = DBConnect("ims");
    $systemProject = 'emulab-ops';
    $myImages = array();
    $projectImages = array();
    $systemImages = array();
    $publicImages = array();
    if ($this_user && $this_user->webonly()) {
        # Only public images
	$publicImages = ImagesWhere("where v.visibility='public' and i.project_urn not like '%$systemProject+authority+sa'", $dblink);
175
	$systemImages = ImagesWhere("where i.project_urn like '%$systemProject+authority+sa' and v.deprecated is NULL", $dblink);
176 177 178 179 180
    } else if ($this_user) {
	$user_urn = addslashes($this_user->urn());
	# Public images that weren't created by the user
	$publicImages = ImagesWhere("where v.visibility='public' and i.project_urn not like '%$systemProject+authority+sa' and v.creator_urn != '$user_urn'", $dblink);
	# System images that weren't created by the user
181
	$systemImages = ImagesWhere("where v.visibility='public' and i.project_urn like '%$systemProject+authority+sa' and v.creator_urn != '$user_urn' and v.deprecated is NULL", $dblink);
182 183 184 185 186 187 188 189 190 191 192
        # All images for user
	$myImages = ImagesWhere("where v.creator_urn='$user_urn'", $dblink);
    }
    $result = array(array("my-images" => $myImages,
                          "project" => $projectImages,
			  "system" => $systemImages,
			  "public" => $publicImages));
    
    SPITAJAX_RESPONSE($result);
}

193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
#
# Return constraint info for a set of images.
#
function Do_GetImageInfo()
{
    global $this_user;
    global $ajax_args;

    if (!isset($ajax_args["images"])) {
	SPITAJAX_ERROR(1, "Missing image list");
	return;
    }
    if ($this_user && !$this_user->webonly()) {
        if (!isset($ajax_args["project"])) {
            SPITAJAX_ERROR(1, "Missing project selection");
            return;
        }
        $pid = $ajax_args["project"];
Leigh Stoller's avatar
Leigh Stoller committed
211
        if (!preg_match("/^[-\w]+$/", $pid)) {
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
            SPITAJAX_ERROR(1, "Illegal project name: $pid");
            return;
        }
        $project = Project::Lookup($pid);
        if (!$project) {
            SPITAJAX_ERROR(1, "No such project: $pid");
            return;
        }
        $approved = 0;
        if (! (ISADMIN() ||
               ($project->IsMember($this_user, $approved) && $approved))) {
            SPITAJAX_ERROR(1, "Not a member of project: $pid");
            return;
        }
    }
    $dblink = DBConnect("ims");

    $constraints = array();
    $images      = array();

    foreach ($ajax_args["images"] as $urn) {
233 234
        $types = array();
        $virts = array();
235
        $deprecated = 0;
236
        
237 238 239 240 241 242 243 244 245 246 247 248 249
        if (Instance::ValidURN($urn)) {
            # This // vs : thing is a pain.
            $urn = preg_replace('/\/\//', ":", $urn);
            # Need to see if there is a specific version.
            list ($auth,$type,$id) = Instance::ParseURN($urn);
            list ($proj,$name,$version) = preg_split('/:/', $id);

            #
            # Lookup is without the version number in the urn.
            #
            $urn = preg_replace('/:\d+$/', "", $urn);
            $safe_urn = addslashes($urn);
            if (is_null($version)) {
250
                if ($proj == "emulab-ops") {
251 252
                    $safe_urn = addslashes("urn:publicid:IDN+%+image+${id}");
                    $innerclause = "innerclause.urn like '$safe_urn'";
253 254
                }
                else {
255
                    $innerclause = "innerclause.urn='$safe_urn'";
256
                }
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
                $query_result = DBQueryFatal(
                    "(select i.*,v.* from image_versions as v ".
                    "  inner join ".
                    "    (select iv.urn,max(version) as version ".
                    "       from image_aliases as innerclause ".
                    "     left join image_versions as iv on ".
                    "           iv.urn=innerclause.target_urn ".
                    "     where $innerclause ".
                    "     group by iv.urn) as ij ".
                    "  on v.urn=ij.urn and v.version=ij.version ".
                    " left join images as i on i.urn=v.urn) ".
                    "union ".
                    "(select i.*,v.* from image_versions as v ".
                    "   inner join ".
                    "      (select urn,max(version) as version ".
                    "         from image_versions as innerclause ".
                    "       where $innerclause ".
                    "       group by urn) as ij ".
                    "   on v.urn=ij.urn and v.version=ij.version ".
                    " left join images as i on i.urn=v.urn)", $dblink);
277 278 279
            }
            else {
                $query_result =
280
                    DBQueryFatal("select i.*,v.* from image_versions as v ".
281 282 283 284
                                 "left join images as i on ".
                                 "     i.image_uuid=v.image_uuid ".
                                 "where v.urn='$safe_urn' and ".
                                 "      v.version='$version'",
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
                                $dblink);
            }
        }
        elseif (parse_url($urn)) {
            #
            # Or it must be a URL.
            #
            $safe_url = addslashes($urn);

            $query_result = 
                DBQueryWarn("select i.*,v.* from image_versions as v ".
                            "left join images as i on ".
                            "     i.image_uuid=v.image_uuid ".
                            "where v.metadata_url='$safe_url'",
                            $dblink);
300 301 302 303 304 305 306 307 308 309 310 311 312

            if ($query_result && !mysql_num_rows($query_result)) {
                #
                # See if the url is for the image instead of a specific
                # version. 
                #
                $query = parse_url($urn, PHP_URL_QUERY);
                if ($query) {
                    parse_str($query, $args);
                    if (isset($args["uuid"]) && IsValidUUID($args["uuid"])) {
                        $uuid = $args["uuid"];

                        $query_result =
313
                            DBQueryFatal("select i.*,v.* ".
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
                                 "  from image_versions as v ".
                                 "   inner join ".
                                 "      (select image_uuid, ".
                                 "              max(version) as version ".
                                 "         from image_versions ".
                                 "       where image_uuid='$uuid' ".
                                 "       group by image_uuid) as ij ".
                                 "   on v.image_uuid=ij.image_uuid and ".
                                 "      v.version=ij.version ".
                                 "left join images as i on ".
                                 "     i.image_uuid=v.image_uuid",
                                 $dblink);
                    }
                }
            }
329 330 331 332 333 334 335 336
        }
        else {
            continue;
        }
        if (!$query_result || !mysql_num_rows($query_result)) {
            # Is this the right thing to do?
            continue;
        }
337
        while ($row = mysql_fetch_array($query_result)) {
338
            #
339 340 341
            # Need to look at the privacy setting, and if the image is not
            # public, the user has to be in the same project as the image
            # (or own the image), or it has to be listed in the permissions.
342
            #
343 344 345 346 347 348 349 350 351 352 353 354 355
            if ($row["visibility"] != "public") {
                # This will not be set for guests.
                if (!isset($project)) {
                    continue;
                }
            
                #
                # Project selection box has to match the project the image
                # belongs too. If the user changes the project selection, we
                # have to rerun the constraints.
                #
                list ($auth) = Instance::ParseURN($row["project_urn"]);
                list ($domain,$impid) = preg_split('/:/', $auth);
356
                if ($impid && strtolower($impid) == strtolower($pid)) {
357 358
                    goto allowed;
                }
359

360
                #
Leigh Stoller's avatar
Leigh Stoller committed
361 362 363 364
                # Check special permissions. Note that I do not do an
                # ISADMIN() check since that does not travel with the
                # user via the geni API, so it would just fail on the
                # backend anyway.
365 366 367 368 369
                #
                $perms_result =
                    DBQueryWarn("select * from image_permissions ".
                                "where urn='" . addslashes($row["urn"]) . "'",
                                $dblink);
370

371 372 373 374 375 376 377 378 379
                while ($prow = mysql_fetch_array($perms_result)) {
                    $ptype = $prow["permission_type"];
                    $purn  = $prow["permission_urn"];
                    
                    if ($ptype == "user") {
                        list ($ign1,$ign2,$id) = Instance::ParseURN($purn);
                        if ($id && $id == $this_user->uid()) {
                            goto allowed;
                        }
380
                    }
381 382 383 384 385 386
                    elseif ($ptype == "project") {
                        list ($auth) = Instance::ParseURN($purn);
                        list ($domain,$ppid) = preg_split('/:/', $auth);
                        if ($ppid && $ppid == $pid) {
                            goto allowed;
                        }
387 388
                    }
                }
389
                continue;
390
            }
391 392 393 394 395 396
     allowed:
	    foreach (preg_split("/,/", $row["types_known_working"]) as $type) {
                $types[$type] = $type;
	    }
            $virts[$row["virtualizaton"]] = $row["virtualizaton"];
            $description = $row["description"];
397 398 399 400 401 402 403 404
            #
            # I suppose an alias can point to a deprecated image.
            #
            if ($row["deprecated"]) {
                $deprecated  = $row["deprecated"];
                $deprecated_iserror = $row["deprecated_iserror"];
                $deprecated_message = $row["deprecated_message"];
            }
405
        }
406
        if (count($types)) {
407 408 409
            if (isset($types["pcvm"])) {
                $virts["emulab-xen"] = "emulab-xen";
            }
410 411 412
            # These are reversed from what they should mean!
            $typelist = implode(",", array_keys($types));
            $virtlist = implode(",", array_keys($virts));
413

414 415 416 417 418 419 420 421 422
            $constraints[] =
                array("node" =>
                      array("images" => array($urn),
                            "types"  => array($virtlist)));
            $constraints[] =
                array("node" =>
                      array("images"   => array($urn),
                            "hardware" => array($typelist)));

423 424 425 426 427 428 429 430 431 432 433
            $im = array("id"   => $urn,
                        "name" => $description,
                        "deprecated" => false);
            if ($deprecated) {
                $im["deprecated"] = $deprecated;
                $im["deprecated_iserror"] = ($deprecated_iserror ? true:false);
                $im["deprecated_message"] = $deprecated_message;
            }
            else {
            }
            $images[] = $im;
434
        }
435 436 437 438 439 440 441
    }
    $result = array(array("constraints" => $constraints,
                          "images" => $images));
    
    SPITAJAX_RESPONSE($result);
}

442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
#
# Allow for checking at each step, although at the moment we
# do notreally do this.
#
function Do_CheckForm()
{
    global $ajax_args;

    if (!isset($ajax_args["step"])) {
	SPITAJAX_ERROR(-1, "Missing step number");
	return -1;
    }
    if ($ajax_args["step"] == 0) {
        if (CheckStep0() == 0) {
            SPITAJAX_RESPONSE(0);
        }
    }
    if ($ajax_args["step"] == 2) {
        if (CheckStep2() == 0) {
            SPITAJAX_RESPONSE(0);
        }
    }
464 465 466 467 468
    if ($ajax_args["step"] == 3) {
        if (CheckStep3() == 0) {
            SPITAJAX_RESPONSE(0);
        }
    }
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 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 529 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 562 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 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
}

#
# Check form arguments on the fist step, so we can halt progress
# right away.
#
function CheckStep0()
{
    global $this_user;
    global $ajax_args;
    global $APTMAIL;

    if (!isset($ajax_args["formfields"])) {
	SPITAJAX_ERROR(-1, "Missing formfields");
	return -1;
    }
    $formfields = $ajax_args["formfields"];
    $errors = array();

    #
    # There is nothing to do for registered users.
    #
    if ($this_user) {
        return 0;
    }
    # For email verification if needed.
    session_start();

    if (!isset($formfields["email"]) || $formfields["email"] == "") {
        $errors["email"] = "Missing Field";
    }
    elseif (! TBvalid_email($formfields["email"])) {
        $errors["email"] = TBFieldErrorString();
    }
    if (!isset($formfields["username"]) ||
        $formfields["username"] == "") {
        $errors["username"] = "Missing Field";
    }
    elseif (! TBvalid_uid($formfields["username"])) {
        $errors["username"] = TBFieldErrorString();
    }
    elseif (User::LookupByUid($formfields["username"])) {
        # Do not allow uid overlap with real users.
        $errors["username"] = "Already in use - ".
            "if you have an Emulab account, log in first";
    }
    else {
        if (!isset($_SESSION["verified"])) {
            $_SESSION["verified"] = 0;
            $_SESSION["codesent"] = 0;
        }
        $geniuser = GeniUser::LookupByEmail("sa", $formfields["email"]);
        if ($geniuser) {
            if ($geniuser->name() != $formfields["username"]) {    
                $errors["email"] = "Already in use by another guest user";
                goto done;
            }
            if (isset($_COOKIE['quickvm_authkey']) &&
                $_COOKIE['quickvm_authkey'] == $geniuser->auth_token()) {
                $_SESSION["verified"] = 1;
            }
            else {
                # Store existing token in session for below.
                $_SESSION["auth_token"] = $geniuser->auth_token();
                # Store user too, convenient for below.
                $_SESSION["geniuser"] = $geniuser->uuid();
            }
        }
        elseif (!isset($_SESSION["auth_token"])) {
            # Generate a new token for guest user to be created later.
            $_SESSION["auth_token"] = substr(GENHASH(), 0, 16);
        }
        #
        # If we need to verify and we have not sent the email, do so.
        #
        if (!$_SESSION["verified"] && !$_SESSION["codesent"]) {
	    mail($formfields["email"],
		 "aptlab.net: Verification code for creating your experiment",
		 "Here is your user verification code. Please copy and\n".
		 "paste this code into the box on the experiment page.\n\n".
		 "      " . $_SESSION["auth_token"] . "\n",
		 "From: $APTMAIL");
            $_SESSION["codesent"] = 1;
	}
        #
        # Tell caller to throw up the verification form.
        #
        if (!$_SESSION["verified"]) {
            SPITAJAX_ERROR(3, 0);
            return -1;
        }
    }
 done:
    if (count($errors)) {
	SPITAJAX_ERROR(2, $errors);
	return -1;
    }
    return 0;
}

#
# Check email verification token for guest users.
#
function Do_VerifyEmail()
{
    global $this_user;
    global $ajax_args;
    global $TBAUTHDOMAIN;
    # auth token stored in session above.
    session_start();

    #
    # See if user exists and is verified. We send email with a code, which
    # they have to paste back into a box we add to the form. See above.
    #
    # We also get here if the user exists, but the browser did not have
    # the tokens, as will happen if switching to another browser. We
    # force the user to repeat the verification with the same code we
    # have stored in the DB.
    #
    if ($_SESSION["verified"]) {
        SPITAJAX_RESPONSE(0);
        return;
    }
    if (!isset($ajax_args["token"])) {
	SPITAJAX_ERROR(-1, "Missing verification token argument");
	return;
    }
    if (!isset($_SESSION["auth_token"])) {
	SPITAJAX_ERROR(-1, "Internal error finding verification token");
	return;
    }
    if ($_SESSION["auth_token"] != $ajax_args["token"]) {
	SPITAJAX_ERROR(1, "Token did not match, please try again");
	return;
    }
    $blob = array();
    
    if (isset($_SESSION["geniuser"])) {
        $geniuser = GeniUser::Lookup("sa", $_SESSION["geniuser"]);
        if (!$geniuser) {
            SPITAJAX_ERROR(-1, "Internal error looking up geni user");
            return;
        }
        #
        # Reset the cookies so status page is happy and so we
        # will stop asking the user to verify their email.
        #
        $cookiedomain = $TBAUTHDOMAIN;
        $expires = time() + (24 * 3600 * 30);
        
        $blob["cookies"]
            = array("quickvm_user" =>
                    array("value"   => $geniuser->uuid(),
                          "expires" => $expires,
                          "domain"  => $cookiedomain),
                    "quickvm_authkey" =>
                    array("value"   => $geniuser->auth_token(),
                          "expires" => $expires,
                          "domain"  => $cookiedomain));
        
	#
	# If this is an existing user and they give us the right code,
	# we can check again for an existing experiment and redirect to the
	# status page.
	#
        $instance = Instance::LookupByCreator($geniuser->uuid());
        if ($instance && $instance->status() != "terminating") {
            $blob["redirect"] = "status.php?oneonly=1&uuid=" .
                $instance->uuid();
            SPITAJAX_RESPONSE($blob);
            session_destroy();
            return;
        }
    }
    $_SESSION["verified"] = 1;
    SPITAJAX_RESPONSE($blob);
}

function CheckStep2()
{
    global $this_user;
    global $ajax_args;
652
    global $ISAPT, $ISPNET, $ISCLOUD, $ISEMULAB, $ISPOWDER;
653
    global $TB_PROJECT_CREATEEXPT;
654 655 656 657 658 659

    if (!isset($ajax_args["formfields"])) {
	SPITAJAX_ERROR(-1, "Missing formfields");
	return -1;
    }
    $formfields = $ajax_args["formfields"];
660 661
    $amlist     = Instance::DefaultAggregateList();
    $am_array   = array();
662 663
    $errors     = array();

664 665 666 667 668 669
    while (list($index, $aggregate) = each($amlist)) {
        $urn  = $aggregate->urn();
        $name = $aggregate->name();
        $am_array[$name] = $urn;
    }

670
    session_start();
671 672 673 674 675 676 677 678 679 680 681 682 683
    #
    # The initial page load did profile checking, this is just a
    # secondary check, so if there are failures, we can show them
    # as a general error on the last step.
    #
    if (!isset($formfields["profile"]) || $formfields["profile"] == "") {
        $errors["error"] = "No profile selection made";
    }
    else {
        $profile = Profile::Lookup($formfields["profile"]);
        if (!$profile) {
            $errors["error"] = "No such profile exists";
        }
684 685 686 687 688 689
        #
        # Our permission model is that anyone who knows the uuid can
        # instantiate the profile, and either they provided the URL
        # in the URL or its a profile uuid they got from the instantiate
        # page via their permissions. So no checks here.
        #
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
    }
    if (!$this_user) {
        #
        # Need to make sure we got verified.
        #
        if (!isset($_SESSION["verified"]) || !$_SESSION["verified"]) {
            $errors["error"] = "Your verification step failed";
        }
    }
    if ($this_user) {
        if (isset($formfields["sites"]) && is_array($formfields["sites"])) {
            while (list($siteid, $am) = each($formfields["sites"])) {
                if (!array_key_exists($am, $am_array)) {
                    $errors["sites"] = "Invalid Aggregate: $siteid";
                    break;
                }
            }
        }
708
        elseif ($ISAPT || $ISPNET || $ISEMULAB || $ISPOWDER) {
709 710 711
            # No choice
            ;
        }
712 713 714 715 716 717 718
        elseif (!isset($formfields["fully_bound"]) ||
                $formfields["fully_bound"] == "0") {
            if (!(isset($formfields["where"]) &&
                  $formfields["where"] != "" &&
                  array_key_exists($formfields["where"], $am_array))) {
                $errors["where"] = "Missing aggregate selection";
            }
719 720 721 722 723
        }
        
        #
        # Project has to exist.  
        #
724 725 726 727
        if (!isset($formfields["pid"])) {
            $errors["pid"] = "Must select a project";
        }
        elseif (! ($project = Project::LookupByPid($formfields["pid"]))) {
728 729 730 731 732 733 734 735
            $errors["pid"] = "No such project";
        }
        # User better be a member.
        elseif (!ISADMIN() &&
                (!$project->IsMember($this_user, $isapproved) ||
                 !$isapproved)) {
            $errors["pid"] = "Illegal project";
        }
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
        elseif ($formfields["pid"] != $formfields["gid"]) {
            $group = $project->LookupSubgroupByName($formfields["gid"]);
            if (!$group) {
                $errors["gid"] = "No such group in selected project";
            }
            elseif (!$group->AccessCheck($this_user, $TB_PROJECT_CREATEEXPT)) {
                $errors["gid"] = "No permission to create experiments in ".
                               "selected group";
            }
        }
        else {
            $group = $project->DefaultGroup();
            if (!$group->AccessCheck($this_user, $TB_PROJECT_CREATEEXPT)) {
                $errors["pid"] = "No permission to create experiments in ".
                               "selected project";
            }
        }
753 754 755 756 757 758 759 760 761 762 763 764 765 766

        # Experiment name is optional, we generate one later.
        if (isset($formfields["name"]) && $formfields["name"] != "") {
            if (strlen($formfields["name"]) > 16) {
                $errors["name"] = "Too long; must be <= 16 characters";
            }
            elseif (!TBvalid_eid($formfields["name"])) {
                $errors["name"] = TBFieldErrorString();
            }
            elseif ($project &&
                    Instance::LookupByName($project, $formfields["name"])) {
                $errors["name"] = "Already in use by another experiment";
            }
        }
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
    }
    if (count($errors)) {
	SPITAJAX_ERROR(2, $errors);
	return -1;
    }
    return 0;
}
function CheckStep3()
{
    global $this_user;
    global $ajax_args;
    global $ISAPT, $ISPNET, $ISCLOUD, $ISEMULAB, $ISPOWDER;
    global $maxduration;
    $start = null;

    if (!isset($ajax_args["formfields"])) {
	SPITAJAX_ERROR(-1, "Missing formfields");
	return -1;
    }
    $formfields = $ajax_args["formfields"];
    session_start();
788

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 819 820 821 822 823 824 825
    #
    # Verify scheduled start time if not start immediately.
    #
    if (! (isset($formfields["start-immediately"]) &&
           $formfields["start-immediately"] == "checked")) {
        if (!isset($formfields["start"]) || $formfields["start"] == "") {
            $errors["error"] = "Missing UTC start time";
        }
        else {
            $start_ascii = $formfields["start"];
            $start = strtotime($formfields["start"]);
            if (!$start) {
                $errors["start"] = "Cannot parse UTC start time";
            }
            elseif ($start < time()) {
                $errors["start_day"] = "Start is in the past";
            }
        }
    }
    if (isset($formfields["end"]) && $formfields["end"] != "") {
        $end_ascii = $formfields["end"];
        $end = strtotime($formfields["end"]);
        if (!$end) {
            $errors["end"] = "Cannot parse UTC end time";
        }
        elseif ($end < time()) {
            $errors["end_day"] = "End is in the past";
        }
        elseif ($start && $end <= $start) {
            $errors["end_day"] = "End is before the start";
        }
        elseif (($start && $end < $start + 3600) ||
                $end < time() + 3600) {
            $errors["end_day"] = "Too short, must be > 1 hour";
        }
    }
    else {
826 827 828
        if (!isset($formfields["duration"]) || $formfields["duration"] == "") {
            $errors["duration"] = "Must set an experiment duration";
        }
829 830 831 832
        elseif (!ctype_digit($formfields["duration"]) ||
                (((int)$formfields["duration"]) <= 0 ||
                 ((int)$formfields["duration"]) > $maxduration)) {
            $errors["duration"] = "Must be between 1 and $maxduration hours";
833
        }
834 835 836 837 838 839 840 841
    }
    if (count($errors)) {
	SPITAJAX_ERROR(2, $errors);
	return -1;
    }
    return 0;
}

842 843 844 845 846 847 848 849 850 851
#
# Run geni-lib script. This is a no parameters script, we just want to
# do the conversion to get the rspec.
#
function Do_RunScript()
{
    global $this_user;
    global $ajax_args;
    global $suexec_output, $suexec_output_array;

852 853
    $script = "";
    if (isset($ajax_args["script"])) {
Jonathon Duerig's avatar
Jonathon Duerig committed
854
        if (!isset($this_user)) {
855 856
	    SPITAJAX_ERROR(1, "Guest users cannot run genilib scripts");
	    return;
Jonathon Duerig's avatar
Jonathon Duerig committed
857 858 859 860
        }
        $this_idx = $this_user->uid_idx();
        $this_uid = $this_user->uid();
        $script = $ajax_args["script"];
861
    } else {
Jonathon Duerig's avatar
Jonathon Duerig committed
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
        if (!isset($ajax_args["uuid"])) {
	    SPITAJAX_ERROR(1, "Missing profile uuid");
	    return;
        }
        $profile = Profile::Lookup($ajax_args["uuid"]);
        if (!$profile) {
	    SPITAJAX_ERROR(1, "Unknown profile uuid");
	    return;
        }
        if (!$profile->script()) {
	    SPITAJAX_ERROR(1, "Not a geni-lib script");
	    return;
        }
        $script = $profile->script();

        # Guest users do not run geni-lib; return the rspec or error.
        if (!isset($this_user)) {
	    if ($profile->rspec() && $profile->rspec() != "") {
	        SPITAJAX_RESPONSE($profile->rspec());
	    } else {
	        SPITAJAX_ERROR(1, "No rspec for guest user");
	    }
        }
        $this_idx = $this_user->uid_idx();
        $this_uid = $this_user->uid();
887
    
Jonathon Duerig's avatar
Jonathon Duerig committed
888 889 890 891
        if (! ($profile->CanInstantiate($this_user) || ISADMIN())) {
	    SPITAJAX_ERROR(1, "Not enough permission to instantiate profile");
	    return;
        }
892
    }
893 894 895 896 897 898 899 900 901 902 903 904

    if (preg_match("/^import/m", $script)) {
        $command = "webrungenilib";
    }
    elseif (preg_match("/^source tb_compat/m", $script)) {
        $command = "webns2rspec -a";
    }
    else {
	SPITAJAX_ERROR(1, "Unknown script type");
	return;
    }

905 906 907 908
    $infname   = tempnam("/tmp", "genilibin");
    $outfname  = tempnam("/tmp", "genilibout");

    $fp = fopen($infname, "w");
909
    fwrite($fp, $script);
910 911 912 913 914 915 916 917
    fclose($fp);
    chmod($infname, 0666);
    chmod($outfname, 0666);

    #
    # Invoke the backend.
    #
    $retval = SUEXEC($this_uid, "nobody",
918
		     "$command -o $outfname $infname",
919 920 921 922 923 924 925 926 927 928
		     SUEXEC_ACTION_IGNORE);
    
    if ($retval != 0) {
	if ($retval < 0) {
	    SUEXECERROR(SUEXEC_ACTION_CONTINUE);
	    SPITAJAX_ERROR(-1, "Internal error, we have been notified");
	}
	else {
            # This might be a json structure, the JS code looks for it. 
	    $errors = file_get_contents($outfname);
929
	    SPITAJAX_ERROR(2, $errors);
930 931 932 933 934 935 936 937 938 939 940 941
	}
	unlink($infname);
	unlink($outfname);
	return;
    }
    $rspec = file_get_contents($outfname);

    unlink($infname);
    unlink($outfname);
    SPITAJAX_RESPONSE($rspec);
}

942 943 944 945 946 947 948
#
# Submit
#
function Do_Submit()
{
    global $this_user;
    global $ajax_args;
949 950
    global $PORTAL_GENESIS, $DEFAULT_AGGREGATE_URN;
    global $TBAUTHDOMAIN, $ISAPT, $ISPNET, $ISEMULAB, $ISPOWDER;
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965

    if (!isset($ajax_args["formfields"])) {
	SPITAJAX_ERROR(1, "Missing formfields");
	return;
    }
    #
    # Must recheck form values of course. 
    #
    if (CheckStep0()) {
        return;
    }
    # Step1 is for a parameterized profile, handled elsewhere. 
    if (CheckStep2()) {
        return;
    }
966 967 968
    if (CheckStep3()) {
        return;
    }
969
    $formfields = $ajax_args["formfields"];
970 971
    $amlist     = Instance::DefaultAggregateList();
    $am_array   = array();
972
    $errors     = array();
973
    $args       = array("portal" => $PORTAL_GENESIS);
974 975
    $profile    = Profile::Lookup($formfields["profile"]);

976 977 978 979 980 981
    while (list($index, $aggregate) = each($amlist)) {
        $urn  = $aggregate->urn();
        $name = $aggregate->name();
        $am_array[$name] = $urn;
    }

982 983 984 985 986 987 988 989 990 991 992 993 994 995
    #
    # SSH keys are optional for guest users; they just have to
    # use the web based ssh window.
    #
    # Backend verifies pubkey and returns error. 
    #
    if (isset($formfields["sshkey"]) && $formfields["sshkey"] != "") {
        $args["sshkey"] = $formfields["sshkey"];
    }
    #
    # Real/Geni users are allowed to use Paramterized Profiles, which means
    # we could get an rspec.
    #
    if ($profile->isParameterized() && $this_user &&
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
        isset($formfields["rspec"]) && $formfields["rspec"] != "") {
        $args["rspec"] = $formfields["rspec"];
    }

    #
    # For a repo-based profile, we might get an rspec and/or a script.
    # Need to deal with the paramdefs block too.
    #
    if ($profile->repourl() && $this_user) {
        if (isset($formfields["script"]) && $formfields["script"] != "") {
            $args["script"] = $formfields["script"];
        }
        if (isset($formfields["rspec"]) && $formfields["rspec"] != "") {
            $args["rspec"] = $formfields["rspec"];
        }
        # If the user is instantiating the profile version, we will not
        # get these.
        if (isset($formfields["reporef"]) && $formfields["reporef"] != "") {
            $args["reporef"] = $formfields["reporef"];
        }
        if (isset($formfields["repohash"]) && $formfields["repohash"] != "") {
            $args["repohash"] = $formfields["repohash"];
        }
1019 1020 1021 1022 1023 1024
    }

    $aggregate_urn = "";
    $sitemap = array();

    if ($this_user) {
1025
        if (isset($formfields["sites"]) && is_array($formfields["sites"])) {
1026 1027 1028 1029 1030 1031
            while (list($siteid, $am) = each($formfields["sites"])) {
                if (array_key_exists($am, $am_array)) {
                    $sitemap[$siteid] = $am_array[$am];
                }
            }
        }
1032
        elseif ($ISAPT || $ISPNET || $ISEMULAB | $ISPOWDER) {
1033 1034 1035
            $aggregate_urn = $DEFAULT_AGGREGATE_URN;
        }
        elseif (isset($formfields["where"])) {
1036 1037
	    $aggregate_urn = $am_array[$formfields["where"]];
        }
1038 1039 1040
        else {
            $aggregate_urn = $DEFAULT_AGGREGATE_URN;
        }
1041 1042
        # Required for real users.
        $args["pid"] = $formfields["pid"];
1043
        $args["gid"] = $formfields["gid"];
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055

        # Experiment name is optional, we generate one later.
        if (isset($formfields["name"]) && $formfields["name"] != "") {
            $args["instance_name"] = $formfields["name"];
        }
    }
    # Ignore the form for a logged in user. 
    $args["username"] = ($this_user ?
                         $this_user->uid() : $formfields["username"]);
    $args["email"]    = ($this_user ?
                         $this_user->email() : $formfields["email"]);
    $args["profile"]  = $formfields["profile"];
1056 1057 1058 1059 1060
    if (!$this_user) {
        if (isset($_SESSION["verified"])) {
            $args["auth_token"] = $_SESSION["auth_token"];
        }
    }
1061 1062 1063
    if ($this_user) {
        $args["duration"]  = $formfields["duration"];
    }
1064 1065 1066 1067 1068 1069 1070 1071 1072

    if (0) {
        TBERROR(print_r($args, true), 0);
        SPITAJAX_RESPONSE(0);
        return;
    }
    $options = "";

    if ($aggregate_urn != "") {
1073
        $options = " -a '$aggregate_urn' ";
1074 1075 1076 1077 1078 1079
    }
    elseif (count($sitemap)) {
        while (list($siteid, $urn) = each($sitemap)) {
            $options .= "--site 'site:${siteid}=${urn}' ";
        }
    }
1080 1081 1082 1083 1084 1085
    # Scheduled start time if not starting immediately.
    if (! (isset($formfields["start-immediately"]) &&
           $formfields["start-immediately"] == "checked")) {
        $start = strtotime($formfields["start"]);
        $options .= " --start $start ";
    }
1086 1087 1088 1089 1090 1091 1092 1093
    if (isset($_SESSION["privkey"])) {
        $keyname = tempnam("/tmp", "genilibkey");
        $fp = fopen($keyname, "w");
        fwrite($fp, $_SESSION["privkey"]);
        fclose($fp);
        chmod($keyname, 0666);
        $options .= " -k $keyname";
    }
1094
    if (isset($formfields["failure_okay"]) &&
1095
        $formfields["failure_okay"] == "checked") {
1096 1097
        $options .= " -i ";
    }
1098 1099 1100 1101 1102 1103 1104 1105 1106

    # So we can look up the slice after the backend creates it.
    $uuid = NewUUID();

    # Create this here. If the instantiate fails, we delete it.
    # Otherwise, the instance owns it.
    $webtask = WebTask::Create($uuid);
    $webtask_id = $webtask->task_id();
           
1107 1108 1109 1110
    #
    # Invoke the backend.
    #
    list ($instance, $creator) =
1111
        Instance::Instantiate($uuid, $this_user, $options, $args, $webtask);
1112 1113

    if (!$instance) {
1114 1115
        # Create error is handled differently.
	SPITAJAX_ERROR(3, $webtask->output());
1116 1117 1118
        if (isset($keyname)) {
            unlink($keyname);
        }
1119
        $webtask->Delete();
1120 1121
        return;
    }
1122 1123 1124
    if (isset($keyname)) {
        unlink($keyname);
    }    
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
    $blob = array("redirect" => "status.php?uuid=" . $instance->uuid());

    #
    # Remember the user and auth key so that we can verify.
    #
    # The cookie handling is a pain since we run this under the aptlab
    # virtual host, but the config uses a different domain, and so the
    # cookies do not work. So, we have to look at our SERVER_NAME and
    # set the cookie appropriately. 
    #
    if (!$this_user) {
        $cookiedomain = $TBAUTHDOMAIN;
        $expires = time() + (24 * 3600 * 30);

        $blob["cookies"] = array("quickvm_user" =>
                                 array("value"   => $creator->uuid(),
                                       "expires" => $expires,
                                       "domain"  => $cookiedomain),
                                 "quickvm_authkey" =>
Leigh Stoller's avatar
Leigh Stoller committed
1144
                                 array("value"   => $creator->auth_token(),
1145 1146 1147
                                       "expires" => $expires,
                                       "domain"  => $cookiedomain));
    }
1148
    session_destroy();
1149 1150 1151 1152
    SPITAJAX_RESPONSE($blob);
    return;
}

1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
#
# Mark (or clear) a profile as a favorite.
#
function Do_MarkFavorite()
{
    global $this_user;
    global $ajax_args;

    if (!isset($ajax_args["uuid"])) {
	SPITAJAX_ERROR(1, "Missing profile uuid");
	return;
    }
    $profile = Profile::Lookup($ajax_args["uuid"]);
    if (!$profile) {
	SPITAJAX_ERROR(1, "Unknown profile uuid");
	return;
    }
    if (!isset($this_user)) {
        SPITAJAX_ERROR(1, "Guest users may not set profile favorites");
        return;
    }
    $profile->MarkFavorite($this_user);
    SPITAJAX_RESPONSE(0);
}
function Do_ClearFavorite()
{
    global $this_user;
    global $ajax_args;

    if (!isset($ajax_args["uuid"])) {
	SPITAJAX_ERROR(1, "Missing profile uuid");
	return;
    }
    $profile = Profile::Lookup($ajax_args["uuid"]);
    if (!$profile) {
	SPITAJAX_ERROR(1, "Unknown profile uuid");
	return;
    }
    if (!isset($this_user)) {
        SPITAJAX_ERROR(1, "Guest users may not set profile favorites");
        return;
    }
    $profile->ClearFavorite($this_user);
    SPITAJAX_RESPONSE(0);
}

1199 1200 1201 1202
# Local Variables:
# mode:php
# End:
?>