Fix errors found by new find-doc-nits
[openssl.git] / util / find-doc-nits
1 #! /usr/bin/env perl
2 # Copyright 2002-2019 The OpenSSL Project Authors. All Rights Reserved.
3 #
4 # Licensed under the Apache License 2.0 (the "License").  You may not use
5 # this file except in compliance with the License.  You can obtain a copy
6 # in the file LICENSE in the source distribution or at
7 # https://www.openssl.org/source/license.html
8
9
10 require 5.10.0;
11 use warnings;
12 use strict;
13 use Pod::Checker;
14 use File::Find;
15 use File::Basename;
16 use File::Spec::Functions;
17 use Getopt::Std;
18 use lib catdir(dirname($0), "perl");
19 use OpenSSL::Util::Pod;
20
21 my $debug = 0;                  # Set to 1 for debug output
22
23 # Options.
24 our($opt_d);
25 our($opt_e);
26 our($opt_s);
27 our($opt_o);
28 our($opt_h);
29 our($opt_l);
30 our($opt_n);
31 our($opt_p);
32 our($opt_u);
33 our($opt_v);
34 our($opt_c);
35
36 sub help {
37     print <<EOF;
38 Find small errors (nits) in documentation.  Options:
39     -d Detailed list of undocumented (implies -u)
40     -e Detailed list of new undocumented (implies -v)
41     -s Same as -e except no output is generated if nothing is undocumented
42     -o Causes -e/-v to count symbols added since 1.1.1 as new (implies -v)
43     -l Print bogus links
44     -n Print nits in POD pages
45     -p Warn if non-public name documented (implies -n)
46     -u Count undocumented functions
47     -v Count new undocumented functions
48     -h Print this help message
49     -c List undocumented commands and options
50 EOF
51     exit;
52 }
53
54 my $temp = '/tmp/docnits.txt';
55 my $OUT;
56 my %public;
57 my $status = 0;
58
59 my %mandatory_sections =
60     ( '*'    => [ 'NAME', 'DESCRIPTION', 'COPYRIGHT' ],
61       1      => [ 'SYNOPSIS', 'OPTIONS' ],
62       3      => [ 'SYNOPSIS', 'RETURN VALUES' ],
63       5      => [ ],
64       7      => [ ] );
65
66 # Print error message, set $status.
67 sub err {
68     print join(" ", @_), "\n";
69     $status = 1
70 }
71
72 # Cross-check functions in the NAME and SYNOPSIS section.
73 sub name_synopsis {
74     my $id = shift;
75     my $filename = shift;
76     my $contents = shift;
77
78     # Get NAME section and all words in it.
79     return unless $contents =~ /=head1 NAME(.*)=head1 SYNOPSIS/ms;
80     my $tmp = $1;
81     $tmp =~ tr/\n/ /;
82     err($id, "trailing comma before - in NAME")
83         if $tmp =~ /, *-/;
84     $tmp =~ s/ -.*//g;
85     err($id, "POD markup among the names in NAME")
86         if $tmp =~ /[<>]/;
87     $tmp =~ s/  */ /g;
88     err($id, "missing comma in NAME")
89         if $tmp =~ /[^,] /;
90
91     my $dirname = dirname($filename);
92     my $simplename = basename(basename($filename, ".in"), ".pod");
93     my $foundfilename = 0;
94     my %foundfilenames = ();
95     my %names;
96     foreach my $n ( split ',', $tmp ) {
97         $n =~ s/^\s+//;
98         $n =~ s/\s+$//;
99         err($id, "the name '$n' contains white-space")
100             if $n =~ /\s/;
101         $names{$n} = 1;
102         $foundfilename++ if $n eq $simplename;
103         $foundfilenames{$n} = 1
104             if ((-f "$dirname/$n.pod.in" || -f "$dirname/$n.pod")
105                 && $n ne $simplename);
106     }
107     err($id, "the following exist as other .pod or .pod.in files:",
108          sort keys %foundfilenames)
109         if %foundfilenames;
110     err($id, "$simplename (filename) missing from NAME section")
111         unless $foundfilename;
112     foreach my $n ( keys %names ) {
113         err($id, "$n is not public")
114             if $opt_p and !defined $public{$n};
115     }
116
117     # Find all functions in SYNOPSIS
118     return unless $contents =~ /=head1 SYNOPSIS(.*)=head1 DESCRIPTION/ms;
119     my $syn = $1;
120     foreach my $line ( split /\n+/, $syn ) {
121         next unless $line =~ /^\s/;
122         my $sym;
123         $line =~ s/STACK_OF\([^)]+\)/int/g;
124         $line =~ s/SPARSE_ARRAY_OF\([^)]+\)/int/g;
125         $line =~ s/__declspec\([^)]+\)//;
126         if ( $line =~ /env (\S*)=/ ) {
127             # environment variable env NAME=...
128             $sym = $1;
129         } elsif ( $line =~ /typedef.*\(\*(\S+)\)\(.*/ ) {
130             # a callback function pointer: typedef ... (*NAME)(...
131             $sym = $1;
132         } elsif ( $line =~ /typedef.* (\S+)\(.*/ ) {
133             # a callback function signature: typedef ... NAME(...
134             $sym = $1;
135         } elsif ( $line =~ /typedef.* (\S+);/ ) {
136             # a simple typedef: typedef ... NAME;
137             $sym = $1;
138         } elsif ( $line =~ /enum (\S*) \{/ ) {
139             # an enumeration: enum ... {
140             $sym = $1;
141         } elsif ( $line =~ /#(?:define|undef) ([A-Za-z0-9_]+)/ ) {
142             $sym = $1;
143         } elsif ( $line =~ /([A-Za-z0-9_]+)\(/ ) {
144             $sym = $1;
145         }
146         else {
147             next;
148         }
149         err($id, "$sym missing from NAME section")
150             unless defined $names{$sym};
151         $names{$sym} = 2;
152
153         # Do some sanity checks on the prototype.
154         err($id, "prototype missing spaces around commas: $line")
155             if ( $line =~ /[a-z0-9],[^ ]/ );
156     }
157
158     foreach my $n ( keys %names ) {
159         next if $names{$n} == 2;
160         err($id, "$n missing from SYNOPSIS")
161     }
162 }
163
164 # Check if SECTION ($3) is located before BEFORE ($4)
165 sub check_section_location {
166     my $id = shift;
167     my $contents = shift;
168     my $section = shift;
169     my $before = shift;
170
171     return unless $contents =~ /=head1 $section/
172         and $contents =~ /=head1 $before/;
173     err($id, "$section should appear before $before section")
174         if $contents =~ /=head1 $before.*=head1 $section/ms;
175 }
176
177 # Check if a =head1 is duplicated, or a =headX is duplicated within a
178 # =head1.  Treats =head2 =head3 as equivalent -- it doesn't reset the head3
179 # sets if it finds a =head2 -- but that is good enough for now. Also check
180 # for proper capitalization, trailing periods, etc.
181 sub check_head_style {
182     my $id = shift;
183     my $contents = shift;
184     my %head1;
185     my %subheads;
186
187     foreach my $line ( split /\n+/, $contents ) {
188         next unless $line =~ /^=head/;
189         if ( $line =~ /head1/ ) {
190             err($id, "duplicate section $line")
191                 if defined $head1{$line};
192             $head1{$line} = 1;
193             %subheads = ();
194         } else {
195             err($id, "duplicate subsection $line")
196                 if defined $subheads{$line};
197             $subheads{$line} = 1;
198         }
199         err($id, "period in =head")
200             if $line =~ /\.[^\w]/ or $line =~ /\.$/;
201         err($id, "not all uppercase in =head1")
202             if $line =~ /head1.*[a-z]/;
203         err($id, "all uppercase in subhead")
204             if $line =~ /head[234][ A-Z0-9]+$/;
205     }
206 }
207
208 # Because we have options and symbols with extra markup, we need
209 # to take that into account, so we need a regexp that extracts
210 # markup chunks, including recursive markup.
211 # please read up on /(?R)/ in perlre(1)
212 # (note: order is important, (?R) needs to come before .)
213 # (note: non-greedy is important, or something like 'B<foo> and B<bar>'
214 # will be captured as one item)
215 my $markup_re =
216     qr/(                        # Capture group
217            [BIL]<               # The start of what we recurse on
218            (?:(?-1)|.)*?        # recurse the whole regexp (refering to
219                                 # the last opened capture group, i.e. the
220                                 # start of this regexp), or pick next
221                                 # character.  Do NOT be greedy!
222            >                    # The end of what we recurse on
223        )/x;                     # (the x allows this sort of split up regexp)
224
225 # Options must start with a dash, followed by a letter, possibly
226 # followed by letters, digits, dashes and underscores, and the last
227 # character must be a letter or a digit.
228 # We do also accept the single -? or -n, where n is a digit
229 my $option_re =
230     qr/(?:
231             \?                  # Single question mark
232             |
233             \d                  # Single digit
234             |
235             -                   # Single dash (--)
236             |
237             [[:alpha:]](?:[-_[:alnum:]]*?[[:alnum:]])?
238        )/x;
239
240 # Helper function to check if a given $thing is properly marked up
241 # option.  It returns one of these values:
242 #
243 # undef         if it's not an option
244 # ""            if it's a malformed option
245 # $unwrapped    the option with the outermost B<> wrapping removed.
246 sub normalise_option {
247     my $id = shift;
248     my $filename = shift;
249     my $thing = shift;
250
251     my $unwrapped = $thing;
252     my $unmarked = $thing;
253
254     # $unwrapped is the option with the outer B<> markup removed
255     $unwrapped =~ s/^B<//;
256     $unwrapped =~ s/>$//;
257     # $unmarked is the option with *all* markup removed
258     $unmarked =~ s/[BIL]<|>//msg;
259
260
261     # If we found an option, check it, collect it
262     if ( $unwrapped =~ /^\s*-/ ) {
263         return $unwrapped       # return option with outer B<> removed
264             if $unmarked =~ /^-${option_re}$/;
265         return "";              # Malformed option
266     }
267     return undef;               # Something else
268 }
269
270 # Checks of command option (man1) formatting.  The man1 checks are
271 # restricted to the SYNOPSIS and OPTIONS sections, the rest is too
272 # free form, we simply cannot be too strict there.
273
274 sub option_check {
275     my $id = shift;
276     my $filename = shift;
277     my $contents = shift;
278
279     my $synopsis = ($contents =~ /=head1\s+SYNOPSIS(.*?)=head1/s, $1);
280
281     # Some pages have more than one OPTIONS section, let's make sure
282     # to get them all
283     my $options = '';
284     while ( $contents =~ /=head1\s+[A-Z ]*?OPTIONS$(.*?)(?==head1)/msg ) {
285         $options .= $1;
286     }
287
288     # Look for options with no or incorrect markup
289     while ( $synopsis =~
290             /(?<![-<[:alnum:]])-(?:$markup_re|.)*(?![->[:alnum:]])/msg ) {
291         err($id, "Malformed option [1] in SYNOPSIS: $&");
292     }
293
294     while ( $synopsis =~ /$markup_re/msg ) {
295         my $found = $&;
296         print STDERR "$id:DEBUG[option_check] SYNOPSIS: found $found\n"
297             if $debug;
298         my $option_uw = normalise_option($id, $filename, $found);
299         err($id, "Malformed option [2] in SYNOPSIS: $found")
300             if defined $option_uw && $option_uw eq '';
301     }
302
303     # In OPTIONS, we look for =item paragraphs.
304     # (?=^\s*$) detects an empty line.
305     while ( $options =~ /=item\s+(.*?)(?=^\s*$)/msg ) {
306         my $item = $&;
307
308         while ( $item =~ /(\[\s*)?($markup_re)/msg ) {
309             my $found = $2;
310             print STDERR "$id:DEBUG[option_check] OPTIONS: found $&\n"
311                 if $debug;
312             err($id, "Unexpected bracket in OPTIONS =item: $item")
313                 if ($1 // '') ne '' && $found =~ /^B<\s*-/;
314
315             my $option_uw = normalise_option($id, $filename, $found);
316             err($id, "Malformed option in OPTIONS: $found")
317                 if defined $option_uw && $option_uw eq '';
318         }
319     }
320 }
321
322 # Normal symbol form
323 my $symbol_re = qr/[[:alpha:]_][_[:alnum:]]*?/;
324
325 # Checks of function name (man3) formatting.  The man3 checks are
326 # easier than the man1 checks, we only check the names followed by (),
327 # and only the names that have POD markup.
328
329 sub functionname_check {
330     my $id = shift;
331     my $filename = shift;
332     my $contents = shift;
333
334     while ( $contents =~ /($markup_re)\(\)/msg ) {
335         print STDERR "$id:DEBUG[functionname_check] SYNOPSIS: found $&\n"
336             if $debug;
337
338         my $symbol = $1;
339         my $unmarked = $symbol;
340         $unmarked =~ s/[BIL]<|>//msg;
341
342         err($id, "Malformed symbol: $symbol")
343             unless $symbol =~ /^B<.*>$/ && $unmarked =~ /^${symbol_re}$/
344     }
345
346     # We can't do the kind of collecting coolness that option_check()
347     # does, because there are too many things that can't be found in
348     # name repositories like the NAME sections, such as symbol names
349     # with a variable part (typically marked up as B<foo_I<TYPE>_bar>
350 }
351
352 # This is from http://man7.org/linux/man-pages/man7/man-pages.7.html
353 my %preferred_words = (
354     'bitmask'       => 'bit mask',
355     'builtin'       => 'built-in',
356    #'epoch'         => 'Epoch', # handled specially, below
357     'file name'     => 'filename',
358     'file system'   => 'filesystem',
359     'host name'     => 'hostname',
360     'i-node'        => 'inode',
361     'lower case'    => 'lowercase',
362     'lower-case'    => 'lowercase',
363     'non-zero'      => 'nonzero',
364     'path name'     => 'pathname',
365     'pseudo-terminal' => 'pseudoterminal',
366     'reserved port' => 'privileged port',
367     'system port'   => 'privileged port',
368     'realtime'      => 'real-time',
369     'real time'     => 'real-time',
370     'runtime'       => 'run time',
371     'saved group ID'=> 'saved set-group-ID',
372     'saved set-GID' => 'saved set-group-ID',
373     'saved user ID' => 'saved set-user-ID',
374     'saved set-UID' => 'saved set-user-ID',
375     'set-GID'       => 'set-group-ID',
376     'setgid'        => 'set-group-ID',
377     'set-UID'       => 'set-user-ID',
378     'setuid'        => 'set-user-ID',
379     'super user'    => 'superuser',
380     'super-user'    => 'superuser',
381     'super block'   => 'superblock',
382     'super-block'   => 'superblock',
383     'time stamp'    => 'timestamp',
384     'time zone'     => 'timezone',
385     'upper case'    => 'uppercase',
386     'upper-case'    => 'uppercase',
387     'useable'       => 'usable',
388     'userspace'     => 'user space',
389     'user name'     => 'username',
390     'zeroes'        => 'zeros'
391 );
392
393 sub wording {
394     my $id = shift;
395     my $contents = shift;
396
397     foreach my $k ( keys %preferred_words ) {
398         # Sigh, trademark
399         next if $k eq 'file system'
400             and $contents =~ /Microsoft Encrypted File System/;
401         err($id, "found '$k' should use '$preferred_words{$k}'")
402             if $contents =~ /\b\Q$k\E\b/i;
403     }
404     err($id, "found 'epoch' should use 'Epoch'")
405         if $contents =~ /\bepoch\b/;
406 }
407
408 sub check {
409     my $filename = shift;
410     my $dirname = basename(dirname($filename));
411
412     my $contents = '';
413     {
414         local $/ = undef;
415         open POD, $filename or die "Couldn't open $filename, $!";
416         $contents = <POD>;
417         close POD;
418     }
419
420     my $id = "${filename}:1:";
421     check_head_style($id, $contents);
422
423     # Check ordering of some sections in man3
424     if ( $filename =~ m|man3/| ) {
425         check_section_location($id, $contents, "RETURN VALUES", "EXAMPLES");
426         check_section_location($id, $contents, "SEE ALSO", "HISTORY");
427         check_section_location($id, $contents, "EXAMPLES", "SEE ALSO");
428     }
429
430     unless ( $contents =~ /=for comment generic/ ) {
431         if ( $filename =~ m|man3/| ) {
432             name_synopsis($id, $filename, $contents);
433             functionname_check($id, $filename, $contents);
434         } elsif ( $filename =~ m|man1/| ) {
435             option_check($id, $filename, $contents)
436         }
437     }
438
439     wording($id, $contents);
440
441     err($id, "doesn't start with =pod")
442         if $contents !~ /^=pod/;
443     err($id, "doesn't end with =cut")
444         if $contents !~ /=cut\n$/;
445     err($id, "more than one cut line.")
446         if $contents =~ /=cut.*=cut/ms;
447     err($id, "EXAMPLE not EXAMPLES section.")
448         if $contents =~ /=head1 EXAMPLE[^S]/;
449     err($id, "WARNING not WARNINGS section.")
450         if $contents =~ /=head1 WARNING[^S]/;
451     err($id, "missing copyright")
452         if $contents !~ /Copyright .* The OpenSSL Project Authors/;
453     err($id, "copyright not last")
454         if $contents =~ /head1 COPYRIGHT.*=head/ms;
455     err($id, "head2 in All uppercase")
456         if $contents =~ /head2\s+[A-Z ]+\n/;
457     err($id, "extra space after head")
458         if $contents =~ /=head\d\s\s+/;
459     err($id, "period in NAME section")
460         if $contents =~ /=head1 NAME.*\.\n.*=head1 SYNOPSIS/ms;
461     err($id, "Duplicate $1 in L<>")
462         if $contents =~ /L<([^>]*)\|([^>]*)>/ && $1 eq $2;
463     err($id, "Bad =over $1")
464         if $contents =~ /=over([^ ][^24])/;
465     err($id, "Possible version style issue")
466         if $contents =~ /OpenSSL version [019]/;
467
468     if ( $contents !~ /=for comment multiple includes/ ) {
469         # Look for multiple consecutive openssl #include lines
470         # (non-consecutive lines are okay; see man3/MD5.pod).
471         if ( $contents =~ /=head1 SYNOPSIS(.*)=head1 DESCRIPTION/ms ) {
472             my $count = 0;
473             foreach my $line ( split /\n+/, $1 ) {
474                 if ( $line =~ m@include <openssl/@ ) {
475                     err($id, "has multiple includes")
476                         if ++$count == 2;
477                 } else {
478                     $count = 0;
479                 }
480             }
481         }
482     }
483
484     open my $OUT, '>', $temp
485         or die "Can't open $temp, $!";
486     podchecker($filename, $OUT);
487     close $OUT;
488     open $OUT, '<', $temp
489         or die "Can't read $temp, $!";
490     while ( <$OUT> ) {
491         next if /\(section\) in.*deprecated/;
492         print;
493     }
494     close $OUT;
495     unlink $temp || warn "Can't remove $temp, $!";
496
497     # Find what section this page is in; assume 3.
498     my $section = 3;
499     $section = $1 if $dirname =~ /man([1-9])/;
500
501     foreach ((@{$mandatory_sections{'*'}}, @{$mandatory_sections{$section}})) {
502         # Skip "return values" if not -s
503         err($id, "missing $_ head1 section")
504             if $contents !~ /^=head1\s+${_}\s*$/m;
505     }
506 }
507
508 my %dups;
509
510 sub parsenum {
511     my $file = shift;
512     my @apis;
513
514     open my $IN, '<', $file
515         or die "Can't open $file, $!, stopped";
516
517     while ( <$IN> ) {
518         next if /^#/;
519         next if /\bNOEXIST\b/;
520         my @fields = split();
521         die "Malformed line $_"
522             if scalar @fields != 2 && scalar @fields != 4;
523         push @apis, $fields[0];
524     }
525
526     close $IN;
527
528     print "# Found ", scalar(@apis), " in $file\n" unless $opt_p;
529     return sort @apis;
530 }
531
532 sub getdocced
533 {
534     my $dir = shift;
535     my %return;
536
537     foreach my $pod ( glob("$dir/*.pod"), glob("$dir/*.pod.in") ) {
538         my %podinfo = extract_pod_info($pod);
539         foreach my $n ( @{$podinfo{names}} ) {
540             $return{$n} = $pod;
541             print "# Duplicate $n in $pod and $dups{$n}\n"
542                 if defined $dups{$n} && $dups{$n} ne $pod;
543             $dups{$n} = $pod;
544         }
545     }
546
547     return %return;
548 }
549
550 my %docced;
551
552 sub loadmissing($)
553 {
554     my $missingfile = shift;
555     my @missing;
556
557     open FH, $missingfile
558         || die "Can't open $missingfile";
559     while ( <FH> ) {
560         chomp;
561         next if /^#/;
562         push @missing, $_;
563     }
564     close FH;
565
566     return @missing;
567 }
568
569 sub checkmacros {
570     my $count = 0;
571     my %seen;
572     my @missing;
573
574     if ($opt_o) {
575         @missing = loadmissing('util/missingmacro111.txt');
576     } elsif ($opt_v) {
577         @missing = loadmissing('util/missingmacro.txt');
578     }
579
580     print "# Checking macros (approximate)\n"
581         if !$opt_s;
582     foreach my $f ( glob('include/openssl/*.h') ) {
583         # Skip some internals we don't want to document yet.
584         next if $f eq 'include/openssl/asn1.h';
585         next if $f eq 'include/openssl/asn1t.h';
586         next if $f eq 'include/openssl/err.h';
587         open(IN, $f) || die "Can't open $f, $!";
588         while ( <IN> ) {
589             next unless /^#\s*define\s*(\S+)\(/;
590             my $macro = $1;
591             next if $docced{$macro} || defined $seen{$macro};
592             next if $macro =~ /i2d_/
593                 || $macro =~ /d2i_/
594                 || $macro =~ /DEPRECATEDIN/
595                 || $macro =~ /IMPLEMENT_/
596                 || $macro =~ /DECLARE_/;
597
598             # Skip macros known to be missing
599             next if $opt_v && grep( /^$macro$/, @missing);
600     
601             print "$f:$macro\n"
602                 if $opt_d || $opt_e;
603             $count++;
604             $seen{$macro} = 1;
605         }
606         close(IN);
607     }
608     print "# Found $count macros missing\n"
609         if !$opt_s || $count > 0;
610 }
611
612 sub printem {
613     my $libname = shift;
614     my $numfile = shift;
615     my $missingfile = shift;
616     my $count = 0;
617     my %seen;
618
619     my @missing = loadmissing($missingfile) if ($opt_v);
620
621     foreach my $func ( parsenum($numfile) ) {
622         next if $docced{$func} || defined $seen{$func};
623
624         # Skip ASN1 utilities
625         next if $func =~ /^ASN1_/;
626
627         # Skip functions known to be missing
628         next if $opt_v && grep( /^$func$/, @missing);
629
630         print "$libname:$func\n"
631             if $opt_d || $opt_e;
632         $count++;
633         $seen{$func} = 1;
634     }
635     print "# Found $count missing from $numfile\n\n"
636         if !$opt_s || $count > 0;
637 }
638
639
640 # Collection of links in each POD file.
641 # filename => [ "foo(1)", "bar(3)", ... ]
642 my %link_collection = ();
643 # Collection of names in each POD file.
644 # "name(s)" => filename
645 my %name_collection = ();
646
647 sub collectnames {
648     my $filename = shift;
649     $filename =~ m|man(\d)/|;
650     my $section = $1;
651     my $simplename = basename(basename($filename, ".in"), ".pod");
652     my $id = "${filename}:1:";
653
654     my $contents = '';
655     {
656         local $/ = undef;
657         open POD, $filename or die "Couldn't open $filename, $!";
658         $contents = <POD>;
659         close POD;
660     }
661
662     $contents =~ /=head1 NAME([^=]*)=head1 /ms;
663     my $tmp = $1;
664     unless (defined $tmp) {
665         err($id, "weird name section");
666         return;
667     }
668     $tmp =~ tr/\n/ /;
669     $tmp =~ s/ -.*//g;
670
671     my @names =
672         map { s|/|-|g; $_ }              # Treat slash as dash
673         map { s/^\s+//g; s/\s+$//g; $_ } # Trim prefix and suffix blanks
674         split(/,/, $tmp);
675     unless (grep { $simplename eq $_ } @names) {
676         err($id, "missing $simplename");
677         push @names, $simplename;
678     }
679     foreach my $name (@names) {
680         next if $name eq "";
681         if ($name =~ /\s/) {
682             err($id, "'$name' contains white space")
683         }
684         my $name_sec = "$name($section)";
685         if (! exists $name_collection{$name_sec}) {
686             $name_collection{$name_sec} = $filename;
687         } elsif ($filename eq $name_collection{$name_sec}) {
688             err($id, "$name_sec repeated in NAME section of",
689                  $name_collection{$name_sec});
690         } else {
691             err($id, "$name_sec also in NAME section of",
692                  $name_collection{$name_sec});
693         }
694     }
695
696     my @foreign_names =
697         map { map { s/\s+//g; $_ } split(/,/, $_) }
698         $contents =~ /=for\s+comment\s+foreign\s+manuals:\s*(.*)\n\n/;
699     foreach (@foreign_names) {
700         $name_collection{$_} = undef; # It still exists!
701     }
702
703     my @links = $contents =~ /L<
704                               # if the link is of the form L<something|name(s)>,
705                               # then remove 'something'.  Note that 'something'
706                               # may contain POD codes as well...
707                               (?:(?:[^\|]|<[^>]*>)*\|)?
708                               # we're only interested in references that have
709                               # a one digit section number
710                               ([^\/>\(]+\(\d\))
711                              /gx;
712     $link_collection{$filename} = [ @links ];
713 }
714
715 sub checklinks {
716     foreach my $filename (sort keys %link_collection) {
717         foreach my $link (@{$link_collection{$filename}}) {
718             err("${filename}:1:", "reference to non-existing $link")
719                 unless exists $name_collection{$link};
720         }
721     }
722 }
723
724 sub publicize {
725     foreach my $name ( parsenum('util/libcrypto.num') ) {
726         $public{$name} = 1;
727     }
728     foreach my $name ( parsenum('util/libssl.num') ) {
729         $public{$name} = 1;
730     }
731     foreach my $name ( parsenum('util/private.num') ) {
732         $public{$name} = 1;
733     }
734 }
735
736 # Cipher/digests to skip if not documented
737 my %skips = (
738     'aes128' => 1,
739     'aes192' => 1,
740     'aes256' => 1,
741     'aria128' => 1,
742     'aria192' => 1,
743     'aria256' => 1,
744     'camellia128' => 1,
745     'camellia192' => 1,
746     'camellia256' => 1,
747     'des' => 1,
748     'des3' => 1,
749     'idea' => 1,
750     'cipher' => 1,
751     'digest' => 1,
752 );
753
754 sub checkflags {
755     my $cmd = shift;
756     my $doc = shift;
757     my %cmdopts;
758     my %docopts;
759     my %localskips;
760
761     # Get the list of options in the command.
762     open CFH, "./apps/openssl list --options $cmd|"
763         || die "Can list options for $cmd, $!";
764     while ( <CFH> ) {
765         chop;
766         s/ .$//;
767         $cmdopts{$_} = 1;
768     }
769     close CFH;
770
771     # Get the list of flags from the synopsis
772     open CFH, "<$doc"
773         || die "Can't open $doc, $!";
774     while ( <CFH> ) {
775         chop;
776         last if /DESCRIPTION/;
777         if ( /=for comment ifdef (.*)/ ) {
778             foreach my $f ( split / /, $1 ) {
779                 $localskips{$f} = 1;
780             }
781             next;
782         }
783         next unless /\[B<-([^ >]+)/;
784         my $opt = $1;
785         $opt = $1 if $opt =~ /I<(.*)/;
786         $docopts{$1} = 1;
787     }
788     close CFH;
789
790     # See what's in the command not the manpage.
791     my @undocced = ();
792     foreach my $k ( keys %cmdopts ) {
793         push @undocced, $k unless $docopts{$k};
794     }
795     if ( scalar @undocced > 0 ) {
796         foreach ( @undocced ) {
797             err("$doc: undocumented option -$_");
798         }
799     }
800
801     # See what's in the command not the manpage.
802     my @unimpl = ();
803     foreach my $k ( keys %docopts ) {
804         push @unimpl, $k unless $cmdopts{$k};
805     }
806     if ( scalar @unimpl > 0 ) {
807         foreach ( @unimpl ) {
808             next if defined $skips{$_} || defined $localskips{$_};
809             err("$cmd documented but not implemented -$_");
810         }
811     }
812 }
813
814 getopts('cdesolnphuv');
815
816 help() if $opt_h;
817
818 $opt_n = 1 if $opt_p;
819 $opt_u = 1 if $opt_d;
820 $opt_e = 1 if $opt_s;
821 $opt_v = 1 if $opt_o || $opt_e;
822
823 die "Cannot use both -u and -v"
824     if $opt_u && $opt_v;
825 die "Cannot use both -d and -e"
826     if $opt_d && $opt_e;
827
828 # We only need to check c, l, n, u and v.
829 # Options d, e, s, o and p imply one of the above.
830 die "Need one of -[cdesolnpuv] flags.\n"
831     unless $opt_c or $opt_l or $opt_n or $opt_u or $opt_v;
832
833 if ( $opt_c ) {
834     my @commands = ();
835
836     # Get list of commands.
837     open FH, "./apps/openssl list -1 -commands|"
838         || die "Can't list commands, $!";
839     while ( <FH> ) {
840         chop;
841         push @commands, $_;
842     }
843     close FH;
844
845     # See if each has a manpage.
846     foreach my $cmd ( @commands ) {
847         next if $cmd eq 'help' || $cmd eq 'exit';
848         my $doc = "doc/man1/$cmd.pod";
849         $doc = "doc/man1/openssl-$cmd.pod" if -f "doc/man1/openssl-$cmd.pod";
850         if ( ! -f "$doc" ) {
851             err("$doc does not exist");
852         } else {
853             checkflags($cmd, $doc);
854         }
855     }
856
857     # See what help is missing.
858     open FH, "./apps/openssl list --missing-help |"
859         || die "Can't list missing help, $!";
860     while ( <FH> ) {
861         chop;
862         my ($cmd, $flag) = split;
863         err("$cmd has no help for -$flag");
864     }
865     close FH;
866
867     exit $status;
868 }
869
870 if ( $opt_l ) {
871     foreach (@ARGV ? @ARGV : (glob('doc/*/*.pod'), glob('doc/*/*.pod.in'),
872                               glob('doc/internal/*/*.pod'))) {
873         collectnames($_);
874     }
875     checklinks();
876 }
877
878 if ( $opt_n ) {
879     publicize() if $opt_p;
880     foreach (@ARGV ? @ARGV : (glob('doc/*/*.pod'), glob('doc/*/*.pod.in'))) {
881         check($_);
882     }
883     {
884         local $opt_p = undef;
885         foreach (@ARGV ? @ARGV : glob('doc/internal/*/*.pod')) {
886             check($_);
887         }
888     }
889
890     # If not given args, check that all man1 commands are named properly.
891     if ( scalar @ARGV == 0 ) {
892         foreach (glob('doc/man1/*.pod')) {
893             next if /CA.pl/ || /openssl.pod/;
894             err("$_ doesn't start with openssl-") unless /openssl-/;
895         }
896     }
897 }
898
899 if ( $opt_u || $opt_v) {
900     my %temp = getdocced('doc/man3');
901     foreach ( keys %temp ) {
902         $docced{$_} = $temp{$_};
903     }
904     if ($opt_o) {
905         printem('crypto', 'util/libcrypto.num', 'util/missingcrypto111.txt');
906         printem('ssl', 'util/libssl.num', 'util/missingssl111.txt');
907     } else {
908         printem('crypto', 'util/libcrypto.num', 'util/missingcrypto.txt');
909         printem('ssl', 'util/libssl.num', 'util/missingssl.txt');
910     }
911     checkmacros();
912 }
913
914 exit $status;