aboutsummaryrefslogtreecommitdiffstats
path: root/asn1c/webcgi/asn1c.cgi
blob: 07966774f712edff892b0c6eb11cb38ea6118bcd (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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
#!/usr/bin/perl -w
#
# $Id$
#

############################################################################
# The following preferences may be modified to match the local environment #
############################################################################

# Directory with the users data.
$TMPDIR = '/tmp/asn1c-cgi-jail/';
$SUIDHelper = './asn1c-suid-helper';
$SkeletonsDir = '/usr/local/share/asn1c';	# Will be needed only once
$CompilerLocation = '/usr/local/bin/asn1c';	# asn1c binary location
$HelpDBFile = $TMPDIR . '/var/db/Help-DB';	# Help requests database
$HashProgramPath = 'md5';			# Program to hash the input
$DM = 0750;					# Directory mode for all mkdirs
$MaxHistoryItems = 5;				# Number of items in History
$DynamicHistory = 'yes';			# Full/Short history
$safeFilenameRE = '[a-zA-Z0-9_]+[.a-zA-Z0-9_-]{0,200}';  # Safe filename regex
$safeTimeRE = '[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}';
$ASN1C_Page = 'http://lionet.info/asn1c';
$HelpEmail = 'asn1c@lionet.info';
$defaultUserEmail = 'your@email-for-reply';
$DataERR = 65;					# EX_DATAERR from <sysexits.h>

$warn = '<CENTER><FONT SIZE=+1><B>';
$unwarn = '</B></FONT></CENTER>';

$OpEnvFailed = 'Failed to create the operations\' environment:';
$RandFailed = 'No source of randomness';
$SandBoxInitFailed = 'User playground initialization failed';

$myName = $ENV{SCRIPT_NAME};	# URL of this particular script (without args)

$homePath = "<FONT FACE=Courier SIZE=-1>"
	. "<A HREF=http://lionet.info>Home</A>"
	. " &gt;&gt; <A HREF=$ASN1C_Page>asn1c</A>"
	. " &gt;&gt; <A HREF=$ASN1C_Page/asn1c.cgi>Free Online ASN.1 Compiler</A>"
	. "</FONT><P>";

###################################################
# The code below rarely requires any modification #
###################################################

use CGI qw/param cookie header upload escapeHTML/;

$|=1;	# Enable AutoFlush (for older versions of Perl)

my $redirect = '';	# No redirection by default
my $redirect_bottom = '';	# No redirection text by default
my $content = '';	# Default content is empty

sub IssueRedirect() {
	$redirect = "<META HTTP-EQUIV=\"Refresh\" "
		. "CONTENT=\"5; URL=$myName\">";
	$redirect_bottom = "<P><CENTER>This page will <A HREF=$myName>disappear</A> in 5 seconds.</CENTER>"
}

# If something goes wrong, this function is invoked to display the error message
sub bark($@) {
	local $_ = join("<BR>\n", @_);
	$content = $warn . $_ . $unwarn;
	goto PRINTOUT;
}

# Make the directory name containing session files for the given Session ID
sub makeSessionDirName($$) {
	my $pfx = shift;	# Prefix is the name of the top-level directory
	my $sid = shift;	# Session identifier (md5)
	$pfx . '/sessions/' . $sid . '/';
}

# Create ISO 8601 time string: "YYYY-MM-DDThh:mm:ss"
my $cachedTime;
sub isoTime() {
	return $cachedTime if $cachedTime;
	my @tm = localtime(time);

	$tm[5] += 1900;
	$tm[4] += 1;

	# Insert leading zeros
	for(my $i = 0; $i < 5; $i++) {
		$tm[$i] =~ s/^(.)$/0$1/;
	}

	$cachedTime = "$tm[5]-$tm[4]-$tm[3]T$tm[2]:$tm[1]:$tm[0]";
}

# Create the necessary environment for chrooting into.
sub prepareChrootEnvironment() {
	return 1 if(-d $TMPDIR);	# Envuronment already exists
	mkdir $TMPDIR, $DM, or bark($OpEnvFailed, $!);	# Global directory
	mkdir $TMPDIR . 'sessions', $DM or bark($OpEnvFailed, $!); # sessions
	mkdir $TMPDIR . 'bin', $DM or bark($OpEnvFailed, $!);	# asn1c location
	mkdir $TMPDIR . 'skeletons', $DM or bark($OpEnvFailed, $!); # asn1c data
	mkdir $TMPDIR . 'var', $DM or bark($OpEnvFailed, $!);
	mkdir $TMPDIR . 'var/db', $DM or bark($OpEnvFailed, $!);
	if(-d '/lib') {
		# Merge in dynamic libc
		mkdir $TMPDIR . 'lib', $DM or bark($OpEnvFailed, $!);
		system("cd $TMPDIR/lib && "
			. "for i in"
				. " /lib/ld-linux.*"	# Linux ELF loader
				. " /lib/libc.*"	# Standard C library
				. " /lib/libm.*"	# Math library
			. '; do ln $i; done');
	} elsif(-d '/usr/lib') {
		# There's no /lib on MacOS
		mkdir $TMPDIR . 'usr', $DM or bark($OpEnvFailed, $!);
		mkdir $TMPDIR . 'usr/lib', $DM or bark($OpEnvFailed, $!);
		mkdir $TMPDIR . 'usr/lib/system', $DM or bark($OpEnvFailed, $!);
		system("cd $TMPDIR/usr/lib && "
			. "for i in"
				. " /usr/lib/libc.*"
				. " /usr/lib/libSystem.*"
				. " /usr/lib/system/libmath*"
				. " /usr/lib/dy*"
			. '; do ln $i; done');
	}
	if(-d '/usr/libexec') {
		# FreeBSD ELF loader
		mkdir $TMPDIR . 'usr', $DM;
		mkdir $TMPDIR . 'usr/libexec',$DM or bark($OpEnvFailed, $!);
		system("cd $TMPDIR/usr/libexec && "
			. 'for i in /usr/libexec/ld-elf.*; do ln $i; done');
	}
	system("cp $CompilerLocation $TMPDIR/bin 2>/dev/null") == 0
		or bark($OpEnvFailed, $!);
	system("cp -r $SkeletonsDir/* $TMPDIR/skeletons >/dev/null 2>&1") == 0
			or bark($OpEnvFailed, $!);
	return 1;
}

sub makeArchive($$) {
	my $TMPDIR = shift;
	my $sandbox = shift;
	my $archName = $sandbox . '/+Archive.tgz';

	if(! -f $archName) {
		system("cd $sandbox && "
			. "for i in ./*.[ch]; do if [ -L \$i ]; then"
			. " cp $TMPDIR/skeletons/\$i \$i.-;"
			. " mv \$i.- \$i;"
			. " fi done && tar --dereference --ignore-failed-read --owner nobody --group nobody -zcf +tmp." . $$ . " *.[ch] Makefile* +Compiler.Log *.asn *.asn1"
			. " && rm -f ./*.[ch] ./Makefile*"
			. " && mv ./+tmp." . $$ . " $archName"
			. " || rm -f ./+tmp." . $$);
		undef unless -f $archName;
	}

	$archName;
}

my $EnvironmentSetOK = prepareChrootEnvironment();

#
# Record user's email.
#
$userEmail = cookie('userEmail');
$userEmail = $defaultUserEmail unless defined($userEmail);
$tmpEmail = param('email');
if(defined($tmpEmail)) {
	unless($tmpEmail =~ /^\s*([a-z0-9._+-]+@[a-z0-9.+-]+)\s*$/i) {
		bark("Invalid email address: "
			. "<B><FONT COLOR=darkred>$tmpEmail</FONT></B>");
	}
	my $previousEmail = $userEmail;
	$userEmail = $1;
	if($userEmail eq $defaultUserEmail) {
		IssueRedirect();
		bark("Please enter <FONT COLOR=red>your own</FONT> "
			. "valid email address, "
			. "instead of default \"<FONT COLOR=darkred>$defaultUserEmail</FONT>\"");
	}
	if($userEmail ne $previousEmail) {
		# Refresh cookie contents.
		my $ck = cookie(-name=>'userEmail',
			-value=>$userEmail,
			-path=>'/', -expires=>'+1d');
		print "Set-Cookie: " . $ck . "\n";
	}
}

#
# Check if full history requested.
#
$HistoryShow = cookie('HistoryShow');
$HistoryShow = '' unless $HistoryShow;
$tmpHSParam = param('history');	# Control cookie setting
if (defined($tmpHSParam)
 && $tmpHSParam ne $HistoryShow
 && $tmpHSParam =~ /^(full|short)$/) {
	$HistoryShow = $tmpHSParam;
	my $ck = cookie(-name=>'HistoryShow',
		-value=>$HistoryShow,
		-path=>'/', -expires=>'+1h');
	print "Set-Cookie: " . $ck . "\n";
}

#
# Prepare the session and create the session directory.
# If session exists, perfom arguments checking and execute historic views.
#
$session = cookie('SessionID');
unless($session) {
	$session = '';
	open(R, '/dev/urandom')
		or open(R, '/dev/random')
			or bark($RandFailed);
	read(R, $session, 16) == 16 or bark("Not enough randomness");
	if($ENV{HTTP_USER_AGENT}) {
		$session .= $ENV{HTTP_USER_AGENT};	# Add randomness
	}
	my $pid = open(R, "-|");
	if($pid == 0) {	# Child
		open(W, "| $HashProgramPath") or die;
		print W $session;
		exit(0);
	}
	$session = <R>;
	$session =~ s/[^a-f0-9]//ig;
	bark("md5 program is rotten here") if(length($session) != 32);
	$sessionDir = makeSessionDirName($TMPDIR, $session);
	mkdir($sessionDir, $DM) or bark($SandBoxInitFailed);
	my $ck = cookie(-name=>'SessionID', -value=>$session,
			-path=>'/', -expires=>'+1y');
	print "Set-Cookie: " . $ck . "\n";
} else {
	$session =~ s/[^a-f0-9]//ig;
	bark("Nope, try again") if(length($session) != 32);	# cool hacker?

	# Make sure the session directory exists
	$sessionDir = makeSessionDirName($TMPDIR, $session);
	mkdir($sessionDir, $DM) or bark($SandBoxInitFailed)
		unless(-d $sessionDir);

	my $t = param('time');
	my $file = param('file');
	my $fetch = param('fetch');
	my $show = param('show');
	my $remove = param('remove');

	unless(defined($t) && defined($file)
		&& $t =~ /^${safeTimeRE}$/
		&& $file =~ /^${safeFilenameRE}$/
		&& ($fetch eq '' or $fetch =~ /^${safeFilenameRE}$/)
	) {
		$file = '';
		$fetch = '';
		$show = '';
		$remove = '';
	}
	if($fetch ne '' or $show =~ /^(log|unber|tgz)$/ or $remove ne '') {
		my $sandbox = $sessionDir . '/' . $t . '--' . $file;
		my $targetFile = '';

		if($show eq 'tgz') {
			my $tarball = makeArchive($TMPDIR, $sandbox);
			defined $tarball
				or bark("Cannot create archive [$sandbox]");

			printf("Content-Type: application/x-tar\n");
			printf("Content-Encoding: gzip\n\n");
			exec("cat $tarball");
			exit(0);
		} elsif($show eq 'unber') {
			$targetFile = $sandbox . '/+UNBER';
		} elsif($show eq 'log') {
			$targetFile = $sandbox . '/+Compiler.Log';
		} elsif($remove ne '') {
			print "Status: 303 See Other\n";
			print "Location: $myName\n";
			print "\n";
			rename($sandbox,
				$sessionDir . '/' . $t . '-R--' . $file);
			exit(0);
		} else {
			$targetFile = $sandbox . '/' . $fetch;
		}
		if($targetFile ne '') {
			open(I, '< ' . $targetFile)
				or bark("Invalid or outdated request $!");
			printf "Content-Type: text/plain\n\n";
			print while <I>;
			exit(0);
		}
	}
}

#
# Check if transaction help is requested.
#
$transHelp = param('transHelp');
if(defined($transHelp)
&& $transHelp =~ /^([0-9]+)--($safeTimeRE)--($safeFilenameRE)$/) {
	open(S, "| sendmail -it")
		or bark("Cannot perform help request, "
			. "please email to the address below");
	print S "From: $userEmail\n";
	print S "To: $HelpEmail\n";
	print S "Subject: asn1c help requested for $3 ($1) by $userEmail\n";
	print S "\n";
	print S "\n-- \n";
	print S "User $userEmail requested help with\n";
	print S "$session/$2--$3 ($1)\n";
	close(S);

	open(S, '>> ' . $sessionDir . '/' . $2 . '--' . $3 . '/+HelpReq')
		or bark("Cannot perform help request, "
			. "please email to the address below");
	print S "$userEmail\n";
	close(S);

	open(S, '>> ' . $HelpDBFile);	# Susceptible to race condition.
	print S "$session/$2--$1--$3\n";
	close(S);

	$content = '<CENTER>Transaction '
		. "$1 ($3) is marked for manual processing.<BR>"
		. "Results will be mailed to "
		. "<FONT COLOR=darkgreen>$userEmail</FONT> shortly."
		. "</CONTENT>";
	IssueRedirect();
	goto PRINTOUT;
}

open(LOG, ">> $sessionDir/+logfile") or bark("Sandbox error: $!");
print LOG isoTime() . "\tIP=$ENV{REMOTE_ADDR}";
print LOG "\tEMAIL=$userEmail" if($userEmail ne $defaultUserEmail);

@gotSafeNames = ();
@gotNames = param('file');
if($#gotNames != -1 && $gotNames[0] ne "") {
	$gotFile = param('file');
	@gotFiles = upload('file');
} else {
	@gotNames = ();
	@gotFiles = ();
	$gotFile = undef;
}

my $asnText = param('text');

if($#gotNames == -1) {
	push(@gotNames, 'module.asn1') if $asnText;
}

# Make safe filenames
foreach my $fname (@gotNames) {
	local $_ = $fname;
	s/.*\///g;	# Strip directory components
	s/.*\\//g;	# Strip directory components (DOS version)
	s/^[.-]/_/g;	# Don't allow filenames starting with a dot or a dash
	s/[^._a-zA-Z0-9-]/_/g;
	if(!length($_)) {
		print LOG "\n";
		bark("Too strange filename: \"$fname\"");
	}
	$_ .= '.asn1' unless(/asn[1]{0,1}$/i);
	@gotSafeNames = (@gotSafeNames, $_);
	print LOG "\t" . $_;
}

#
# Save the files and start compilation process.
#
if($#gotSafeNames >= 0) {
	$transactionDir = isoTime() . '--' . join("-", @gotSafeNames);
	print LOG "\tDST=$transactionDir";

	my $sandbox = $sessionDir . '/' . $transactionDir;
	mkdir($sandbox, $DM) or bark($SandBoxInitFailed);

	open(O, '> ' . $sandbox . '/+Names');
	print O join("\n", @gotNames);
	open(O, '> ' . $sandbox . '/+safeNames');
	print O join("\n", @gotSafeNames);
	for(my $i = 0; $i <= $#gotSafeNames; $i++) {
		my $name = $gotSafeNames[$i];
		open(O, '> ' . $sandbox . '/'. $name);
		if($#gotFiles == -1) {
			print O $asnText;	# param(text)
			unlink $sessionDir . '/lastText';
			symlink $transactionDir . '/' . $name,
				$sessionDir . '/lastText';
		} else {
			# Save the uploaded data into specified file
			print O while <$gotFile>;
		}
	}
	close(O);

	my $inChDir = makeSessionDirName("/", $session) . $transactionDir;
	my $options = '';
	my $optDebugL = param('optDebugL');
	my $optE = param('optE');
	my $optEF = param('optEF');
	my $optNT = param('optNT');
	my $optCN = param('optCN');
	$options .= " -Wdebug-lexer"
		if(defined($optDebugL) && $optDebugL eq "on");
	$options .= " -E" if(defined($optE) && $optE eq "on");
	$options .= " -EF" if(defined($optEF) && $optEF eq "on");
	$options .= " -fnative-types" if(defined($optNT) && $optNT eq "on");
	$options .= " -fcompound-names" if(defined($optCN) && $optNT eq "on");
	my $CompileASN = "$TMPDIR/bin/asn1c -v | sed -e 's/^/-- /'"
			. " > $sandbox/+Compiler.Log 2>&1"
		. "; $SUIDHelper $TMPDIR $inChDir asn1c $options @gotSafeNames "
			. " >> $sandbox/+Compiler.Log 2>&1"
		. "; ec=\$?; echo \$ec > $sandbox/+ExitCode"
		. "; exit \$ec";

	my $ec = (256 * $DataERR);	# Simulate EX_DATAERR
	my $fType = param('fileType');

	# Compile as ASN.1 text
	if($fType ne 'ber') {
		$ec = system($CompileASN);
		bark("Failed to initiate compilation process: $!")
			if(!-r $sandbox . '/+ExitCode');
	}

	if($ec == (256 * $DataERR) and $fType ne 'asn') {
		# Unrecognized ASN.1 module format.
		# Try out BER decoding.
		my $uec = system("$SUIDHelper $TMPDIR $inChDir unber @gotSafeNames > $TMPDIR/$inChDir/+UNBER.tmp 2>&1");
		if(($uec == 0 or $fType eq 'ber')
		and open(U, "> $TMPDIR/$inChDir/+UNBER")) {
			my $fnames = escapeHTML(join(", ", @gotNames));
			open(T, "< $TMPDIR/$inChDir/+UNBER.tmp");
			print U "<!-- BER structure of $fnames; decoded by 'unber' (c) Lev Walkin <vlm\@lionet.info> -->\n";
			print U while <T>;
			close(U);
			close(T);
		}
		unlink("$TMPDIR/$inChDir/+UNBER.tmp");
	} else {
		makeArchive($TMPDIR, $sandbox);
	}
	if($ENV{REQUEST_METHOD} ne 'GET') {
		print "Status: 303 See Other\n";
		print "Location: $myName\n";
	}
}

my $rtt = '';
if(-f $sessionDir . '/lastText') {
	if(param('resetText')) {
		unlink $sessionDir . '/lastText';
	} else {
		$rtt = "<BR>&nbsp;&nbsp;[<A HREF=$myName?resetText=ok>refill with sample ASN.1 module text</A>]";
	}
}

$form =
  "<FORM METHOD=POST ACTION=$myName ENCTYPE=\"multipart/form-data\">"
. "<TABLE BORDER=0><TR><TD>&nbsp;</TD><TD COLSPAN=2>"
. "Pick the ASN.1 module or binary encoded data file:\n"
. "</TD></TR><TD VALIGN=top><FONT COLOR=green>&rArr;</FONT></TD><TD>"
. "<SELECT NAME=fileType>"
. "<OPTION VALUE=auto>Autodetect type of file ..."
. "<OPTION VALUE=asn>ASN.1 text file ..."
. "<OPTION VALUE=ber>BER/DER/CER data ..."
. "</SELECT>"
. "</TD><TD ALIGN=right>"
. "<INPUT TYPE=file NAME=file SIZE=13>"
. "</TD></TR><TR><TD>&nbsp;</TD><TD COLSPAN=2>"
. "Or paste the ASN.1 text into the following area:$rtt\n"
. "</TD></TR><TD VALIGN=top><FONT COLOR=green>&rArr;</FONT></TD><TD COLSPAN=2>"
. "<TEXTAREA NAME=text ROWS=16 COLS=60>\n"
;
if(open(T, '< ' . $sessionDir . '/lastText')) {
	$form .= escapeHTML($_) while <T>;
	close(T);
} else {
	$form .= ""
	. "/*\n"
	. " * This ASN.1 specification is given for illustrative purposes.\n"
	. " * Your own ASN.1 module must be properly formed too!\n"
	. " * (Make sure it has BEGIN/END statements, etc.)\n"
	. " */\n"
	. "TestModule DEFINITIONS ::= \n"
	. "BEGIN\n"
	. "\n"
	. "  TestType ::= SEQUENCE {\n"
	. "      num [PRIVATE 1] INTEGER,\n"
	. "      str UTF8String (SIZE(1..20)) OPTIONAL\n"
	. "  }\n"
	. "\n"
	. "END\n"
	;
}

$form .= "</TEXTAREA>\n"
. "</TD></TR><TD COLSPAN=3 ID=extrasmall"
. " STYLE=\"border-left: dashed 1px rgb(200, 200, 200);\">\n"
. "These options may be used to control the compiler's behavior:<BR>\n"
. "<INPUT TYPE=checkbox NAME=optDebugL> Debug lexer (<I>-Wdebug-lexer</I>)<BR>\n"
. "<INPUT TYPE=checkbox NAME=optE> Just parse and dump (do not verify) (<I>-E</I>)<BR>\n"
. "<INPUT TYPE=checkbox NAME=optEF> Parse, verify validity, and dump (<I>-E -F</I>)<BR>\n"
. "<INPUT TYPE=checkbox NAME=optNT CHECKED=on> Use native machine types (e.g. <b>double</b> instead of <b>REAL_t</b>) (<I>-fnative-types</I>)<BR>\n"
. "<INPUT TYPE=checkbox NAME=optCN> Prevent name clashes in compiled output (<I>-fcompound-names</I>)<BR>\n"
. "<I>... the command line ASN.1 compiler, <A HREF=$ASN1C_Page>asn1c</A>, supports many other parameters</I>."
. "</FONT>"
. "</TD></TR><TD VALIGN=top><FONT COLOR=green>&rArr;</FONT></TD><TD COLSPAN=2>"
. "<INPUT TYPE=submit VALUE=\"Proceed with ASN.1 compilation\">"
. " (<A HREF=$ASN1C_Page>What is ASN.1?</A>)"
. "</FORM></TD></TR></TABLE>";

#
# Gather previous transactions to generate the history page.
# The history page contains a list of several last ASN.1 files
# which were uploaded for compilation into the system
# by this particular browser (cookie-tracked).
#
opendir(SD, $sessionDir) or bark("Cannot open sandbox: $!");
my @transactions = sort { $b cmp $a }
		(grep {/^${safeTimeRE}(-R)?--${safeFilenameRE}?$/}
			readdir(SD));
my $CountHistoryItems = 0;
my $CountGlobalItems = 0;
my $CountShownItems = 0;
my $fullresp = param("fullresp");
foreach my $trans (sort { $b cmp $a } @transactions) {
	$CountGlobalItems++;
	next unless($trans =~ /^($safeTimeRE)--($safeFilenameRE)$/);
	$CountHistoryItems++;
	next if($CountHistoryItems > $MaxHistoryItems
		&& $HistoryShow ne 'full');
	$CountShownItems++;

	my ($t, $f) = ($1, $2);
	my $origTime = $t;
	$t =~ s/T/ /;	# "1999-01-02T13:53:12" => "1999-01-02 13:53:12"

	# Global transaction number
	my $tNum = 2 + $#transactions - $CountGlobalItems;

	# Open the list of file names under which these files are known
	# at the remote system.
	open(I, '< ' . $sessionDir . '/' . $trans . '/+Names');
	my @Names = <I>;

	# Open the list of "safe" file names under which these files
	# are known to our file system.
	open(I, '< ' . $sessionDir . '/' . $trans . '/+safeNames');
	my @safeNames = <I>;

	# Create a list of real file names whith appropriate links to the
	# "safe" file names for subsequent file fetching.
	my @markedNames = ();
	for(my $i = 0; $i <= $#Names; $i++) {
		local $_ = "<A HREF=\"$myName?time="
			. escapeHTML($origTime)
			. "&file=$f"
			. "&fetch=$safeNames[$i]\" ID=modrefs>"
			. escapeHTML($Names[$i])
			. "</A>";
		@markedNames = (@markedNames, $_);
	}

	my $ec = '';
	open(I, '< ' . $sessionDir . '/' . $trans . '/+ExitCode')
		and chop($ec = <I>);

	my $resCode = "log";
	my $resText = "Show compiler log";

	if($ec eq "0") {
		$results = "<FONT COLOR=darkgreen><B>"
			. "Compiled OK</B></FONT><BR>\n";
	} elsif(-f $sessionDir . '/' . $trans . '/+UNBER') {
		my $msg = 'This looks like a BER-encoded data';
		$msg = "Treating input as BER-encoded data" if $ec eq '';
		$results = "<FONT COLOR=darkgreen><B>$msg</B></FONT><BR>\n";
		$resText = "Show BER structure";
		$resCode = "unber";
		$ec = 0;
	} else {
		my $why = $ec;
		$why = "<NOBR>Broken input file</NOBR>" if $ec == $DataERR;
		$results = "<FONT COLOR=darkred SIZE=-1>"
			. "<NOBR>ASN.1 compiler error:</NOBR> "
			. "$why</FONT><BR>\n";
	}

	$allowFetchResults = $ec eq "0"
		&& (-f $sessionDir . '/' . $trans . '/+Archive.tgz'
		|| -f $sessionDir . '/' . $trans . '/Makefile.am.sample');

	$results .= "<NOBR>"
		. ($allowFetchResults ? '1. ' : '')
		. "<A HREF=\"$myName/$f-$tNum.$resCode?time="
		. escapeHTML($origTime)
		. "&file=$f"
		. "&show=$resCode\">"
		. "$resText</A>"
		. ($ec ? ' &larr;' : '')
		. "</NOBR>";
	$results .= "<BR>\n<NOBR>"
		. "2. <A HREF=\"$myName/$f-$tNum.tgz?time="
		. escapeHTML($origTime)
		. "&file=$f"
		. "&show=tgz\">"
		. "Fetch compiled C sources (.tgz)</A> &larr;</NOBR>"
		if $allowFetchResults;
	if($ec ne "0") {
		my ($eml, @resp);
		open(H, '< ' . $sessionDir . '/' . $trans . '/+HelpResp')
			and @resp = <H>;
		open(H, '< ' . $sessionDir . '/' . $trans . '/+HelpReq')
			and chomp($eml = <H>);
		if($#resp >= 0) {
			shift(@resp) while($resp[0] =~ /^$/);
			if($fullresp eq $tNum) {
				my $r = join("<BR>", @resp);
				$r =~ s/ /&nbsp;/g;
				$results .= "<P><B>Analysis:</B>";
				$results .= "<BR>(<A HREF=\"$myName\">Hide full explanation</A>)";
				$results .= "<BLOCKQUOTE>";
				$results .= $r;
				$results .= "</BLOCKQUOTE>";
				$results .= "(<A HREF=\"$myName\">Hide full explanation</A>)";
			} else {
				$results .= "<P><B>Analysis:</B> $resp[0]<BR>";
				$results .= "(<A HREF=\"$myName?fullresp=$tNum\">Show full explanation</A>)";
			}
		} elsif($eml) {
			$results .= "<P><FONT COLOR=darkred Family=Serif><B>"
				. "Status: manual help requested<BR>"
				. " by <FONT COLOR=black>$eml</FONT>,<BR>"
				. "expect results in a few hours.<B></FONT>";
		} else {
			$results .= '<P>'
			. "To get free help, leave a return address:<BR>"
			. "<INPUT TYPE=text NAME=email VALUE=\"$userEmail\"><BR>"
			. "<INPUT TYPE=hidden NAME=transHelp VALUE=\"$tNum--$trans\">"
			. '<INPUT TYPE=Submit VALUE="Help me fix it!">'
			;
			$atLeastOneError = 1;
		}
	}

	$trColor = ' BGCOLOR=#f8f8f8';
	$trColor = ' BGCOLOR=#d0ffe0' if $CountHistoryItems == 1;

	$history .= "<TR $trColor>"
		. "<TH ALIGN=center ID=num>$tNum"
		. "<BR><FONT FACE=Serif>[<A ID=modrefs "
			. "HREF=\"$myName?time="
			. escapeHTML($origTime)
			. "&file=$f&remove=$tNum\""
			. ">&times;</A>]</FONT>"
		. "</TH>"
		. "<TD ALIGN=center>"
		. join(", ", @markedNames)
		. "</TD></TD>"
		. "<FORM METHOD=POST ACTION=$myName><TD ID=extrasmall>"
			. $results
			. "</TD></FORM>"
		. "</TR>"
		;
}

if($DynamicHistory eq 'yes') {
	# [Un-]limit number of history items
	$HistoryItemsHidden = $CountHistoryItems - $CountShownItems;
	if($HistoryItemsHidden > 0) {
		# Propose to expand the list.
		my $item = 'item';
		$HistoryItemsHidden == 1 or $item = 'items';
		$history .= "<TR BGCOLOR=white><TD COLSPAN=3 ALIGN=center>"
			. "<A HREF=\"$myName?history=full\">"
			. "Show full history</A> "
			. "($HistoryItemsHidden hidden $item)"
			. "</TD></TR>\n";
	} elsif($HistoryShow eq "full" && $#transactions >= $MaxHistoryItems) {
		# Propose to shorten the list.
		my $item = 'item';
		$MaxHistoryItems == 1 or $item = 'items';
		$history .= "<TR BGCOLOR=white><TD COLSPAN=3 ALIGN=center>"
			. "<A HREF=\"$myName?history=short\">"
			. "Short history</A> ($MaxHistoryItems $item)"
			. "</TD></TR>\n";
	}
}

if($history) {
	$history = "<H3>History</H3>"
	. "<TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0 BGCOLOR=#404040 WIDTH=100%><TR><TD>"
	. "<TABLE BORDER=0 CELLPADDING=5 CELLSPACING=1 WIDTH=100%>\n"
	. "<TR BGCOLOR=#e0f0d0>"
	. "<TH WIDTH=1%>N</TH><TH>Files processed</TH><TH>Result</TH>\n"
	. "</TR>\n"
	. $history . "</TABLE></TD></TR></TABLE><BR>\n";

	if($atLeastOneError) {
		$history .= "<FONT COLOR=#404040>"
			. "<FONT COLOR=darkred><B>Bottom line:</B> ASN.1 compiler was unable to process some of the input.</FONT><BR>"
			. "This is typically caused by syntax errors in the input files.\n"
			. "Such errors are normally fixed by removing or adding a couple of characters in the ASN.1 module.<BR>\n"
			. "<BR><B><FONT COLOR=darkred>Please consider clicking on the appropriate &quot;<I>Help me fix it!</I>&quot; button above.</FONT></B><BR>\n"
			. "An email will be sent to a live person who will fix the ASN.1 module for you. (The typical turn-around time is less than 24 hours.)\n"
			. "<BR>This is <B>free</B>, and highly advisable.\n"
			. "<BR>Your request will help us make a better compiler!\n"
			. "<BR>Thank you."
			. "</FONT>";
	}
}

unless($history) {
	$history = "<FONT SIZE=+2 COLOR=#a0a0a0>"
		. "[compiled results will appear here]</FONT>";
	$histValign = 'center';
} else {
	$histValign = 'top';
}

$content .=
  "<TABLE WIDTH=100% BORDER=0 CELLSPACING=5 CELLPADDING=5><TR><TD ID=inputbox VALIGN=top ROWSPAN=2 WIDTH=40%>\n"
. "<H3 ALIGN=center>ASN.1 Input</H3>\n"
. "$form"
. "</TD><TD WIDTH=60% HEIGHT=50% ALIGN=center VALIGN=$histValign>$history \n"
. "</TD></TR><TR><TD HEIGHT=50% VALIGN=bottom>"
	. "<B>Privacy Note:</B> this page is tailored "
	. "to your browser using a cryprographically strong cookie. "
	. "<I>Other users will see their own (different) data.</I> "
	. "(<A HREF=asn1c-privacy.html>Read more...</A>)"
. "</TD></TR></TABLE>";

$ua = $ENV{HTTP_USER_AGENT};
$ua =~ s/\\/\\\\/;
$ua =~ s/"/\\"/;
print LOG "\tUA=\"$ua\"";
print LOG "\n";	# Finalize logging record

PRINTOUT:

print header(-expires=>'-1y');

# If environment has never been set up completely, remove it.
if($EnvironmentSetOK != 1 && $TMPDIR ne "/") {
	system("rm -rf $TMPDIR/ >/dev/null 2>&1");
}

print<<EOM;
<HTML>
<HEAD>
<TITLE>Free Online ASN.1 Compiler</TITLE>
<META NAME="Description" CONTENT="Free Online ASN.1 Compiler">
$redirect
<STYLE TYPE="text/css">
	TH {
		font-size: 11pt;
		color: #404040;
		font-family: monospace;
	}
	TH#num {
		font-size: 8pt;
		font-family: sans-serif;
	}
        TD {
                font-size: 10pt;
                font-family: sans-serif;
	}
	TD#inputbox {
		border-right: dashed 1px rgb(200, 200, 200);
	}
	TD#extrasmall {
                font-size: 8pt;
                font-family: sans-serif;
	}
	A#modrefs {
		color: #606060;
		text-decoration: none;
	}
	A:hover#modrefs {
		text-decoration: underline;
	}
	A:visited#modrefs {
		color: #b06060;
	}
</STYLE>
</HEAD>
<BODY BGCOLOR=white>

$homePath

$content

$redirect_bottom

<HR WIDTH=70%>
<CENTER><ADDRESS><FONT SIZE=-1 FACE=Courier COLOR=#404040>
<A HREF=$ASN1C_Page>The ASN.1 Compiler</A>
	Copyright &copy; 2003, 2004, 2005
Lev Walkin &lt;<A HREF=mailto:vlm&#64;lionet.info?Subject=asn1c>vlm&#64;lionet.info</A>&gt;
</FONT></ADDRESS></CENTER>
</BODY>
</HTML>
EOM