9f72b668227427b606d55ef6e4b5ebacf71f256c
[openssl.git] / util / perl / OpenSSL / Test.pm
1 # Copyright 2016-2019 The OpenSSL Project Authors. All Rights Reserved.
2 #
3 # Licensed under the Apache License 2.0 (the "License").  You may not use
4 # this file except in compliance with the License.  You can obtain a copy
5 # in the file LICENSE in the source distribution or at
6 # https://www.openssl.org/source/license.html
7
8 package OpenSSL::Test;
9
10 use strict;
11 use warnings;
12
13 use Test::More 0.96;
14
15 use Exporter;
16 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
17 $VERSION = "1.0";
18 @ISA = qw(Exporter);
19 @EXPORT = (@Test::More::EXPORT, qw(setup run indir cmd app fuzz test
20                                    perlapp perltest subtest));
21 @EXPORT_OK = (@Test::More::EXPORT_OK, qw(bldtop_dir bldtop_file
22                                          srctop_dir srctop_file
23                                          data_file data_dir
24                                          pipe with cmdstr quotify
25                                          openssl_versions
26                                          ok_nofips is_nofips isnt_nofips));
27
28 =head1 NAME
29
30 OpenSSL::Test - a private extension of Test::More
31
32 =head1 SYNOPSIS
33
34   use OpenSSL::Test;
35
36   setup("my_test_name");
37
38   ok(run(app(["openssl", "version"])), "check for openssl presence");
39
40   indir "subdir" => sub {
41     ok(run(test(["sometest", "arg1"], stdout => "foo.txt")),
42        "run sometest with output to foo.txt");
43   };
44
45 =head1 DESCRIPTION
46
47 This module is a private extension of L<Test::More> for testing OpenSSL.
48 In addition to the Test::More functions, it also provides functions that
49 easily find the diverse programs within a OpenSSL build tree, as well as
50 some other useful functions.
51
52 This module I<depends> on the environment variables C<$TOP> or C<$SRCTOP>
53 and C<$BLDTOP>.  Without one of the combinations it refuses to work.
54 See L</ENVIRONMENT> below.
55
56 With each test recipe, a parallel data directory with (almost) the same name
57 as the recipe is possible in the source directory tree.  For example, for a
58 recipe C<$SRCTOP/test/recipes/99-foo.t>, there could be a directory
59 C<$SRCTOP/test/recipes/99-foo_data/>.
60
61 =cut
62
63 use File::Copy;
64 use File::Spec::Functions qw/file_name_is_absolute curdir canonpath splitdir
65                              catdir catfile splitpath catpath devnull abs2rel
66                              rel2abs/;
67 use File::Path 2.00 qw/rmtree mkpath/;
68 use File::Basename;
69 use Cwd qw/abs_path/;
70
71 my $level = 0;
72
73 # The name of the test.  This is set by setup() and is used in the other
74 # functions to verify that setup() has been used.
75 my $test_name = undef;
76
77 # Directories we want to keep track of TOP, APPS, TEST and RESULTS are the
78 # ones we're interested in, corresponding to the environment variables TOP
79 # (mandatory), BIN_D, TEST_D, UTIL_D and RESULT_D.
80 my %directories = ();
81
82 # The environment variables that gave us the contents in %directories.  These
83 # get modified whenever we change directories, so that subprocesses can use
84 # the values of those environment variables as well
85 my @direnv = ();
86
87 # A bool saying if we shall stop all testing if the current recipe has failing
88 # tests or not.  This is set by setup() if the environment variable STOPTEST
89 # is defined with a non-empty value.
90 my $end_with_bailout = 0;
91
92 # A set of hooks that is affected by with() and may be used in diverse places.
93 # All hooks are expected to be CODE references.
94 my %hooks = (
95
96     # exit_checker is used by run() directly after completion of a command.
97     # it receives the exit code from that command and is expected to return
98     # 1 (for success) or 0 (for failure).  This is the status value that run()
99     # will give back (through the |statusvar| reference and as returned value
100     # when capture => 1 doesn't apply).
101     exit_checker => sub { return shift == 0 ? 1 : 0 },
102
103     );
104
105 # Debug flag, to be set manually when needed
106 my $debug = 0;
107
108 =head2 Main functions
109
110 The following functions are exported by default when using C<OpenSSL::Test>.
111
112 =cut
113
114 =over 4
115
116 =item B<setup "NAME">
117
118 C<setup> is used for initial setup, and it is mandatory that it's used.
119 If it's not used in a OpenSSL test recipe, the rest of the recipe will
120 most likely refuse to run.
121
122 C<setup> checks for environment variables (see L</ENVIRONMENT> below),
123 checks that C<$TOP/Configure> or C<$SRCTOP/Configure> exists, C<chdir>
124 into the results directory (defined by the C<$RESULT_D> environment
125 variable if defined, otherwise C<$BLDTOP/test> or C<$TOP/test>, whichever
126 is defined).
127
128 =back
129
130 =cut
131
132 sub setup {
133     my $old_test_name = $test_name;
134     $test_name = shift;
135
136     BAIL_OUT("setup() must receive a name") unless $test_name;
137     warn "setup() detected test name change.  Innocuous, so we continue...\n"
138         if $old_test_name && $old_test_name ne $test_name;
139
140     return if $old_test_name;
141
142     BAIL_OUT("setup() needs \$TOP or \$SRCTOP and \$BLDTOP to be defined")
143         unless $ENV{TOP} || ($ENV{SRCTOP} && $ENV{BLDTOP});
144     BAIL_OUT("setup() found both \$TOP and \$SRCTOP or \$BLDTOP...")
145         if $ENV{TOP} && ($ENV{SRCTOP} || $ENV{BLDTOP});
146
147     __env();
148
149     BAIL_OUT("setup() expects the file Configure in the source top directory")
150         unless -f srctop_file("Configure");
151
152     __cwd($directories{RESULTS});
153 }
154
155 =over 4
156
157 =item B<indir "SUBDIR" =E<gt> sub BLOCK, OPTS>
158
159 C<indir> is used to run a part of the recipe in a different directory than
160 the one C<setup> moved into, usually a subdirectory, given by SUBDIR.
161 The part of the recipe that's run there is given by the codeblock BLOCK.
162
163 C<indir> takes some additional options OPTS that affect the subdirectory:
164
165 =over 4
166
167 =item B<create =E<gt> 0|1>
168
169 When set to 1 (or any value that perl perceives as true), the subdirectory
170 will be created if it doesn't already exist.  This happens before BLOCK
171 is executed.
172
173 =item B<cleanup =E<gt> 0|1>
174
175 When set to 1 (or any value that perl perceives as true), the subdirectory
176 will be cleaned out and removed.  This happens both before and after BLOCK
177 is executed.
178
179 =back
180
181 An example:
182
183   indir "foo" => sub {
184       ok(run(app(["openssl", "version"]), stdout => "foo.txt"));
185       if (ok(open(RESULT, "foo.txt"), "reading foo.txt")) {
186           my $line = <RESULT>;
187           close RESULT;
188           is($line, qr/^OpenSSL 1\./,
189              "check that we're using OpenSSL 1.x.x");
190       }
191   }, create => 1, cleanup => 1;
192
193 =back
194
195 =cut
196
197 sub indir {
198     my $subdir = shift;
199     my $codeblock = shift;
200     my %opts = @_;
201
202     my $reverse = __cwd($subdir,%opts);
203     BAIL_OUT("FAILURE: indir, \"$subdir\" wasn't possible to move into")
204         unless $reverse;
205
206     $codeblock->();
207
208     __cwd($reverse);
209
210     if ($opts{cleanup}) {
211         rmtree($subdir, { safe => 0 });
212     }
213 }
214
215 =over 4
216
217 =item B<cmd ARRAYREF, OPTS>
218
219 This functions build up a platform dependent command based on the
220 input.  It takes a reference to a list that is the executable or
221 script and its arguments, and some additional options (described
222 further on).  Where necessary, the command will be wrapped in a
223 suitable environment to make sure the correct shared libraries are
224 used (currently only on Unix).
225
226 It returns a CODEREF to be used by C<run>, C<pipe> or C<cmdstr>.
227
228 The options that C<cmd> can take are in the form of hash values:
229
230 =over 4
231
232 =item B<stdin =E<gt> PATH>
233
234 =item B<stdout =E<gt> PATH>
235
236 =item B<stderr =E<gt> PATH>
237
238 In all three cases, the corresponding standard input, output or error is
239 redirected from (for stdin) or to (for the others) a file given by the
240 string PATH, I<or>, if the value is C<undef>, C</dev/null> or similar.
241
242 =back
243
244 =item B<app ARRAYREF, OPTS>
245
246 =item B<test ARRAYREF, OPTS>
247
248 Both of these are specific applications of C<cmd>, with just a couple
249 of small difference:
250
251 C<app> expects to find the given command (the first item in the given list
252 reference) as an executable in C<$BIN_D> (if defined, otherwise C<$TOP/apps>
253 or C<$BLDTOP/apps>).
254
255 C<test> expects to find the given command (the first item in the given list
256 reference) as an executable in C<$TEST_D> (if defined, otherwise C<$TOP/test>
257 or C<$BLDTOP/test>).
258
259 Also, for both C<app> and C<test>, the command may be prefixed with
260 the content of the environment variable C<$EXE_SHELL>, which is useful
261 in case OpenSSL has been cross compiled.
262
263 =item B<perlapp ARRAYREF, OPTS>
264
265 =item B<perltest ARRAYREF, OPTS>
266
267 These are also specific applications of C<cmd>, where the interpreter
268 is predefined to be C<perl>, and they expect the script to be
269 interpreted to reside in the same location as C<app> and C<test>.
270
271 C<perlapp> and C<perltest> will also take the following option:
272
273 =over 4
274
275 =item B<interpreter_args =E<gt> ARRAYref>
276
277 The array reference is a set of arguments for the interpreter rather
278 than the script.  Take care so that none of them can be seen as a
279 script!  Flags and their eventual arguments only!
280
281 =back
282
283 An example:
284
285   ok(run(perlapp(["foo.pl", "arg1"],
286                  interpreter_args => [ "-I", srctop_dir("test") ])));
287
288 =back
289
290 =begin comment
291
292 One might wonder over the complexity of C<apps>, C<fuzz>, C<test>, ...
293 with all the lazy evaluations and all that.  The reason for this is that
294 we want to make sure the directory in which those programs are found are
295 correct at the time these commands are used.  Consider the following code
296 snippet:
297
298   my $cmd = app(["openssl", ...]);
299
300   indir "foo", sub {
301       ok(run($cmd), "Testing foo")
302   };
303
304 If there wasn't this lazy evaluation, the directory where C<openssl> is
305 found would be incorrect at the time C<run> is called, because it was
306 calculated before we moved into the directory "foo".
307
308 =end comment
309
310 =cut
311
312 sub cmd {
313     my $cmd = shift;
314     my %opts = @_;
315     return sub {
316         my $num = shift;
317         # Make a copy to not destroy the caller's array
318         my @cmdargs = ( @$cmd );
319         my @prog = __wrap_cmd(shift @cmdargs, $opts{exe_shell} // ());
320
321         return __decorate_cmd($num, [ @prog, quotify(@cmdargs) ],
322                               %opts);
323     }
324 }
325
326 sub app {
327     my $cmd = shift;
328     my %opts = @_;
329     return sub {
330         my @cmdargs = ( @{$cmd} );
331         my @prog = __fixup_prg(__apps_file(shift @cmdargs, __exeext()));
332         return cmd([ @prog, @cmdargs ],
333                    exe_shell => $ENV{EXE_SHELL}, %opts) -> (shift);
334     }
335 }
336
337 sub fuzz {
338     my $cmd = shift;
339     my %opts = @_;
340     return sub {
341         my @cmdargs = ( @{$cmd} );
342         my @prog = __fixup_prg(__fuzz_file(shift @cmdargs, __exeext()));
343         return cmd([ @prog, @cmdargs ],
344                    exe_shell => $ENV{EXE_SHELL}, %opts) -> (shift);
345     }
346 }
347
348 sub test {
349     my $cmd = shift;
350     my %opts = @_;
351     return sub {
352         my @cmdargs = ( @{$cmd} );
353         my @prog = __fixup_prg(__test_file(shift @cmdargs, __exeext()));
354         return cmd([ @prog, @cmdargs ],
355                    exe_shell => $ENV{EXE_SHELL}, %opts) -> (shift);
356     }
357 }
358
359 sub perlapp {
360     my $cmd = shift;
361     my %opts = @_;
362     return sub {
363         my @interpreter_args = defined $opts{interpreter_args} ?
364             @{$opts{interpreter_args}} : ();
365         my @interpreter = __fixup_prg($^X);
366         my @cmdargs = ( @{$cmd} );
367         my @prog = __apps_file(shift @cmdargs, undef);
368         return cmd([ @interpreter, @interpreter_args,
369                      @prog, @cmdargs ], %opts) -> (shift);
370     }
371 }
372
373 sub perltest {
374     my $cmd = shift;
375     my %opts = @_;
376     return sub {
377         my @interpreter_args = defined $opts{interpreter_args} ?
378             @{$opts{interpreter_args}} : ();
379         my @interpreter = __fixup_prg($^X);
380         my @cmdargs = ( @{$cmd} );
381         my @prog = __test_file(shift @cmdargs, undef);
382         return cmd([ @interpreter, @interpreter_args,
383                      @prog, @cmdargs ], %opts) -> (shift);
384     }
385 }
386
387 =over 4
388
389 =item B<run CODEREF, OPTS>
390
391 CODEREF is expected to be the value return by C<cmd> or any of its
392 derivatives, anything else will most likely cause an error unless you
393 know what you're doing.
394
395 C<run> executes the command returned by CODEREF and return either the
396 resulting output (if the option C<capture> is set true) or a boolean
397 indicating if the command succeeded or not.
398
399 The options that C<run> can take are in the form of hash values:
400
401 =over 4
402
403 =item B<capture =E<gt> 0|1>
404
405 If true, the command will be executed with a perl backtick, and C<run> will
406 return the resulting output as an array of lines.  If false or not given,
407 the command will be executed with C<system()>, and C<run> will return 1 if
408 the command was successful or 0 if it wasn't.
409
410 =item B<prefix =E<gt> EXPR>
411
412 If specified, EXPR will be used as a string to prefix the output from the
413 command.  This is useful if the output contains lines starting with C<ok >
414 or C<not ok > that can disturb Test::Harness.
415
416 =item B<statusvar =E<gt> VARREF>
417
418 If used, B<VARREF> must be a reference to a scalar variable.  It will be
419 assigned a boolean indicating if the command succeeded or not.  This is
420 particularly useful together with B<capture>.
421
422 =back
423
424 For further discussion on what is considered a successful command or not, see
425 the function C<with> further down.
426
427 =back
428
429 =cut
430
431 sub run {
432     my ($cmd, $display_cmd) = shift->(0);
433     my %opts = @_;
434
435     return () if !$cmd;
436
437     my $prefix = "";
438     if ( $^O eq "VMS" ) {       # VMS
439         $prefix = "pipe ";
440     }
441
442     my @r = ();
443     my $r = 0;
444     my $e = 0;
445
446     die "OpenSSL::Test::run(): statusvar value not a scalar reference"
447         if $opts{statusvar} && ref($opts{statusvar}) ne "SCALAR";
448
449     # For some reason, program output, or even output from this function
450     # somehow isn't caught by TAP::Harness (TAP::Parser?) on VMS, so we're
451     # silencing it specifically there until further notice.
452     my $save_STDOUT;
453     my $save_STDERR;
454     if ($^O eq 'VMS') {
455         # In non-verbose, we want to shut up the command interpreter, in case
456         # it has something to complain about.  On VMS, it might complain both
457         # on stdout and stderr
458         if ($ENV{HARNESS_ACTIVE} && !$ENV{HARNESS_VERBOSE}) {
459             open $save_STDOUT, '>&', \*STDOUT or die "Can't dup STDOUT: $!";
460             open $save_STDERR, '>&', \*STDERR or die "Can't dup STDERR: $!";
461             open STDOUT, ">", devnull();
462             open STDERR, ">", devnull();
463         }
464     }
465
466     $ENV{HARNESS_OSSL_LEVEL} = $level + 1;
467
468     # The dance we do with $? is the same dance the Unix shells appear to
469     # do.  For example, a program that gets aborted (and therefore signals
470     # SIGABRT = 6) will appear to exit with the code 134.  We mimic this
471     # to make it easier to compare with a manual run of the command.
472     if ($opts{capture} || defined($opts{prefix})) {
473         my $pipe;
474         local $_;
475
476         open($pipe, '-|', "$prefix$cmd") or die "Can't start command: $!";
477         while(<$pipe>) {
478             my $l = ($opts{prefix} // "") . $_;
479             if ($opts{capture}) {
480                 push @r, $l;
481             } else {
482                 print STDOUT $l;
483             }
484         }
485         close $pipe;
486     } else {
487         $ENV{HARNESS_OSSL_PREFIX} = "# ";
488         system("$prefix$cmd");
489         delete $ENV{HARNESS_OSSL_PREFIX};
490     }
491     $e = ($? & 0x7f) ? ($? & 0x7f)|0x80 : ($? >> 8);
492     $r = $hooks{exit_checker}->($e);
493     if ($opts{statusvar}) {
494         ${$opts{statusvar}} = $r;
495     }
496
497     # Restore STDOUT / STDERR on VMS
498     if ($^O eq 'VMS') {
499         if ($ENV{HARNESS_ACTIVE} && !$ENV{HARNESS_VERBOSE}) {
500             close STDOUT;
501             close STDERR;
502             open STDOUT, '>&', $save_STDOUT or die "Can't restore STDOUT: $!";
503             open STDERR, '>&', $save_STDERR or die "Can't restore STDERR: $!";
504         }
505
506         print STDERR "$prefix$display_cmd => $e\n"
507             if !$ENV{HARNESS_ACTIVE} || $ENV{HARNESS_VERBOSE};
508     } else {
509         print STDERR "$prefix$display_cmd => $e\n";
510     }
511
512     # At this point, $? stops being interesting, and unfortunately,
513     # there are Test::More versions that get picky if we leave it
514     # non-zero.
515     $? = 0;
516
517     if ($opts{capture}) {
518         return @r;
519     } else {
520         return $r;
521     }
522 }
523
524 END {
525     my $tb = Test::More->builder;
526     my $failure = scalar(grep { $_ == 0; } $tb->summary);
527     if ($failure && $end_with_bailout) {
528         BAIL_OUT("Stoptest!");
529     }
530 }
531
532 =head2 Utility functions
533
534 The following functions are exported on request when using C<OpenSSL::Test>.
535
536   # To only get the bldtop_file and srctop_file functions.
537   use OpenSSL::Test qw/bldtop_file srctop_file/;
538
539   # To only get the bldtop_file function in addition to the default ones.
540   use OpenSSL::Test qw/:DEFAULT bldtop_file/;
541
542 =cut
543
544 # Utility functions, exported on request
545
546 =over 4
547
548 =item B<bldtop_dir LIST>
549
550 LIST is a list of directories that make up a path from the top of the OpenSSL
551 build directory (as indicated by the environment variable C<$TOP> or
552 C<$BLDTOP>).
553 C<bldtop_dir> returns the resulting directory as a string, adapted to the local
554 operating system.
555
556 =back
557
558 =cut
559
560 sub bldtop_dir {
561     return __bldtop_dir(@_);    # This caters for operating systems that have
562                                 # a very distinct syntax for directories.
563 }
564
565 =over 4
566
567 =item B<bldtop_file LIST, FILENAME>
568
569 LIST is a list of directories that make up a path from the top of the OpenSSL
570 build directory (as indicated by the environment variable C<$TOP> or
571 C<$BLDTOP>) and FILENAME is the name of a file located in that directory path.
572 C<bldtop_file> returns the resulting file path as a string, adapted to the local
573 operating system.
574
575 =back
576
577 =cut
578
579 sub bldtop_file {
580     return __bldtop_file(@_);
581 }
582
583 =over 4
584
585 =item B<srctop_dir LIST>
586
587 LIST is a list of directories that make up a path from the top of the OpenSSL
588 source directory (as indicated by the environment variable C<$TOP> or
589 C<$SRCTOP>).
590 C<srctop_dir> returns the resulting directory as a string, adapted to the local
591 operating system.
592
593 =back
594
595 =cut
596
597 sub srctop_dir {
598     return __srctop_dir(@_);    # This caters for operating systems that have
599                                 # a very distinct syntax for directories.
600 }
601
602 =over 4
603
604 =item B<srctop_file LIST, FILENAME>
605
606 LIST is a list of directories that make up a path from the top of the OpenSSL
607 source directory (as indicated by the environment variable C<$TOP> or
608 C<$SRCTOP>) and FILENAME is the name of a file located in that directory path.
609 C<srctop_file> returns the resulting file path as a string, adapted to the local
610 operating system.
611
612 =back
613
614 =cut
615
616 sub srctop_file {
617     return __srctop_file(@_);
618 }
619
620 =over 4
621
622 =item B<data_dir LIST>
623
624 LIST is a list of directories that make up a path from the data directory
625 associated with the test (see L</DESCRIPTION> above).
626 C<data_dir> returns the resulting directory as a string, adapted to the local
627 operating system.
628
629 =back
630
631 =cut
632
633 sub data_dir {
634     return __data_dir(@_);
635 }
636
637 =over 4
638
639 =item B<data_file LIST, FILENAME>
640
641 LIST is a list of directories that make up a path from the data directory
642 associated with the test (see L</DESCRIPTION> above) and FILENAME is the name
643 of a file located in that directory path.  C<data_file> returns the resulting
644 file path as a string, adapted to the local operating system.
645
646 =back
647
648 =cut
649
650 sub data_file {
651     return __data_file(@_);
652 }
653
654 =over 4
655
656 =item B<pipe LIST>
657
658 LIST is a list of CODEREFs returned by C<app> or C<test>, from which C<pipe>
659 creates a new command composed of all the given commands put together in a
660 pipe.  C<pipe> returns a new CODEREF in the same manner as C<app> or C<test>,
661 to be passed to C<run> for execution.
662
663 =back
664
665 =cut
666
667 sub pipe {
668     my @cmds = @_;
669     return
670         sub {
671             my @cs  = ();
672             my @dcs = ();
673             my @els = ();
674             my $counter = 0;
675             foreach (@cmds) {
676                 my ($c, $dc, @el) = $_->(++$counter);
677
678                 return () if !$c;
679
680                 push @cs, $c;
681                 push @dcs, $dc;
682                 push @els, @el;
683             }
684             return (
685                 join(" | ", @cs),
686                 join(" | ", @dcs),
687                 @els
688                 );
689     };
690 }
691
692 =over 4
693
694 =item B<with HASHREF, CODEREF>
695
696 C<with> will temporarily install hooks given by the HASHREF and then execute
697 the given CODEREF.  Hooks are usually expected to have a coderef as value.
698
699 The currently available hoosk are:
700
701 =over 4
702
703 =item B<exit_checker =E<gt> CODEREF>
704
705 This hook is executed after C<run> has performed its given command.  The
706 CODEREF receives the exit code as only argument and is expected to return
707 1 (if the exit code indicated success) or 0 (if the exit code indicated
708 failure).
709
710 =back
711
712 =back
713
714 =cut
715
716 sub with {
717     my $opts = shift;
718     my %opts = %{$opts};
719     my $codeblock = shift;
720
721     my %saved_hooks = ();
722
723     foreach (keys %opts) {
724         $saved_hooks{$_} = $hooks{$_}   if exists($hooks{$_});
725         $hooks{$_} = $opts{$_};
726     }
727
728     $codeblock->();
729
730     foreach (keys %saved_hooks) {
731         $hooks{$_} = $saved_hooks{$_};
732     }
733 }
734
735 =over 4
736
737 =item B<cmdstr CODEREF, OPTS>
738
739 C<cmdstr> takes a CODEREF from C<app> or C<test> and simply returns the
740 command as a string.
741
742 C<cmdstr> takes some additional options OPTS that affect the string returned:
743
744 =over 4
745
746 =item B<display =E<gt> 0|1>
747
748 When set to 0, the returned string will be with all decorations, such as a
749 possible redirect of stderr to the null device.  This is suitable if the
750 string is to be used directly in a recipe.
751
752 When set to 1, the returned string will be without extra decorations.  This
753 is suitable for display if that is desired (doesn't confuse people with all
754 internal stuff), or if it's used to pass a command down to a subprocess.
755
756 Default: 0
757
758 =back
759
760 =back
761
762 =cut
763
764 sub cmdstr {
765     my ($cmd, $display_cmd) = shift->(0);
766     my %opts = @_;
767
768     if ($opts{display}) {
769         return $display_cmd;
770     } else {
771         return $cmd;
772     }
773 }
774
775 =over 4
776
777 =item B<quotify LIST>
778
779 LIST is a list of strings that are going to be used as arguments for a
780 command, and makes sure to inject quotes and escapes as necessary depending
781 on the content of each string.
782
783 This can also be used to put quotes around the executable of a command.
784 I<This must never ever be done on VMS.>
785
786 =back
787
788 =cut
789
790 sub quotify {
791     # Unix setup (default if nothing else is mentioned)
792     my $arg_formatter =
793         sub { $_ = shift;
794               ($_ eq '' || /\s|[\{\}\\\$\[\]\*\?\|\&:;<>]/) ? "'$_'" : $_ };
795
796     if ( $^O eq "VMS") {        # VMS setup
797         $arg_formatter = sub {
798             $_ = shift;
799             if ($_ eq '' || /\s|["[:upper:]]/) {
800                 s/"/""/g;
801                 '"'.$_.'"';
802             } else {
803                 $_;
804             }
805         };
806     } elsif ( $^O eq "MSWin32") { # MSWin setup
807         $arg_formatter = sub {
808             $_ = shift;
809             if ($_ eq '' || /\s|["\|\&\*\;<>]/) {
810                 s/(["\\])/\\$1/g;
811                 '"'.$_.'"';
812             } else {
813                 $_;
814             }
815         };
816     }
817
818     return map { $arg_formatter->($_) } @_;
819 }
820
821 =over 4
822
823 =item B<openssl_versions>
824
825 Returns a list of two version numbers, the first representing the build
826 version, the second representing the library version.  See opensslv.h for
827 more information on those numbers.
828
829 =back
830
831 =cut
832
833 my @versions = ();
834 sub openssl_versions {
835     unless (@versions) {
836         my %lines =
837             map { s/\R$//;
838                   /^(.*): (.*)$/;
839                   $1 => $2 }
840             run(test(['versions']), capture => 1);
841         @versions = ( $lines{'Build version'}, $lines{'Library version'} );
842     }
843     return @versions;
844 }
845
846 =over 4
847
848 =item B<ok_nofips EXPR, TEST_NAME>
849
850 C<ok_nofips> is equivalent to using C<ok> when the environment variable
851 C<FIPS_MODE> is undefined, otherwise it is equivalent to C<not ok>. This can be
852 used for C<ok> tests that must fail when testing a FIPS provider. The parameters
853 are the same as used by C<ok> which is an expression EXPR followed by the test
854 description TEST_NAME.
855
856 An example:
857
858   ok_nofips(run(app(["md5.pl"])), "md5 should fail in fips mode");
859
860 =item B<is_nofips EXPR1, EXPR2, TEST_NAME>
861
862 C<is_nofips> is equivalent to using C<is> when the environment variable
863 C<FIPS_MODE> is undefined, otherwise it is equivalent to C<isnt>. This can be
864 used for C<is> tests that must fail when testing a FIPS provider. The parameters
865 are the same as used by C<is> which has 2 arguments EXPR1 and EXPR2 that can be
866 compared using eq or ne, followed by a test description TEST_NAME.
867
868 An example:
869
870   is_nofips(ultimate_answer(), 42,  "Meaning of Life");
871
872 =item B<isnt_nofips EXPR1, EXPR2, TEST_NAME>
873
874 C<isnt_nofips> is equivalent to using C<isnt> when the environment variable
875 C<FIPS_MODE> is undefined, otherwise it is equivalent to C<is>. This can be
876 used for C<isnt> tests that must fail when testing a FIPS provider. The
877 parameters are the same as used by C<isnt> which has 2 arguments EXPR1 and EXPR2
878 that can be compared using ne or eq, followed by a test description TEST_NAME.
879
880 An example:
881
882   isnt_nofips($foo, '',  "Got some foo");
883
884 =back
885
886 =cut
887
888 sub ok_nofips {
889     return ok(!$_[0], @_[1..$#_]) if defined $ENV{FIPS_MODE};
890     return ok($_[0], @_[1..$#_]);
891 }
892
893 sub is_nofips {
894     return isnt($_[0], $_[1], @_[2..$#_]) if defined $ENV{FIPS_MODE};
895     return is($_[0], $_[1], @_[2..$#_]);
896 }
897
898 sub isnt_nofips {
899     return is($_[0], $_[1], @_[2..$#_]) if defined $ENV{FIPS_MODE};
900     return isnt($_[0], $_[1], @_[2..$#_]);
901 }
902
903 ######################################################################
904 # private functions.  These are never exported.
905
906 =head1 ENVIRONMENT
907
908 OpenSSL::Test depends on some environment variables.
909
910 =over 4
911
912 =item B<TOP>
913
914 This environment variable is mandatory.  C<setup> will check that it's
915 defined and that it's a directory that contains the file C<Configure>.
916 If this isn't so, C<setup> will C<BAIL_OUT>.
917
918 =item B<BIN_D>
919
920 If defined, its value should be the directory where the openssl application
921 is located.  Defaults to C<$TOP/apps> (adapted to the operating system).
922
923 =item B<TEST_D>
924
925 If defined, its value should be the directory where the test applications
926 are located.  Defaults to C<$TOP/test> (adapted to the operating system).
927
928 =item B<STOPTEST>
929
930 If defined, it puts testing in a different mode, where a recipe with
931 failures will result in a C<BAIL_OUT> at the end of its run.
932
933 =item B<FIPS_MODE>
934
935 If defined it indicates that the FIPS provider is being tested. Tests may use
936 B<ok_nofips>, B<is_nofips> and B<isnt_nofips> to invert test results
937 i.e. Some tests may only work in non FIPS mode.
938
939 =back
940
941 =cut
942
943 sub __env {
944     (my $recipe_datadir = basename($0)) =~ s/\.t$/_data/i;
945
946     $directories{SRCTOP}  = abs_path($ENV{SRCTOP} || $ENV{TOP});
947     $directories{BLDTOP}  = abs_path($ENV{BLDTOP} || $ENV{TOP});
948     $directories{BLDAPPS} = $ENV{BIN_D}  || __bldtop_dir("apps");
949     $directories{SRCAPPS} =                 __srctop_dir("apps");
950     $directories{BLDFUZZ} =                 __bldtop_dir("fuzz");
951     $directories{SRCFUZZ} =                 __srctop_dir("fuzz");
952     $directories{BLDTEST} = $ENV{TEST_D} || __bldtop_dir("test");
953     $directories{SRCTEST} =                 __srctop_dir("test");
954     $directories{SRCDATA} =                 __srctop_dir("test", "recipes",
955                                                          $recipe_datadir);
956     $directories{RESULTS} = $ENV{RESULT_D} || $directories{BLDTEST};
957
958     push @direnv, "TOP"       if $ENV{TOP};
959     push @direnv, "SRCTOP"    if $ENV{SRCTOP};
960     push @direnv, "BLDTOP"    if $ENV{BLDTOP};
961     push @direnv, "BIN_D"     if $ENV{BIN_D};
962     push @direnv, "TEST_D"    if $ENV{TEST_D};
963     push @direnv, "RESULT_D"  if $ENV{RESULT_D};
964
965     $end_with_bailout     = $ENV{STOPTEST} ? 1 : 0;
966 };
967
968 # __srctop_file and __srctop_dir are helpers to build file and directory
969 # names on top of the source directory.  They depend on $SRCTOP, and
970 # therefore on the proper use of setup() and when needed, indir().
971 # __bldtop_file and __bldtop_dir do the same thing but relative to $BLDTOP.
972 # __srctop_file and __bldtop_file take the same kind of argument as
973 # File::Spec::Functions::catfile.
974 # Similarly, __srctop_dir and __bldtop_dir take the same kind of argument
975 # as File::Spec::Functions::catdir
976 sub __srctop_file {
977     BAIL_OUT("Must run setup() first") if (! $test_name);
978
979     my $f = pop;
980     return catfile($directories{SRCTOP},@_,$f);
981 }
982
983 sub __srctop_dir {
984     BAIL_OUT("Must run setup() first") if (! $test_name);
985
986     return catdir($directories{SRCTOP},@_);
987 }
988
989 sub __bldtop_file {
990     BAIL_OUT("Must run setup() first") if (! $test_name);
991
992     my $f = pop;
993     return catfile($directories{BLDTOP},@_,$f);
994 }
995
996 sub __bldtop_dir {
997     BAIL_OUT("Must run setup() first") if (! $test_name);
998
999     return catdir($directories{BLDTOP},@_);
1000 }
1001
1002 # __exeext is a function that returns the platform dependent file extension
1003 # for executable binaries, or the value of the environment variable $EXE_EXT
1004 # if that one is defined.
1005 sub __exeext {
1006     my $ext = "";
1007     if ($^O eq "VMS" ) {        # VMS
1008         $ext = ".exe";
1009     } elsif ($^O eq "MSWin32") { # Windows
1010         $ext = ".exe";
1011     }
1012     return $ENV{"EXE_EXT"} || $ext;
1013 }
1014
1015 # __test_file, __apps_file and __fuzz_file return the full path to a file
1016 # relative to the test/, apps/ or fuzz/ directory in the build tree or the
1017 # source tree, depending on where the file is found.  Note that when looking
1018 # in the build tree, the file name with an added extension is looked for, if
1019 # an extension is given.  The intent is to look for executable binaries (in
1020 # the build tree) or possibly scripts (in the source tree).
1021 # These functions all take the same arguments as File::Spec::Functions::catfile,
1022 # *plus* a mandatory extension argument.  This extension argument can be undef,
1023 # and is ignored in such a case.
1024 sub __test_file {
1025     BAIL_OUT("Must run setup() first") if (! $test_name);
1026
1027     my $e = pop || "";
1028     my $f = pop;
1029     my $out = catfile($directories{BLDTEST},@_,$f . $e);
1030     $out = catfile($directories{SRCTEST},@_,$f) unless -f $out;
1031     return $out;
1032 }
1033
1034 sub __apps_file {
1035     BAIL_OUT("Must run setup() first") if (! $test_name);
1036
1037     my $e = pop || "";
1038     my $f = pop;
1039     my $out = catfile($directories{BLDAPPS},@_,$f . $e);
1040     $out = catfile($directories{SRCAPPS},@_,$f) unless -f $out;
1041     return $out;
1042 }
1043
1044 sub __fuzz_file {
1045     BAIL_OUT("Must run setup() first") if (! $test_name);
1046
1047     my $e = pop || "";
1048     my $f = pop;
1049     my $out = catfile($directories{BLDFUZZ},@_,$f . $e);
1050     $out = catfile($directories{SRCFUZZ},@_,$f) unless -f $out;
1051     return $out;
1052 }
1053
1054 sub __data_file {
1055     BAIL_OUT("Must run setup() first") if (! $test_name);
1056
1057     my $f = pop;
1058     return catfile($directories{SRCDATA},@_,$f);
1059 }
1060
1061 sub __data_dir {
1062     BAIL_OUT("Must run setup() first") if (! $test_name);
1063
1064     return catdir($directories{SRCDATA},@_);
1065 }
1066
1067 sub __results_file {
1068     BAIL_OUT("Must run setup() first") if (! $test_name);
1069
1070     my $f = pop;
1071     return catfile($directories{RESULTS},@_,$f);
1072 }
1073
1074 # __cwd DIR
1075 # __cwd DIR, OPTS
1076 #
1077 # __cwd changes directory to DIR (string) and changes all the relative
1078 # entries in %directories accordingly.  OPTS is an optional series of
1079 # hash style arguments to alter __cwd's behavior:
1080 #
1081 #    create = 0|1       The directory we move to is created if 1, not if 0.
1082 #    cleanup = 0|1      The directory we move from is removed if 1, not if 0.
1083
1084 sub __cwd {
1085     my $dir = catdir(shift);
1086     my %opts = @_;
1087     my $abscurdir = rel2abs(curdir());
1088     my $absdir = rel2abs($dir);
1089     my $reverse = abs2rel($abscurdir, $absdir);
1090
1091     # PARANOIA: if we're not moving anywhere, we do nothing more
1092     if ($abscurdir eq $absdir) {
1093         return $reverse;
1094     }
1095
1096     # Do not support a move to a different volume for now.  Maybe later.
1097     BAIL_OUT("FAILURE: \"$dir\" moves to a different volume, not supported")
1098         if $reverse eq $abscurdir;
1099
1100     # If someone happened to give a directory that leads back to the current,
1101     # it's extremely silly to do anything more, so just simulate that we did
1102     # move.
1103     # In this case, we won't even clean it out, for safety's sake.
1104     return "." if $reverse eq "";
1105
1106     $dir = canonpath($dir);
1107     if ($opts{create}) {
1108         mkpath($dir);
1109     }
1110
1111     # We are recalculating the directories we keep track of, but need to save
1112     # away the result for after having moved into the new directory.
1113     my %tmp_directories = ();
1114     my %tmp_ENV = ();
1115
1116     # For each of these directory variables, figure out where they are relative
1117     # to the directory we want to move to if they aren't absolute (if they are,
1118     # they don't change!)
1119     my @dirtags = sort keys %directories;
1120     foreach (@dirtags) {
1121         if (!file_name_is_absolute($directories{$_})) {
1122             my $newpath = abs2rel(rel2abs($directories{$_}), rel2abs($dir));
1123             $tmp_directories{$_} = $newpath;
1124         }
1125     }
1126
1127     # Treat each environment variable that was used to get us the values in
1128     # %directories the same was as the paths in %directories, so any sub
1129     # process can use their values properly as well
1130     foreach (@direnv) {
1131         if (!file_name_is_absolute($ENV{$_})) {
1132             my $newpath = abs2rel(rel2abs($ENV{$_}), rel2abs($dir));
1133             $tmp_ENV{$_} = $newpath;
1134         }
1135     }
1136
1137     # Should we just bail out here as well?  I'm unsure.
1138     return undef unless chdir($dir);
1139
1140     if ($opts{cleanup}) {
1141         rmtree(".", { safe => 0, keep_root => 1 });
1142     }
1143
1144     # We put back new values carefully.  Doing the obvious
1145     # %directories = ( %tmp_directories )
1146     # will clear out any value that happens to be an absolute path
1147     foreach (keys %tmp_directories) {
1148         $directories{$_} = $tmp_directories{$_};
1149     }
1150     foreach (keys %tmp_ENV) {
1151         $ENV{$_} = $tmp_ENV{$_};
1152     }
1153
1154     if ($debug) {
1155         print STDERR "DEBUG: __cwd(), directories and files:\n";
1156         print STDERR "  \$directories{BLDTEST} = \"$directories{BLDTEST}\"\n";
1157         print STDERR "  \$directories{SRCTEST} = \"$directories{SRCTEST}\"\n";
1158         print STDERR "  \$directories{SRCDATA} = \"$directories{SRCDATA}\"\n";
1159         print STDERR "  \$directories{RESULTS} = \"$directories{RESULTS}\"\n";
1160         print STDERR "  \$directories{BLDAPPS} = \"$directories{BLDAPPS}\"\n";
1161         print STDERR "  \$directories{SRCAPPS} = \"$directories{SRCAPPS}\"\n";
1162         print STDERR "  \$directories{SRCTOP}  = \"$directories{SRCTOP}\"\n";
1163         print STDERR "  \$directories{BLDTOP}  = \"$directories{BLDTOP}\"\n";
1164         print STDERR "\n";
1165         print STDERR "  current directory is \"",curdir(),"\"\n";
1166         print STDERR "  the way back is \"$reverse\"\n";
1167     }
1168
1169     return $reverse;
1170 }
1171
1172 # __wrap_cmd CMD
1173 # __wrap_cmd CMD, EXE_SHELL
1174 #
1175 # __wrap_cmd "wraps" CMD (string) with a beginning command that makes sure
1176 # the command gets executed with an appropriate environment.  If EXE_SHELL
1177 # is given, it is used as the beginning command.
1178 #
1179 # __wrap_cmd returns a list that should be used to build up a larger list
1180 # of command tokens, or be joined together like this:
1181 #
1182 #    join(" ", __wrap_cmd($cmd))
1183 sub __wrap_cmd {
1184     my $cmd = shift;
1185     my $exe_shell = shift;
1186
1187     my @prefix = ( __bldtop_file("util", "shlib_wrap.sh") );
1188
1189     if(defined($exe_shell)) {
1190         @prefix = ( $exe_shell );
1191     } elsif ($^O eq "VMS" || $^O eq "MSWin32") {
1192         # VMS and Windows don't use any wrapper script for the moment
1193         @prefix = ();
1194     }
1195
1196     return (@prefix, $cmd);
1197 }
1198
1199 # __fixup_prg PROG
1200 #
1201 # __fixup_prg does whatever fixup is needed to execute an executable binary
1202 # given by PROG (string).
1203 #
1204 # __fixup_prg returns a string with the possibly prefixed program path spec.
1205 sub __fixup_prg {
1206     my $prog = shift;
1207
1208     my $prefix = "";
1209
1210     if ($^O eq "VMS" ) {
1211         $prefix = ($prog =~ /^(?:[\$a-z0-9_]+:)?[<\[]/i ? "mcr " : "mcr []");
1212     }
1213
1214     if (defined($prog)) {
1215         # Make sure to quotify the program file on platforms that may
1216         # have spaces or similar in their path name.
1217         # To our knowledge, VMS is the exception where quotifying should
1218         # never happen.
1219         ($prog) = quotify($prog) unless $^O eq "VMS";
1220         return $prefix.$prog;
1221     }
1222
1223     print STDERR "$prog not found\n";
1224     return undef;
1225 }
1226
1227 # __decorate_cmd NUM, CMDARRAYREF
1228 #
1229 # __decorate_cmd takes a command number NUM and a command token array
1230 # CMDARRAYREF, builds up a command string from them and decorates it
1231 # with necessary redirections.
1232 # __decorate_cmd returns a list of two strings, one with the command
1233 # string to actually be used, the other to be displayed for the user.
1234 # The reason these strings might differ is that we redirect stderr to
1235 # the null device unless we're verbose and unless the user has
1236 # explicitly specified a stderr redirection.
1237 sub __decorate_cmd {
1238     BAIL_OUT("Must run setup() first") if (! $test_name);
1239
1240     my $num = shift;
1241     my $cmd = shift;
1242     my %opts = @_;
1243
1244     my $cmdstr = join(" ", @$cmd);
1245     my $null = devnull();
1246     my $fileornull = sub { $_[0] ? $_[0] : $null; };
1247     my $stdin = "";
1248     my $stdout = "";
1249     my $stderr = "";
1250     my $saved_stderr = undef;
1251     $stdin = " < ".$fileornull->($opts{stdin})  if exists($opts{stdin});
1252     $stdout= " > ".$fileornull->($opts{stdout}) if exists($opts{stdout});
1253     $stderr=" 2> ".$fileornull->($opts{stderr}) if exists($opts{stderr});
1254
1255     my $display_cmd = "$cmdstr$stdin$stdout$stderr";
1256
1257     # VMS program output escapes TAP::Parser
1258     if ($^O eq 'VMS') {
1259         $stderr=" 2> ".$null
1260             unless $stderr || !$ENV{HARNESS_ACTIVE} || $ENV{HARNESS_VERBOSE};
1261     }
1262
1263     $cmdstr .= "$stdin$stdout$stderr";
1264
1265     if ($debug) {
1266         print STDERR "DEBUG[__decorate_cmd]: \$cmdstr = \"$cmdstr\"\n";
1267         print STDERR "DEBUG[__decorate_cmd]: \$display_cmd = \"$display_cmd\"\n";
1268     }
1269
1270     return ($cmdstr, $display_cmd);
1271 }
1272
1273 =head1 SEE ALSO
1274
1275 L<Test::More>, L<Test::Harness>
1276
1277 =head1 AUTHORS
1278
1279 Richard Levitte E<lt>levitte@openssl.orgE<gt> with assistance and
1280 inspiration from Andy Polyakov E<lt>appro@openssl.org<gt>.
1281
1282 =cut
1283
1284 no warnings 'redefine';
1285 sub subtest {
1286     $level++;
1287
1288     Test::More::subtest @_;
1289
1290     $level--;
1291 };
1292
1293 1;