summaryrefslogtreecommitdiff
path: root/cgissi.fcgi
blob: 09e3c5ec37ec2ad07a282443d4bbd4976e1b5c7d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
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
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
#!/usr/bin/perl

# \file
# cgissi.fcgi -- A FastCGI script to emulate Server-Side Includes
#
# At the time of writing, it supports #include, #fsize and #flastmod
#

use warnings;
use strict;

use Digest::MD5 qw(md5_base64);
use File::Spec;
use FCGI;
use POSIX qw(strftime);

# Content cache to avoid regenerating pages unless it's absolutely necessary
#
# This hash maps between the full local path to the URL data 
# and a hash containing cache data. For example:
#
# { "/foo/bar/baz" => 
# 	{ last_modified => 0123456789,
# 	  data_digest => "base64(MD5($data))"
# 	  data_last_modified => 0123456789,
#	  data => "generated page content",
#	  dependencies => 
#	  	{ "/foo/bar/bat" => 
#	  		{ last_modified => 0123456789,
#	  		  commands => 
#				[
#				  { command => "include" | "fsize" | "flastmod",
#				    start_offset = 123,
#				    end_offset = 456
#				  },
#				  { command => "include" | "fsize" | "flastmod",
#				    start_offset = 678,
#				    end_offset = 901
#				  }
#				]
#			}
#		}
#	} 
# }
#
my %cache;

# Request object
my $request = FCGI::Request();

# Loop until the server tells us to quit
while ($request->Accept() >= 0) {
	# Get document root for this request
	my $docroot = $ENV{DOCUMENT_ROOT};

	# Get path of item for this request
	# Yes, this is hacky. It appears that REDIRECT_PATH contains
	# the destination document resulting from content negotiation.
	# As this is an absolute path, we strip the document root from it.
	my ($path) = ($ENV{REDIRECT_PATH} =~ m/$docroot(.*)/);

	# Find item in cache
	my $cachedata = $cache{$docroot . $path};

	# Determine if we need to (re)generate page
	validate_cache_entry($docroot, $path, $cachedata);

	# Refetch cache entry 
	# (as it may have been created by validate_cache_entry)
	$cachedata = $cache{$docroot . $path};

	# TODO It would be nice to send 304 responses where appropriate
	# and also to pay attention to conditional requests namely
	# If-(None-)Match and If-(Un)Modified-Since

	# Cache-related headers
	print "ETag: " . $$cachedata{data_digest} . "\r\n";
	# Don't use %Z here, as perl's strftime appears to assume that the 
	# time is always in the local timezone
	print "Last-Modified: " . strftime("%a, %d %b %Y %H:%M:%S GMT", 
			gmtime($$cachedata{data_last_modified})) . "\r\n";

	# Send Content-Type header
	print "Content-Type: text/html; charset=ISO-8859-1\r\n";
	print "\r\n";

	# And the page data
	print $$cachedata{data};
}

################################################################################

# Run an include command
#
# \param filepath  The full path of the file to include
# \param data      Data buffer to append file data to (reference)
#
sub do_include
{
	my ($filepath, $data) = @_;

	if (-e $filepath) {
		# Unlike Zeus, we don't recursively apply SSI.
		open FILE, $filepath;
		{
			local $/ = undef;
			$$data .= <FILE>;
		}
		close FILE;
	}
}

# Run a fsize command
#
# \param filepath  The full path of the file to measure the size of
# \param data      Data buffer to append size to (reference)
#
sub do_fsize
{
	my ($filepath, $data) = @_;
	my @units = ( "B", "kB", "MB", "GB", "TB" ); # should be sufficient ;)

	if (-e $filepath) {
		my $size = -s $filepath;
		my $index = 0;

		while ($size > 1000) {
			$size /= 1024;
			$index++;
		}

		$$data .= sprintf("%.1f %s", $size, $units[$index]);
	}
}

# Run a flastmod command
#
# \param filepath  The full path of the file to get the modification time of
# \param data      Data buffer to append modification time to (reference)
#
sub do_flastmod
{
	my ($filepath, $data) = @_;

	if (-e $filepath) {
		my $mod_string = 
			strftime("%d %b %Y %R", gmtime((stat($filepath))[9]));

		$$data .= $mod_string . " UTC";
	}
}

# Process an include command
#
# \param command  The command string to process
# \param data     Data buffer to append output to (reference)
# \param docroot  The document root
# \param path     Path of the current document, relative to ::docroot
# \return The full path of the included file
#
sub process_include_command
{
	my ($command, $data, $docroot, $path) = @_;
	my $filepath;

	if ($command =~ /file=/) {
		my ($relpath) = ($command =~ m/file="(.*)"/);
		my ($vol, $dirs, $file) = 
				File::Spec->splitpath($docroot . $path);
		$filepath = File::Spec->rel2abs($relpath,
				File::Spec->catpath($vol, $dirs, ""));
	} elsif ($command =~ /virtual=/) {
		my ($vpath) = ($command =~ m/virtual="(.*)"/);
		if ($vpath =~ m#^/.*#) {
			$filepath = $docroot . $vpath;
		} else {
			my ($vol, $dirs, $file) = 
					File::Spec->splitpath($docroot . $path);
			$filepath = File::Spec->rel2abs($vpath,
					File::Spec->catpath($vol, $dirs, ""));
		}
	}

	do_include($filepath, $data);

	return $filepath;
}

# Process an fsize command
#
# \param command  The command string to process
# \param data     Data buffer to append output to (reference)
# \param docroot  The document root
# \param path     Path of the current document, relative to ::docroot
# \return The full path of the included file
#
sub process_fsize_command
{
	my ($command, $data, $docroot, $path) = @_;
	my $filepath;

	if ($command =~ /file=/) {
		my ($relpath) = ($command =~ m/file="(.*)"/);
		my ($vol, $dirs, $file) = 
				File::Spec->splitpath($docroot . $path);
		$filepath = File::Spec->rel2abs($relpath,
				File::Spec->catpath($vol, $dirs, ""));
	} elsif ($command =~ /virtual=/) {
		my ($vpath) = ($command =~ m/virtual="(.*)"/);
		if ($vpath =~ m#^/.*#) {
			$filepath = $docroot . $vpath;
		} else {
			my ($vol, $dirs, $file) = 
					File::Spec->splitpath($docroot . $path);
			$filepath = File::Spec->rel2abs($vpath,
					File::Spec->catpath($vol, $dirs, ""));
		}
	}

	do_fsize($filepath, $data);

	return $filepath;
}

# Process an flastmod command
#
# \param command  The command string to process
# \param data     Data buffer to append output to (reference)
# \param docroot  The document root
# \param path     Path of the current document, relative to ::docroot
# \return The full path of the included file
#
sub process_flastmod_command
{
	my ($command, $data, $docroot, $path) = @_;
	my $filepath;

	if ($command =~ /file=/) {
		my ($relpath) = ($command =~ m/file="(.*)"/);
		my ($vol, $dirs, $file) = 
				File::Spec->splitpath($docroot . $path);
		$filepath = File::Spec->rel2abs($relpath,
				File::Spec->catpath($vol, $dirs, ""));
	} elsif ($command =~ /virtual=/) {
		my ($vpath) = ($command =~ m/virtual="(.*)"/);
		if ($vpath =~ m#^/.*#) {
			$filepath = $docroot . $vpath;
		} else {
			my ($vol, $dirs, $file) = 
					File::Spec->splitpath($docroot . $path);
			$filepath = File::Spec->rel2abs($vpath,
					File::Spec->catpath($vol, $dirs, ""));
		}
	}

	do_flastmod($filepath, $data);

	return $filepath;
}

# Complete parsing of and process a command string
#
# \param template      Open file handle of template input
# \param char          Current input character
# \param command       The command string read so far
# \param data          Buffer to append data into (reference)
# \param docroot       The document root
# \param path          Path of the current document relative to ::docroot
# \param start_offset  Offset into template input of start of SSI command
# \param cacheentry    The cache entry for the current document
# 
sub process_command
{
	my ($template, $char, $command, $data, 
		$docroot, $path, $start_offset, $cacheentry) = @_;
	my $keyword = lc($command);
	my $dash_count = 0;
	my $filepath;

	# See state machine documentation in generate_page_full for details of
	# how this function works.

	# Reject command if it's one we know nothing about
	if ($keyword ne "include" && $keyword ne "fsize" &&
			$keyword ne "flastmod") {
		# ProcessCmd -> Initial transition occurs in generate_page_full
		$$data .= "<!--#" . $command . $char;
		return;
	}

	# Process the current input character
	if ($char eq '-') {
		# ProcessCmd -> ProcCmdDash
		$dash_count++;
	} else {
		# ProcessCmd -> ProcessCmd
		$command .= $char;
	}

	# Read rest of command string, then process command
	while ($char = getc($template)) {
		if ($char eq '-') {
			# ProcessCmd -> ProcCmdDash / ProcCmdDash -> ProcCmdCT
			$dash_count++;
		} elsif ($dash_count == 2 && $char eq '>') {
			# Run command (ProcCmdCT -> Initial transition occurs
			# in generate_page_full)
			if ($keyword eq "include") {
				$filepath = process_include_command($command, 
						$data, $docroot, $path);
			} elsif ($keyword eq "fsize") {
				$filepath = process_fsize_command($command, 
						$data, $docroot, $path);
			} elsif ($keyword eq "flastmod") {
				$filepath = process_flastmod_command($command, 
						$data, $docroot, $path);
			}

			$$cacheentry{dependencies}{$filepath}{last_modified} = 
					(stat($filepath))[9];
			push(@{$$cacheentry{dependencies}{$filepath}{commands}},
					{ command => $keyword, 
					  start_offset => $start_offset, 
					  end_offset => tell($template)
					});
			return;
		} else {
			# ProcessCmd / ProcCmdDash / ProcCmdCT -> ProcessCmd
			while ($dash_count > 0) {
				$command .= "-";
				$dash_count--;
			}
			$command .= $char;
		}
	}
}

# Fully generate a page. 
# This involves parsing the page source looking for SSI commands.
#
# \param docroot  The document root
# \param path     Path of the current document relative to ::docroot
# 
sub generate_page_full
{
	my ($docroot, $path) = @_;
	my $data = "";
	my $in_tag = 0;
	my $had_pling = 0;
	my $dash_count = 0;
	my $in_comment = 0;
	my $had_hash = 0;
	my $command = "";
	my $start_offset = 0;

	if (! -e $docroot . $path) {
		# File doesn't exist
		$cache{$docroot . $path}{data} = $data;
		$cache{$docroot . $path}{data_digest} = 
				'"' . md5_base64($data) . '"';
		$cache{$docroot . $path}{data_last_modified} = time;
		return;
	}

	open my $template, $docroot . $path;

	# Save document modification time into cache
	my $lastmod = (stat($docroot . $path))[9];
	$cache{$docroot . $path} = { last_modified => $lastmod }; 
	my $cacheentry = $cache{$docroot . $path};

	# Parse document template, looking for SSI comments
	#
	# This is basically a state machine, thus:
	#
	# State:	Input:		Next state:	Output:
	#
	# Initial	[^<]		Initial		Input character
	# Initial	'<'		InTag		None
	#
	# InTag		[^!]		Initial		'<' followed by input
	# InTag		!		InTagPling	None
	#
	# InTagPling	[^-]		Initial		'<!' followed by input
	# InTagPling	'-'		InTagPling1	None
	#
	# InTagPling1	[^-]		Initial		'<!-' followed by input
	# InTagPling1	'-'		InComment	None
	#
	# InComment	[^#]		Initial		'<!--' followed by input
	# InComment	'#'		InCommentHash	None
	#
	# InCommentHash	[^a-zA-Z]	ProcessCmd	None
	# InCommentHash	[a-zA-Z]	InCommentHash	None [1]
	#
	# ProcessCmd	n/a		Initial		'<!--#' followed by the 
	# 						command read in 
	# 						InCommentHash followed 
	# 						by input [2]
	# ProcessCmd	[^-]		ProcessCmd	None
	# ProcessCmd	'-'		ProcCmdDash	None
	#
	# ProcCmdDash	[^-]		ProcessCmd	None [3]
	# ProcCmdDash	'-'		ProcCmdCT	None
	#
	# ProcCmdCT	[^>]		ProcessCmd	None [4]
	# ProcCmdCT	'>'		Initial		Command specific [5]
	#
	# Notes:
	#
	# 1. This transition causes the input to be buffered as a command string
	# 2. This transition only happens if the command read so far is not
	#    recognised
	# 3. A dash is appended to the command string, however
	# 4. A '>' is appended to the command string, however
	# 5. The output is determined by running the command.
	#
	while (defined(my $char = getc($template))) {
		if (!$in_comment && !$in_tag && $char eq '<') {
			# Initial -> InTag
			$start_offset = tell($template);
			$in_tag = 1;
		} elsif ($in_tag) {
			if (!$had_pling) {
				if ($char ne '!') {
					# InTag -> Initial
					$data .= "<" . $char;
					$in_tag = 0;
				} elsif ($char eq '!') {
					# InTag -> InTagPling
					$had_pling = 1;
				}
			} else {
				if ($char ne '-') {
					# InTagPling(1) -> Initial
					$data .= "<!";
					while ($dash_count > 0) {
						$data .= "-";
						$dash_count--;
					}
					$data .= $char;

					$had_pling = 0;
					$in_tag = 0;
				} else {
					# InTagPling -> InTagPling1
					$dash_count++;

					if ($dash_count == 2) {
						# InTagPling1 -> InComment
						$dash_count = 0;
						$in_comment = 1;
						$had_pling = 0;
						$in_tag = 0;
					}
				}
			}
		} elsif ($in_comment) {
			if (!$had_hash) {
				if ($char ne '#') {
					# InComment -> Initial
					$data .= "<!--" . $char;
					$in_comment = 0;
				} else {
					# InComment -> InCommentHash
					$command = "";
					$had_hash = 1;
				}
			} else {
				my $c = lc($char);

				if ('a' le $c && $c le 'z') {
					# InCommentHash -> InCommentHash
					$command .= $char;
				} else {
					# InCommentHash -> ProcessCmd
					process_command($template, $char, 
						$command, \$data, $docroot,
						$path, $start_offset, 
						$cacheentry);

					# ProcessCmd/ProcCmdCT -> Initial
					$had_hash = 0;
					$in_comment = 0;
				}
			}
		} else {
			# Initial -> Initial
			$data .= $char;
		}
	}

	close $template;

	# Save generated page data in cache
	$$cacheentry{data} = $data;
	$$cacheentry{data_digest} = '"' . md5_base64($data) . '"';
	$$cacheentry{data_last_modified} = time;
}

# Partially generate a page.
# This involves using cached information to inject SSI data into a page
#
# \param docroot  The document root
# \param path     The path of the current document, relative to ::docroot
sub generate_page_partial
{
	my ($docroot, $path) = @_;

	if (! -e $docroot . $path) {
		# File doesn't exist
		$cache{$docroot . $path}{data} = "";
		$cache{$docroot . $path}{data_digest} = 
				'"' . md5_base64("") . '"';
		$cache{$docroot . $path}{data_last_modified} = time;
		return;
	}
	
	# Get dependency hash
	my $deps = $cache{$docroot . $path}{dependencies};

	# Build command map for this page
	my %cmds;
	foreach my $dep (keys %{$deps}) {
		my $index = 0;
		foreach my $cmd (@{$$deps{$dep}{commands}}) {
			# The key here is the index into the commands array
			# prepended to the dependency URL. This ensures that
			# we have unique map entries for each command.
			$cmds{$index . $dep} = $cmd;
			$index++;
		}
	}

	# Sort command map by start_offset
	my @sorted = 
		sort { # Unpack dependency URLs and command array indices
		       my ($a_index, $a_dep) = ($a =~ m/([0-9]+)(.*)/);
		       my ($b_index, $b_dep) = ($b =~ m/([0-9]+)(.*)/);
		       # Now compare the start offsets
		       $$deps{$a_dep}{commands}[$a_index]{start_offset} <=> 
		       $$deps{$b_dep}{commands}[$b_index]{start_offset} 
		     } 
			keys %cmds;

	my $data = "";
	my $temp;
	my $curpos = 0;
	my $template_length = 0;

	# Open requested document
	open TEMPLATE, $docroot . $path;

	# Find its length
	seek(TEMPLATE, 0, 2);
	$template_length = tell(TEMPLATE);
	seek(TEMPLATE, 0, 0);

	# Iterate through commands, loading intervening chunks of template
	foreach my $cmd (@sorted) {
		# Unpack dependency URL and command array index
		my ($index, $dep) = ($cmd =~ m/([0-9]+)(.*)/);
		my $vars = $$deps{$dep};
		my $length = 
			$$vars{commands}[$index]{start_offset} - $curpos - 1;

		# Update last_modified time of this dependency (at least one
		# must have changed for a partial regeneration to occur)
		$$vars{last_modified} = (stat($dep))[9];

		# Read template input from end of previous dependency 
		# to the start of this one
		read(TEMPLATE, $temp, $length);

		# Append it to our data buffer
		$data .= $temp;

		# Run this SSI command
		if ($$vars{commands}[$index]{command} eq "include") {
			do_include($dep, \$data);
		} elsif ($$vars{commands}[$index]{command} eq "fsize") {
			do_fsize($dep, \$data);
		} elsif ($$vars{commands}[$index]{command} eq "flastmod") {
			do_flastmod($dep, \$data);
		}

		# Skip over SSI command in template input
		$curpos = $$vars{commands}[$index]{end_offset};

		seek(TEMPLATE, $curpos, 0);
	}

	# Read any remaining template input
	read(TEMPLATE, $temp, $template_length - $curpos);

	$data .= $temp;

	close TEMPLATE;

	# Update document cache
	$cache{$docroot . $path}{data} = $data;
	$cache{$docroot . $path}{data_digest} = '"' . md5_base64($data) . '"';
	$cache{$docroot . $path}{data_last_modified} = time;
}

# Validate a cache entry
# 
# \param docroot  The document root
# \param path     The path of the current document, relative to ::docroot
# \param entry    Current cache entry or undef if none
#
sub validate_cache_entry
{
	my ($docroot, $path, $entry) = @_;

	if (!$entry) {
		# No entry -- generate one
		generate_page_full($docroot, $path);
		return;
	}

	if ((stat($docroot . $path))[9] > $$entry{last_modified}) {
		# Page modified -- fully regenerate page
		generate_page_full($docroot, $path);
		return;
	}

	while (my ($dep, $data) = each(%{$entry->{dependencies}})) {
		if ((stat($dep))[9] > $$data{last_modified}) {
			# Dependency changed -- partially regenerate page
			generate_page_partial($docroot, $path);
			return;
		}
	}

	# Otherwise, the cached data is valid
}