GeniTicket.pm.in 23.4 KB
Newer Older
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1
2
#!/usr/bin/perl -wT
#
3
# GENIPUBLIC-COPYRIGHT
Leigh B Stoller's avatar
Leigh B Stoller committed
4
# Copyright (c) 2008-2012 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
5
6
7
8
9
10
11
12
13
14
15
16
# All rights reserved.
#
package GeniTicket;

#
# Some simple ticket stuff.
#
use strict;
use Exporter;
use vars qw(@ISA @EXPORT);

@ISA    = "Exporter";
17
@EXPORT = qw (TICKET_PURGED TICKET_EXPIRED TICKET_REDEEMED
18
	      TICKET_RELEASED TICKET_DELETED TICKET_NOSTATS);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
19
20

use GeniDB;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
21
use GeniCredential;
22
use GeniCertificate;
23
24
use emutil qw(TBGetUniqueIndex);
use GeniUtil;
25
use GeniHRN;
26
use GeniXML;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
27
use English;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
28
29
use XML::Simple;
use XML::LibXML;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
30
use Data::Dumper;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
31
32
33
use Date::Parse;
use POSIX qw(strftime);
use Time::Local;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
34
use File::Temp qw(tempfile);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
35
use overload ('""' => 'Stringify');
Leigh B. Stoller's avatar
Leigh B. Stoller committed
36
37
38
39
40
41
42
43
44

# Configure variables
my $TB		   = "@prefix@";
my $TBOPS          = "@TBOPSEMAIL@";
my $TBAPPROVAL     = "@TBAPPROVALEMAIL@";
my $TBAUDIT   	   = "@TBAUDITEMAIL@";
my $BOSSNODE       = "@BOSSNODE@";
my $OURDOMAIN      = "@OURDOMAIN@";
my $SIGNCRED	   = "$TB/sbin/signgenicred";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
45
my $VERIFYCRED	   = "$TB/sbin/verifygenicred";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
46
my $NFREE	   = "$TB/bin/nfree";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
47
my $CMCERT	   = "$TB/etc/genicm.pem";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
48

49
50
51
52
53
# Ticket release flags
sub TICKET_PURGED()	{ return 1; }
sub TICKET_REDEEMED()	{ return 2; }
sub TICKET_EXPIRED()	{ return 3; }
sub TICKET_RELEASED()	{ return 4; }
54
sub TICKET_DELETED()	{ return 5; }
55
sub TICKET_NOSTATS()	{ return 0x1; }
56

Leigh B. Stoller's avatar
Leigh B. Stoller committed
57
58
# Cache of tickets.
my %tickets = ();
59
60
61
62
63
64
BEGIN { use GeniUtil; GeniUtil::AddCache(\%tickets); }

# Do not load this for the Clearinghouse XML server.
BEGIN { 
    if (! defined($main::GENI_ISCLRHOUSE)) {
	require Experiment;
65
	require Node;
66
67
    }
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
68
69
70
71
72
73

#
# Lookup by local idx.
#
sub Lookup($$)
{
74
75
76
    my ($class, $token) = @_;
    my $idx;
    my $query_result;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
77

78
    if (GeniHRN::IsValid($token)) {
79
	# We don't attempt to handle tickets for foreign authorities.
80
81
82
83
84
85
86
	return undef if !GeniHRN::Authoritative($token, "@OURDOMAIN@");

	my ($authority, $type, $id) = GeniHRN::Parse($token);
	return undef if $type ne "ticket";
	$idx = $id;
    }
    elsif ($token =~ /^\d+$/) {
87
88
89
90
91
92
93
94
95
96
97
98
99
100
	$idx = $token;
    }
    elsif ($token =~ /^\w+\-\w+\-\w+\-\w+\-\w+$/) {
	$query_result =
	    DBQueryWarn("select idx from geni_tickets ".
			"where ticket_uuid='$token'");
	    return undef
		if (! $query_result || !$query_result->numrows);

	    ($idx) = $query_result->fetchrow_array();
    }
    else {
	return undef;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
101
102
103
    return $tickets{"$idx"}
        if (exists($tickets{"$idx"}));

104
    $query_result =
Leigh B. Stoller's avatar
Leigh B. Stoller committed
105
106
107
108
109
110
111
	DBQueryWarn("select * from geni_tickets where idx='$idx'");

    return undef
	if (!defined($query_result) || !$query_result->numrows);

    my $row = $query_result->fetchrow_hashref();

112
    my $ticket = GeniTicket->CreateFromSignedTicket($row->{'ticket_string'},1);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
113
114
115
    return undef
	if (!defined($ticket));

Leigh B. Stoller's avatar
Leigh B. Stoller committed
116
117
118
119
    # We ignore this in the ticket. In fact, we need to change how we bring
    # tickets back into the system.
    $ticket->{'redeem_before'} = $row->{'redeem_before'};

120
121
122
    # Mark as coming from the DB.
    $ticket->{'idx'}    = $idx;
    $ticket->{'stored'} = 1;
123
    $ticket->{'LOCKED'}   = 0;
124
125

    # Cache.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
126
127
128
129
    $tickets{"$idx"} = $ticket;
    return $ticket;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
130
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
131
# Create an unsigned ticket object, to be populated and signed and returned.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
132
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
133
sub Create($$$$)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
134
{
135
    # $rspec is an XML string.
136
    my ($class, $target, $owner, $rspec) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
137

138
139
140
141
142
143
144
145
146
147
    my $parser = XML::LibXML->new;
    my $doc;
    eval {
	$doc = $parser->parse_string($rspec);
    };
    if ($@) {
	print STDERR "Failed to parse ticket string: $@\n";
	return undef;
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
148
149
    # Every Ticket gets a new unique index (sequence number).
    my $seqno = TBGetUniqueIndex('next_ticket', 1);
150

Leigh B. Stoller's avatar
Leigh B. Stoller committed
151
    my $self = {};
152
    $self->{'rspec'}         = $doc->documentElement();
153
    $self->{'ticket_uuid'}   = undef;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
154
    $self->{'owner_uuid'}    = $owner->uuid();
155
    $self->{'owner_hrn'}     = $owner->hrn();
156
    $self->{'owner_urn'}     = $owner->urn();
157
    $self->{'owner_cert'}    = $owner->GetCertificate();
158
159
    $self->{'target_uuid'}   = $target->uuid();
    $self->{'target_hrn'}    = $target->hrn();
160
    $self->{'target_urn'}    = $target->urn();
161
    $self->{'target_cert'}   = $target->GetCertificate();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
162
    $self->{'seqno'}         = $seqno;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
163
    $self->{'ticket_string'} = undef;
164
    $self->{'slice'}         = undef;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
165
    $self->{'stored'}        = 0;	# Stored to the DB.
166
    $self->{'LOCKED'}        = 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
167

Leigh B. Stoller's avatar
Leigh B. Stoller committed
168
169
170
171
    #
    # For now, all tickets expire very quickly ...
    #
    $self->{'redeem_before'} =
172
	POSIX::strftime("20%y-%m-%dT%H:%M:%S", localtime(time() + (10*60)));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
173

Leigh B. Stoller's avatar
Leigh B. Stoller committed
174
175
176
177
178
179
180
181
    #
    # Locally generated tickets need a local DB index, which can be the
    # same as the sequence number. A ticket from a remote component will
    # have it own seqno, and so we will generate a locally valid idx for
    # those when when(if) we store them in the DB.
    #
    $self->{'idx'}           = $seqno;
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
182
183
184
185
186
187
    bless($self, $class);

    return $self;
}
# accessors
sub field($$)           { return ($_[0]->{$_[1]}); }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
188
sub idx($)		{ return field($_[0], "idx"); }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
189
sub seqno($)		{ return field($_[0], "seqno"); }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
190
sub rspec($)		{ return field($_[0], "rspec"); }
191
sub target_uuid($)	{ return field($_[0], "target_uuid"); }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
192
sub owner_uuid($)	{ return field($_[0], "owner_uuid"); }
193
sub target_hrn($)	{ return field($_[0], "target_hrn"); }
194
sub owner_hrn($)	{ return field($_[0], "owner_hrn"); }
195
196
sub target_urn($)	{ return field($_[0], "target_urn"); }
sub owner_urn($)	{ return field($_[0], "owner_urn"); }
197
sub target_cert($)	{ return field($_[0], "target_cert"); }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
198
sub owner_cert($)	{ return field($_[0], "owner_cert"); }
199
sub uuid($)		{ return field($_[0], "ticket_uuid"); }
200
sub ticket_uuid($)	{ return field($_[0], "ticket_uuid"); }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
201
sub ticket($)		{ return field($_[0], "ticket"); }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
202
sub asString($)		{ return field($_[0], "ticket_string"); }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
203
sub ticket_string($)	{ return field($_[0], "ticket_string"); }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
204
sub redeem_before($)	{ return field($_[0], "redeem_before"); }
205
sub expires($)	        { return field($_[0], "expires"); }
206
sub redeemed($   )	{ return field($_[0], "redeemed"); }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
207
sub stored($)		{ return field($_[0], "stored"); }
208
209
210
211
sub slice($)            { return $_[0]->{'slice'}; }
sub slice_uuid($)	{ return $_[0]->slice()->uuid(); }
sub slice_hrn($)	{ return $_[0]->slice()->hrn(); }
sub slice_urn($)	{ return $_[0]->slice()->urn(); }
212
sub LOCKED($)           { return $_[0]->{'LOCKED'}; }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
213

214
215
216
217
218
219
220
221
222

# Return the URN.
sub urn($)
{
    my ($self) = @_;

    return GeniHRN::Generate("@OURDOMAIN@", "ticket", $self->idx());
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
223
224
225
226
227
228
229
230
231
232
233
234
#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $idx = $self->idx();
    if (!defined($idx)) {
	my $seqno = $self->seqno();
	$idx = "S$seqno";
    }
235
    my $owner_hrn   = $self->owner_hrn();
236
    my $target_urn  = $self->target_urn();
237
    
238
    return "[GeniTicket: $idx, owner:$owner_hrn, target:$target_urn]";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
239
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
240

Leigh B. Stoller's avatar
Leigh B. Stoller committed
241
242
243
244
245
246
247
248
249
250
#
# Flush from our little cache, as for the expire daemon.
#
sub Flush($)
{
    my ($self) = @_;

    delete($tickets{$self->idx()});
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
251
252
253
#
# Create a ticket object from a signed ticket string.
#
254
sub CreateFromSignedTicket($$;$)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
255
{
256
    my ($class, $ticket_string, $nosig) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
257

Leigh B. Stoller's avatar
Leigh B. Stoller committed
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
    #
    # This flag is used to avoid verifying the signature since I do not
    # really care if the component gives me a bad ticket; I am not using
    # it locally, just passing it back to the component at some point.
    #
    $nosig = 0
	if (!defined($nosig));

    if (! $nosig) {
	my ($fh, $filename) = tempfile(UNLINK => 0);
	return undef
	    if (!defined($fh));
	print $fh $ticket_string;
	close($fh);
	system("$VERIFYCRED $filename");
	if ($?) {
	    print STDERR "Ticket in $filename did not verify\n";
	    return undef;
	}
	unlink($filename);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
278
279
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
280
281
    # Use XML::Simple to convert to something we can mess with.
    my $parser = XML::LibXML->new;
282
283
284
285
286
287
288
289
    my $doc;
    eval {
	$doc = $parser->parse_string($ticket_string);
    };
    if ($@) {
	print STDERR "Failed to parse ticket string: $@\n";
	return undef;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
290
291

    # Dig out the rspec.
292
293
294
    my $rspec = GeniXML::FindFirst("//*[local-name()='rspec']",
				   $doc->documentElement());
    if (!defined($rspec)) {
295
296
297
298
	print STDERR "Ticket is missing rspec node\n";
	return undef;
    }
    
299
300
    # Dig out the ticket uuid.
    my ($uuid_node) = $doc->getElementsByTagName("uuid");
301
302
303
304
    if (!defined($uuid_node)) {
	print STDERR "Ticket is missing uuid node\n";
	return undef;
    }
305
    my $ticket_uuid = $uuid_node->to_literal();
306
307
308
309
310
311

    if (! ($ticket_uuid =~ /^\w+\-\w+\-\w+\-\w+\-\w+$/)) {
	print STDERR "Invalid uuid in ticket\n";
	return undef;
    }

312
313
    # Dig out the target certificate.
    my ($cert_node) = $doc->getElementsByTagName("target_gid");
314
315
316
317
    if (!defined($cert_node)) {
	print STDERR "Ticket is missing target gid node\n";
	return undef;
    }
318
319
    my $target_certificate =
	GeniCertificate->LoadFromString($cert_node->to_literal());
320
321
322
323
    if (!defined($target_certificate)) {
	print STDERR "Could not get target certificate from string\n";
	return undef;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
324

325
326
327
328
    if (!($target_certificate->uuid() =~ /^\w+\-\w+\-\w+\-\w+\-\w+$/)) {
	print STDERR "Invalid target_uuid in credential\n";
	return undef;
    }
329
330
331
    if (!($target_certificate->hrn() =~ /^[-\w\.]+$/)) {
	my $hrn = $target_certificate->hrn();
	print STDERR "Invalid hrn $hrn in target of ticket\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
332
333
334
	return undef;
    }

335
336
    # Dig out the owner certificate.
    ($cert_node) = $doc->getElementsByTagName("owner_gid");
337
338
339
340
    if (!defined($cert_node)) {
	print STDERR "Ticket is missing owner gid node\n";
	return undef;
    }
341
342
    my $owner_certificate =
	GeniCertificate->LoadFromString($cert_node->to_literal());
343
344
345
346
    if (!defined($target_certificate)) {
	print STDERR "Could not get owner certificate from string\n";
	return undef;
    }
347
348
349
350
    if (!($owner_certificate->uuid() =~ /^\w+\-\w+\-\w+\-\w+\-\w+$/)) {
	print STDERR "Invalid target_uuid in credential\n";
	return undef;
    }
351
352
353
    if (!($owner_certificate->hrn() =~ /^[-\w\.]+$/)) {
	my $hrn = $owner_certificate->hrn();
	print STDERR "Invalid hrn $hrn in owner of ticket\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
354
355
356
	return undef;
    }

357
    # Sequence number
Leigh B. Stoller's avatar
Leigh B. Stoller committed
358
    my ($seqno_node) = $doc->getElementsByTagName("serial");
359
360
361
362
    if (!defined($seqno_node)) {
	print STDERR "Ticket is missing seqno node\n";
	return undef;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
363
    my $seqno = $seqno_node->to_literal();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
364

Leigh B. Stoller's avatar
Leigh B. Stoller committed
365
366
367
    if (! ($seqno =~ /^\w+$/)) {
	print STDERR "Invalid sequence number in ticket\n";
	return undef;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
368
369
    }

370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
    # Expiration
    my ($expires_node) = $doc->getElementsByTagName("expires");
    if (!defined($expires_node)) {
	print STDERR "Ticket is missing expires node\n";
	return undef;
    }
    my $expires = $expires_node->to_literal();

    if (! ($expires =~ /^[-\w:.\/]+/)) {
	print STDERR "Invalid expires date in ticket\n";
	return undef;
    }
    # Convert to a localtime.
    my $when = timegm(strptime($expires));
    if (!defined($when)) {
	print STDERR "Could not parse expires: '$expires'\n";
	return undef;
    }
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
389
    my $self = {};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
390
    $self->{'idx'}           = undef;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
391
    $self->{'rspec'}         = $rspec;
392
    $self->{'ticket_uuid'}   = $ticket_uuid;
393
    $self->{'target_uuid'}   = $target_certificate->uuid();
394
    $self->{'owner_uuid'}    = $owner_certificate->uuid();
395
    $self->{'target_hrn'}    = $target_certificate->hrn();
396
    $self->{'owner_hrn'}     = $owner_certificate->hrn();
397
398
    $self->{'target_urn'}    = $target_certificate->urn();
    $self->{'owner_urn'}     = $owner_certificate->urn();
399
    $self->{'target_cert'}   = $target_certificate;
400
    $self->{'owner_cert'}    = $owner_certificate;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
401
402
    $self->{'ticket_string'} = $ticket_string;
    $self->{'xmlref'}        = $doc;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
403
    $self->{'seqno'}         = $seqno;
404
    $self->{'expires'}       = $expires;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
405
    $self->{'stored'}        = 0;
406
    $self->{'slice'}         = undef;
407
    $self->{'LOCKED'}        = 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
408
409
    
    #
410
411
    # We save copies of the tickets we hand out, but delete them
    # when redeemed. If we still have it, mark it.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
412
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
413
414
415
416
417
418
419
420
    my $query_result =
	DBQueryWarn("select * from geni_tickets where idx='$seqno'");

    if ($query_result && $query_result->numrows) {
	my $row = $query_result->fetchrow_hashref();
	$self->{'redeem_before'} = $row->{'redeem_before'};
	$self->{'idx'}    = $seqno;
	$self->{'stored'} = 1;
421
422
423
424
425
426
427
428
429
430
431
432
433
434
	#
	# Older tickets might not have the slice set. The CM will
	# set it later though.
	#
	if (defined($row->{'slice_uuid'})) {
	    my $slice_uuid = $row->{'slice_uuid'};
	    my $slice = GeniSlice->Lookup($slice_uuid);
	    if (!defined($slice)) {
		print STDERR
		    "Could not locate slice for ticket from $slice_uuid\n";
		return undef;
	    }
	    $self->{'slice'} = $slice;
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
435
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
436
437
438
    bless($self, $class);
    return $self;
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
439

Leigh B. Stoller's avatar
Leigh B. Stoller committed
440
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
441
442
# Might have to delete this from the DB, as with an error handing out
# a ticket.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
443
#
444
sub Delete($$)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
445
{
446
    my ($self, $flag) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
447
448
449
450

    return -1
	if (! ref($self));

Leigh B. Stoller's avatar
Leigh B. Stoller committed
451
    if ($self->stored()) {
452
453
	my $idx  = $self->idx();
	my $uuid = $self->ticket_uuid();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
454
455
456
	
	DBQueryWarn("delete from geni_tickets where idx='$idx'")
	    or return -1;
457

458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
	if ($flag == TICKET_PURGED) {
	    GeniUsage->DeleteTicket($self) == 0 
		or print STDERR "GeniTicket::Delete: ".
		    "GeniUsage->DeleteTicket($self) failed\n";
	}
	elsif ($flag == TICKET_RELEASED) {
	    GeniUsage->ReleaseTicket($self) == 0 
		or print STDERR "GeniTicket::Delete: ".
		    "GeniUsage->ReleaseTicket($self) failed\n";
	}
	elsif ($flag == TICKET_EXPIRED) {
	    GeniUsage->ExpireTicket($self) == 0 
		or print STDERR "GeniTicket::Delete: ".
		    "GeniUsage->ExpireTicket($self) failed\n";
	}
473
474
475
476
477
478
479
480
481
	elsif ($flag == TICKET_REDEEMED) {
	    GeniUsage->RedeemTicket($self) == 0 
		or print STDERR "GeniTicket::Delete: ".
		"GeniUsage->RedeemTicket($self) failed\n";
	}
	elsif ($flag == TICKET_DELETED) {
	    # Do nothing for this. Just removing from the tickets table,
	    # but want to leave it in the history.
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
482
	delete($tickets{"$idx"});
Leigh B. Stoller's avatar
Leigh B. Stoller committed
483
484
485
486
    }
    return 0;
}

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
#
# We lock at a very coarse grain, mostly in the CM. 
#
sub Lock($)
{
    my ($self) = @_;
    my $idx    = $self->idx();

    # We already have it locked.
    return 0
	if ($self->LOCKED());

    # Not in the DB, so does not matter.
    return 0
	if (!$self->stored());

    DBQueryWarn("lock tables geni_tickets write")
	or return -1;

    my $query_result =
	DBQueryWarn("select locked from geni_tickets ".
		    "where idx='$idx' and locked is null");
    if (!$query_result || !$query_result->numrows) {
	DBQueryWarn("unlock tables");
	return 1;
    }
    $query_result =
	DBQueryWarn("update geni_tickets set locked=now() where idx='$idx'");
    DBQueryWarn("unlock tables");

    return 1
	if (!$query_result);
    $self->{'LOCKED'} = $$;
    return 0;
}
sub UnLock($)
{
    my ($self) = @_;
    my $idx    = $self->idx();

    return 1
	if (!$self->LOCKED());

    DBQueryWarn("update geni_tickets set locked=NULL where idx='$idx'")
	or return -1;
    
    $self->{'LOCKED'} = 0;
    return 0;
}

537
538
sub SetSlice($$)
{
539
    my ($self, $slice) = @_;
540
    
541
    $self->{'slice'} = $slice;
542
543
544
    return 0;
}

545
546
547
#
# Return the outstanding ticket for a slice.
#
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
sub SliceTicket($$)
{
    my ($class, $slice) = @_;

    my $slice_uuid = $slice->uuid();

    my $query_result =
	DBQueryWarn("select idx from geni_tickets ".
		    "where slice_uuid='$slice_uuid'");
    return undef
	if (!$query_result);
    return undef
	if ($query_result->numrows != 1);

    my ($idx) = $query_result->fetchrow_array();
    return GeniTicket->Lookup($idx);
}

566
567
568
569
570
571
572
573
574
575
576
577
#
# Return the rspec in XML for the ticket.
#
sub rspecXML($)
{
    my ($self) = @_;

    return undef
	if (! ref($self));
    return undef
	if (!defined($self->rspec()));

578
    return GeniXML::Serialize($self->rspec());
579
580
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
581
582
583
584
585
586
587
588
#
# Populate the ticket with some stuff, which right now is just the
# number of node we are willing to grant.
#
sub Grant($$)
{
    my ($self, $count) = @_;

Leigh B. Stoller's avatar
Leigh B. Stoller committed
589
    return -1
Leigh B. Stoller's avatar
Leigh B. Stoller committed
590
591
592
593
594
595
	if (! ref($self));

    $self->{'count'} = $count;
    return 0;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
596
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
597
598
599
# Store the given ticket in the DB. We only do this for signed tickets,
# so we have a record of them. We store them on the server and the client
# side.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
600
#
601
sub Store($;$)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
602
{
603
    my ($self, $flags) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
604
605
    my @insert_data  = ();

606
607
608
    $flags = 0
	if (!defined($flags));

609
610
611
612
613
    my $idx         = $self->idx();
    my $seqno       = $self->seqno();
    my $target_uuid = $self->target_uuid();
    my $owner_uuid  = $self->owner_uuid();
    my $ticket_uuid = $self->ticket_uuid();
614
615
    my $expires     = $self->redeem_before() || $self->expires();
    my $slice_uuid  = $self->slice_uuid();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
616

Leigh B. Stoller's avatar
Leigh B. Stoller committed
617
    #
618
    # For a locally created/signed ticket, seqno=idx. 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
619
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
620
621
622
623
    if (!defined($idx)) {
	$idx = TBGetUniqueIndex('next_ticket', 1);
	$self->{'idx'} = $idx;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
624
625
626
    # Now tack on other stuff we need.
    push(@insert_data, "created=now()");
    push(@insert_data, "idx='$idx'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
627
    push(@insert_data, "seqno='$seqno'");
628
    push(@insert_data, "ticket_uuid='$ticket_uuid'");
629
    push(@insert_data, "target_uuid='$target_uuid'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
630
    push(@insert_data, "owner_uuid='$owner_uuid'");
631
    push(@insert_data, "slice_uuid='$slice_uuid'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
632
    push(@insert_data, "redeem_before='$expires'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
633
634
635
636
637
638
639
640
    
    my $safe_ticket = DBQuoteSpecial($self->ticket_string());
    push(@insert_data, "ticket_string=$safe_ticket");

    # Insert into DB.
    DBQueryWarn("insert into geni_tickets set " . join(",", @insert_data))
	or return -1;

641
642
643
644
645
    if (! ($flags & TICKET_NOSTATS)) {
	if (GeniUsage->NewTicket($self)) {
	    print STDERR
		"GeniTicket::Store: GeniUsage->NewTicket($self) failed\n";
	}
646
647
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
648
649
    $tickets{"$idx"}  = $self;
    $self->{'stored'} = 1;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
650
651
652
    return 0;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
653
#
654
# When we redeem a ticket, we update the history file and delete it.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
655
#
656
sub Redeem($)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
657
658
659
660
661
{
    my ($self) = @_;

    return -1
	if (!ref($self));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
662

663
664
665
666
667
668
669
670
671
672
673
674
    return $self->Delete(TICKET_REDEEMED);
}

#
# Sign the ticket before returning it.
#
sub Sign($)
{
    my ($self) = @_;

    return -1
	if (!ref($self));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
675

676
    #
677
    # Every ticket/credential gets its own uuid.
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
    $self->{'ticket_uuid'} = GeniUtil::NewUUID();

    $self->RunSigner() == 0
	or return -1;

    return 0;
}

#
# Sign the ticket before returning it. We capture the output, which is
# in XML. 
#
sub RunSigner($$)
{
    my ($self) = @_;

    return -1
	if (!ref($self));

    my $idx         = $self->seqno();
    my $expires     = $self->redeem_before();
    my $target_cert = $self->target_cert()->cert();
    my $owner_cert  = $self->owner_cert()->cert();
    my $ticket_uuid = $self->{'ticket_uuid'};
703
    my $rspec_xml   = GeniXML::Serialize($self->rspec());
704

Leigh B. Stoller's avatar
Leigh B. Stoller committed
705
    # Convert to GMT.
706
    $expires = POSIX::strftime("20%y-%m-%dT%H:%M:%SZ",
Leigh B. Stoller's avatar
Leigh B. Stoller committed
707
708
			       gmtime(str2time($expires)));

Leigh B. Stoller's avatar
Leigh B. Stoller committed
709
710
711
712
713
    #
    # Create a template xml file to sign.
    #
    my $template =
	"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
714
	"<credential xml:id=\"ref1\">\n".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
715
	" <type>ticket</type>\n".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
716
	" <serial>$idx</serial>\n".
717
	" <owner_gid>$owner_cert</owner_gid>\n".
718
	" <target_gid>$target_cert</target_gid>\n".
719
	" <uuid>$ticket_uuid</uuid>\n".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
720
	" <expires>$expires</expires>\n".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
721
722
	" <ticket>\n".
	"  <can_delegate>1</can_delegate>\n".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
723
	"  <redeem_before>$expires</redeem_before>\n".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
724
	"  $rspec_xml\n".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
725
726
727
728
729
730
731
732
733
734
735
736
737
738
	" </ticket>\n".	
        "</credential>\n";

    my ($fh, $filename) = tempfile(UNLINK => 0);
    return -1
	if (!defined($fh));

    print $fh $template;
    close($fh);

    #
    # Fire up the signer and capture the output. This is the signed ticket
    # that is returned. 
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
739
    if (! open(SIGNER, "$SIGNCRED -c $CMCERT $filename |")) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
740
741
742
743
744
745
746
	print STDERR "Could not sign $filename\n";
	return -1;
    }
    my $ticket = "";
    while (<SIGNER>) {
	$ticket .= $_;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
747
748
749
750
    if (!close(SIGNER)) {
	print STDERR "Could not sign $filename\n";
	return -1;
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
751
    unlink($filename);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
752
    $self->{'ticket_string'} = $ticket;
753
754
755
    return 0;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
756
757
#
# Release a ticket. Need to release the nodes ...
758
# Used by the CM.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
759
#
760
sub Release($$)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
761
{
762
    my ($self, $flag) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
763

764
765
766
    return -1
	if (! ref($self));

767
    # Older tickets do not have this.
768
769
770
771
772
773
774
775
776
777
778
779
    return 0
	if (!defined($self->slice_uuid()) || $self->slice_uuid() eq "");

    my $experiment = Experiment->Lookup($self->slice_uuid());
    if (!defined($experiment)) {
	$self->Delete($flag);
	return 0;
    }
    my $pid     = $experiment->pid();
    my $eid     = $experiment->eid();
    my @nodeids = ();
    my @nodes   = ();
780
    my @vhosts  = ();
781

782
    foreach my $ref (GeniXML::FindNodes("n:node",
783
					$self->rspec())->get_nodelist()) {
784
785
	# Skip lan nodes; they are fake.
	next
786
	    if (GeniXML::IsLanNode($ref));
787
	
788
789
	# Skip remote nodes.
	next
790
	    if (!GeniXML::IsLocalNode($ref));
791
	
792
	my $resource_id = GeniXML::GetNodeId($ref);
793
794
	my $vnode_id    = GeniXML::GetVnodeId($ref);
	if (!defined($resource_id) || !defined($vnode_id)) {
795
	    print STDERR "No resource id for node in ticket\n";
796
	    print GeniXML::Serialize($ref);
797
798
	    return -1;
	}
799

800
	my $node = GeniUtil::LookupNode($vnode_id);
801
802
803
804
805
806
807
808
809
810
811
812
813
814
	next
	    if (!defined($node));

	my $reservation = $node->Reservation();
	next
	    if (!defined($reservation));

	#
	# If the node is still in the experiment and not incorporated,
	# release it. genisliver_idx is not defined until ticket redeemed.
	#
	if ($reservation->SameExperiment($experiment)) {
	    my $restable = $node->ReservedTableEntry();
	    if (defined($restable) &&
815
816
		(!defined($restable->{'genisliver_idx'}) ||
		 $restable->{'genisliver_idx'} == 0)) {
817
818
819
820
821
822
		# Bridge nodes could be listed twice, and nfree does not like
		# it when a node is in the list twice.
		if (! grep {$_ eq $node->node_id()} @nodeids) {
		    push(@nodeids, $node->node_id());
		    push(@nodes, $node);
		}
823
824
825
826
827
828
829

		# So we can tell if we need to deallocate a physical
		# host once all the VMs on it are gone. 
		if ($node->isvirtnode() && !$node->sharing_mode()) {
		    push(@vhosts, $node->phys_nodeid())
			if (! grep {$_ eq $node->phys_nodeid()} @vhosts);
		}
830
831
832
833
	    }
	}
    }
    if (@nodeids) {
834
835
836
837
838
	#
	# XXX Need to determine when a node needs to be reloaded.
	#
	#system("export NORELOAD=1; $NFREE -x -q $pid $eid @nodeids");
	system("$NFREE -x -q $pid $eid @nodeids");
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
	return -1
	    if ($?);
    }
    foreach my $node (@nodes) {
	$node->Refresh();
    }

    @nodes = @nodeids = ();
    #
    # Now go through the vhosts that belong to us, and see if we can
    # free them cause there are no longer VMs on them.
    #
    foreach my $pnode_id (@vhosts) {
	my $pnode = Node->Lookup($pnode_id);
	if (!defined($pnode)) {
	    print STDERR "ReleaseTicket: *** No such pnode $pnode_id\n";
	    next;
	}
	
	my $reservation = $pnode->Reservation();
	next
	    if (!defined($reservation) ||
		!$reservation->SameExperiment($experiment));
	
	my @vnodes = ();
	if ($pnode->VirtualNodes(\@vnodes) != 0) {
	    print STDERR
		"ReleaseTicket: *** Could not get vnode list for $pnode_id\n";
	    return -1;
	}
	if (!@vnodes) {
	    push(@nodeids, $pnode->node_id());
	    push(@nodes, $pnode);
	}
    }
    if (@nodeids) {
	system("$NFREE -x -q $pid $eid @nodeids");
	return -1
	    if ($?);
878
879
880
881
    }
    foreach my $node (@nodes) {
	$node->Refresh();
    }
882
    
883
884
885
886
    $self->Delete($flag);
    return 0;
}

887
888
889
890
891
892
893
894
895
896
897
898
899
900
#
# Equality test for two tickets.
#
sub SameTicket($$)
{
    my ($self, $other) = @_;

    # Must be a real reference. 
    return 0
	if (! (ref($self) && ref($other)));

    return $self->idx() == $other->idx();
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
#
# Check if ticket has expired. Use the DB directly.
#
sub Expired($)
{
    my ($self) = @_;
    my $idx    = $self->idx();

    my $query_result =
	DBQueryWarn("select idx from geni_tickets ".
		    "where idx='$idx' and ".
		    "      (UNIX_TIMESTAMP(now()) > ".
		    "       UNIX_TIMESTAMP(redeem_before))");
    
    return $query_result->numrows;
}

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
#
# List all tickets for a user.
#
sub ListUserTickets($$$)
{
    my ($class, $user, $pref) = @_;
    my @result = ();

    my $user_uuid = $user->uuid();
    my $query_result = DBQueryWarn("select idx from geni_tickets ".
				   "where owner_uuid='$user_uuid'");
    return -1
	if (!$query_result);

    while (my ($idx) = $query_result->fetchrow_array()) {
	my $ticket = GeniTicket->Lookup($idx);
	return -1
	    if (!defined($ticket));
	push(@result, $ticket);
    }

    @$pref = @result;
    return 0;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
943
944
# _Always_ make sure that this 1 is at the end of the file...
1;