instantiate.ajax 26.7 KB
Newer Older
1
2
<?php
#
Leigh B Stoller's avatar
Leigh B Stoller committed
3
# Copyright (c) 2000-2015 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
33
34
35
36

#
# Return info about specific profile.
#
function Do_GetProfile()
{
    global $this_user;
    global $ajax_args;
37
    global $DEFAULT_AGGREGATE;
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
    
    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;
    }
53
54
55
56
57
    $amdefault = $DEFAULT_AGGREGATE;
    # Temporary override until constraint system in place.
    if ($profile->BestAggregate()) {
	$amdefault = $profile->BestAggregate();
    }
58
    $ispp = ($profile->isParameterized() ? 1 : 0);
59
    
60
    #
61
62
    # Knowing the UUID means the user can instantiate it,
    # so no permission checks on the profile. 
63
64
    #
    SPITAJAX_RESPONSE(array('rspec'       => $profile->rspec(),
65
			    'name'        => $profile->name(),
66
			    'ispprofile'  => $ispp,
67
			    'amdefault'   => $amdefault));
68
}
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

#
# 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;
	}	    
    }
94
    elseif (! ($profile->CanInstantiate($this_user) || ISADMIN())) {
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
	SPITAJAX_ERROR(1, "Not enough permission to instantiate profile");
	return;
    }
    if (!$profile->isParameterized()) {
	SPITAJAX_ERROR(1, "Not a parameterized profile");
	return;
    }
    list ($formfrag, $defaults) = $profile->GenerateFormFragment();
    SPITAJAX_RESPONSE(array("formfrag" => htmlentities($formfrag),
			    "defaults" => $defaults));
}

#
# Instantiate profile (as the user)
#
function Do_Instantiate()
{
112
    global $this_user, $DEFAULT_AGGREGATE, $ISCLOUD;
113
    global $ajax_args;
114
    $am_array = Instance::DefaultAggregateList();
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
    
    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;
	}	    
    }
131
    elseif (! ($profile->CanInstantiate($this_user) || ISADMIN())) {
132
133
134
135
136
137
138
	SPITAJAX_ERROR(1, "Not enough permission to instantiate profile");
	return;
    }
    $args = array();
    $args["username"]   = $this_user->uid();
    $args["email"]      = $this_user->email();
    $args["profile"]    = $profile->uuid();
139
140
    # Guest users not allowed to provide rspec
    if (isset($this_user) &&
141
        array_key_exists("rspec", $ajax_args)) {
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
	$args["rspec"]  = $ajax_args["rspec"];
    }
    $opts = "";
    # Guest users not allowed to choose aggregate.
    if (isset($this_user) && ($ISCLOUD || ISADMIN() || STUDLY()) &&
	isset($ajax_args["where"])) {
	if (array_key_exists($ajax_args["where"], $am_array)) {
	    $opts = "-a " . $am_array[$ajax_args["where"]];
	}
	else {
	    SPITAJAX_ERROR(1, "Invalid Aggregate");
	    return;
	}
    }
    else {
	# Temporary until constraint system in place.
	$best = $profile->BestAggregate();
	if (!$best) {
	    $best = $DEFAULT_AGGREGATE;
	}
	$opts = "-a " . $am_array[$best];
    }

    #
    # Invoke the backend.
    #
    $errors = array();
    list ($instance, $creator) =
	Instance::Instantiate($this_user, $opts, $args, $errors);

    if (!isset($instance) || is_null($instance)) {
	SPITAJAX_ERROR(1, $errors["error"]);
Leigh B Stoller's avatar
Leigh B Stoller committed
174
        return;
175
176
177
178
179
180
181
182
    }
    #
    # Redirect user to status page.
    #
    $uuid = $instance->uuid();
    SPITAJAX_RESPONSE("status.php?uuid=$uuid");
}

183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
#
# 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 B Stoller's avatar
Leigh B Stoller committed
201
        if (!preg_match("/^[-\w]+$/", $pid)) {
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
            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) {
223
224
225
        $types = array();
        $virts = array();
        
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
        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);

         again:
            if (is_null($version)) {
241
242
243
244
245
246
247
248
                if ($proj == "emulab-ops") {
                    list ($a,$b,$c) = Instance::ParseURN($urn);
                    $safe_urn = addslashes("urn:publicid:IDN+%+image+${c}");
                    $innerclause = "urn like '$safe_urn'";
                }
                else {
                    $innerclause = "urn='$safe_urn'";
                }
249
                $query_result =
250
251
252
253
254
255
256
257
                    DBQueryFatal("select i.*,v.* from image_versions as v ".
                                 "   inner join ".
                                 "      (select urn,max(version) as version ".
                                 "         from image_versions ".
                                 "       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",
258
259
260
261
                                $dblink);
            }
            else {
                $query_result =
262
                    DBQueryFatal("select i.*,v.* from image_versions as v ".
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
                                "left join images as i on ".
                                "     i.image_uuid=v.image_uuid ".
                                "where v.urn='$safe_urn' and v.version='$version'",
                                $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);
281
282
283
284
285
286
287
288
289
290
291
292
293

            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 =
294
                            DBQueryFatal("select i.*,v.* ".
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
                                 "  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);
                    }
                }
            }
310
311
312
313
314
315
316
317
        }
        else {
            continue;
        }
        if (!$query_result || !mysql_num_rows($query_result)) {
            # Is this the right thing to do?
            continue;
        }
318
        while ($row = mysql_fetch_array($query_result)) {
319
            #
320
321
322
            # 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.
323
            #
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
            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);
                if ($impid && $impid == $pid) {
                    goto allowed;
                }
340

341
                #
Leigh B Stoller's avatar
Leigh B Stoller committed
342
343
344
345
                # 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.
346
347
348
349
350
                #
                $perms_result =
                    DBQueryWarn("select * from image_permissions ".
                                "where urn='" . addslashes($row["urn"]) . "'",
                                $dblink);
351

352
353
354
355
356
357
358
359
360
                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;
                        }
361
                    }
362
363
364
365
366
367
                    elseif ($ptype == "project") {
                        list ($auth) = Instance::ParseURN($purn);
                        list ($domain,$ppid) = preg_split('/:/', $auth);
                        if ($ppid && $ppid == $pid) {
                            goto allowed;
                        }
368
369
                    }
                }
370
                continue;
371
            }
372
373
374
375
376
377
     allowed:
	    foreach (preg_split("/,/", $row["types_known_working"]) as $type) {
                $types[$type] = $type;
	    }
            $virts[$row["virtualizaton"]] = $row["virtualizaton"];
            $description = $row["description"];
378
        }
379
380
381
382
        if (count($types)) {
            # These are reversed from what they should mean!
            $typelist = implode(",", array_keys($types));
            $virtlist = implode(",", array_keys($virts));
383

384
385
386
387
388
389
390
391
392
393
394
395
            $constraints[] =
                array("node" =>
                      array("images" => array($urn),
                            "types"  => array($virtlist)));
            $constraints[] =
                array("node" =>
                      array("images"   => array($urn),
                            "hardware" => array($typelist)));

            $images[] = array("id"   => $urn,
                              "name" => $description);
        }
396
397
398
399
400
401
402
    }
    $result = array(array("constraints" => $constraints,
                          "images" => $images));
    
    SPITAJAX_RESPONSE($result);
}

403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
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
#
# 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);
        }
    }
}

#
# 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;
608
    global $ISAPT, $ISCLOUD;
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630

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

    #
    # 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";
        }
631
632
633
634
635
636
        #
        # 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.
        #
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
    }
    if (!$this_user) {
        #
        # Need to make sure we got verified.
        #
        session_start();
        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;
                }
            }
        }
656
657
658
659
        elseif ($ISAPT) {
            # No choice
            ;
        }
Leigh B Stoller's avatar
Leigh B Stoller committed
660
661
662
663
664
665
666
        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";
            }
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
        }
        
        #
        # Project has to exist.  
        #
        $project = Project::LookupByPid($formfields["pid"]);
        if (!$project) {
            $errors["pid"] = "No such project";
        }
        # User better be a member.
        elseif (!ISADMIN() &&
                (!$project->IsMember($this_user, $isapproved) ||
                 !$isapproved)) {
            $errors["pid"] = "Illegal project";
        }

        # 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";
            }
        }
    }
    if (count($errors)) {
	SPITAJAX_ERROR(2, $errors);
	return -1;
    }
    return 0;
}

#
# Submit
#
function Do_Submit()
{
    global $this_user;
    global $ajax_args;
711
    global $TBAUTHDOMAIN, $ISAPT;
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

    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;
    }
    $formfields = $ajax_args["formfields"];
    $am_array   = Instance::DefaultAggregateList();
    $errors     = array();
    $args       = array();
    $profile    = Profile::Lookup($formfields["profile"]);

    #
    # 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 &&
        isset($formfields["pp_rspec"]) && $formfields["pp_rspec"] != "") {
        $args["rspec"] = $formfields["pp_rspec"];
    }

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

    if ($this_user) {
755
756
757
758
        if ($ISAPT) {
	    $aggregate_urn = "urn:publicid:IDN+apt.emulab.net+authority+cm";
        }
        elseif (isset($formfields["sites"]) && is_array($formfields["sites"])) {
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
            while (list($siteid, $am) = each($formfields["sites"])) {
                if (array_key_exists($am, $am_array)) {
                    $sitemap[$siteid] = $am_array[$am];
                }
            }
        }
        else {
	    $aggregate_urn = $am_array[$formfields["where"]];
        }
        # Required for real users.
        $args["pid"] = $formfields["pid"];

        # 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"];
782
783
784
785
786
787
788
    if (!$this_user) {
        session_start();

        if (isset($_SESSION["verified"])) {
            $args["auth_token"] = $_SESSION["auth_token"];
        }
    }
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
826
827
828
829
830
831
832
833

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

    if ($aggregate_urn != "") {
        $options = " -a '$aggregate_urn'";
    }
    elseif (count($sitemap)) {
        while (list($siteid, $urn) = each($sitemap)) {
            $options .= "--site 'site:${siteid}=${urn}' ";
        }
    }
    #
    # Invoke the backend.
    #
    list ($instance, $creator) =
        Instance::Instantiate($this_user, $options, $args, $errors);

    if (!$instance) {
	SPITAJAX_ERROR(2, $errors);
        return;
    }
    $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 B Stoller's avatar
Leigh B Stoller committed
834
                                 array("value"   => $creator->auth_token(),
835
836
837
838
839
840
841
842
                                       "expires" => $expires,
                                       "domain"  => $cookiedomain));
        session_destroy();
    }
    SPITAJAX_RESPONSE($blob);
    return;
}

843
844
845
846
# Local Variables:
# mode:php
# End:
?>