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