find-doc-nits: Minor improvements of help and diagnostic output
[openssl.git] / util / find-doc-nits
1 #! /usr/bin/env perl
2 # Copyright 2002-2021 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 Carp qw(:DEFAULT cluck);
15 use Pod::Checker;
16 use File::Find;
17 use File::Basename;
18 use File::Spec::Functions;
19 use Getopt::Std;
20 use FindBin;
21 use lib "$FindBin::Bin/perl";
22
23 use OpenSSL::Util::Pod;
24
25 use lib '.';
26 use configdata;
27
28 # Set to 1 for debug output
29 my $debug = 0;
30
31 # Options.
32 our($opt_d);
33 our($opt_e);
34 our($opt_s);
35 our($opt_o);
36 our($opt_h);
37 our($opt_l);
38 our($opt_n);
39 our($opt_p);
40 our($opt_u);
41 our($opt_v);
42 our($opt_c);
43
44 # Print usage message and exit.
45 sub help {
46     print <<EOF;
47 Find small errors (nits) in documentation.  Options:
48     -c List undocumented commands, undocumented options and unimplemented options.
49     -d Detailed list of undocumented (implies -u)
50     -e Detailed list of new undocumented (implies -v)
51     -h Print this help message
52     -l Print bogus links
53     -n Print nits in POD pages
54     -o Causes -e/-v to count symbols added since 1.1.1 as new (implies -v)
55     -u Count undocumented functions
56     -v Count new undocumented functions
57 EOF
58     exit;
59 }
60
61 getopts('cdehlnouv');
62
63 help() if $opt_h;
64 $opt_u = 1 if $opt_d;
65 $opt_v = 1 if $opt_o || $opt_e;
66 die "Cannot use both -u and -v"
67     if $opt_u && $opt_v;
68 die "Cannot use both -d and -e"
69     if $opt_d && $opt_e;
70
71 # We only need to check c, l, n, u and v.
72 # Options d, e, o imply one of the above.
73 die "Need one of -[cdehlnouv] flags.\n"
74     unless $opt_c or $opt_l or $opt_n or $opt_u or $opt_v;
75
76
77 my $temp = '/tmp/docnits.txt';
78 my $OUT;
79 my $status = 0;
80
81 my @sections = ( 'man1', 'man3', 'man5', 'man7' );
82 my %mandatory_sections = (
83     '*' => [ 'NAME', 'DESCRIPTION', 'COPYRIGHT' ],
84     1   => [ 'SYNOPSIS', 'OPTIONS' ],
85     3   => [ 'SYNOPSIS', 'RETURN VALUES' ],
86     5   => [ ],
87     7   => [ ]
88                          );
89
90 # Symbols that we ignored.
91 # They are reserved macros that we currently don't document
92 my $ignored = qr/(?| ^i2d_
93                  |   ^d2i_
94                  |   ^DEPRECATEDIN
95                  |   ^OSSL_DEPRECATED
96                  |   \Q_fnsig(3)\E$
97                  |   ^IMPLEMENT_
98                  |   ^_?DECLARE_
99                  |   ^sk_
100                  |   ^SKM_DEFINE_STACK_OF_INTERNAL
101                  |   ^lh_
102                  |   ^DEFINE_LHASH_OF_INTERNAL
103                  )/x;
104
105 # A common regexp for C symbol names
106 my $C_symbol = qr/\b[[:alpha:]][_[:alnum:]]*\b/;
107
108 # Collect all POD files, both internal and public, and regardless of location
109 # We collect them in a hash table with each file being a key, so we can attach
110 # tags to them.  For example, internal docs will have the word "internal"
111 # attached to them.
112 my %files = ();
113 # We collect files names on the fly, on known tag basis
114 my %collected_tags = ();
115 # We cache results based on tags
116 my %collected_results = ();
117
118 # files OPTIONS
119 #
120 # Example:
121 #
122 #       files(TAGS => 'manual');
123 #       files(TAGS => [ 'manual', 'man1' ]);
124 #
125 # This function returns an array of files corresponding to a set of tags
126 # given with the options "TAGS".  The value of this option can be a single
127 # word, or an array of several words, which work as inclusive or exclusive
128 # selectors.  Inclusive selectors are used to add one more set of files to
129 # the returned array, while exclusive selectors limit the set of files added
130 # to the array.  The recognised tag values are:
131 #
132 # 'public_manual'       - inclusive selector, adds public manuals to the
133 #                         returned array of files.
134 # 'internal_manual'     - inclusive selector, adds internal manuals to the
135 #                         returned array of files.
136 # 'manual'              - inclusive selector, adds any manual to the returned
137 #                         array of files.  This is really a shorthand for
138 #                         'public_manual' and 'internal_manual' combined.
139 # 'public_header'       - inclusive selector, adds public headers to the
140 #                         returned array of files.
141 # 'header'              - inclusive selector, adds any header file to the
142 #                         returned array of files.  Since we currently only
143 #                         care about public headers, this is exactly
144 #                         equivalent to 'public_header', but is present for
145 #                         consistency.
146 #
147 # 'man1', 'man3', 'man5', 'man7'
148 #                       - exclusive selectors, only applicable together with
149 #                         any of the manual selectors.  If any of these are
150 #                         present, only the manuals from the given sections
151 #                         will be include.  If none of these are present,
152 #                         the manuals from all sections will be returned.
153 #
154 # All returned manual files come from configdata.pm.
155 # All returned header files come from looking inside
156 # "$config{sourcedir}/include/openssl"
157 #
158 sub files {
159     my %opts = ( @_ );          # Make a copy of the arguments
160
161     $opts{TAGS} = [ $opts{TAGS} ] if ref($opts{TAGS}) eq '';
162
163     croak "No tags given, or not an array"
164         unless exists $opts{TAGS} && ref($opts{TAGS}) eq 'ARRAY';
165
166     my %tags = map { $_ => 1 } @{$opts{TAGS}};
167     $tags{public_manual} = 1
168         if $tags{manual} && ($tags{public} // !$tags{internal});
169     $tags{internal_manual} = 1
170         if $tags{manual} && ($tags{internal} // !$tags{public});
171     $tags{public_header} = 1
172         if $tags{header} && ($tags{public} // !$tags{internal});
173     delete $tags{manual};
174     delete $tags{header};
175     delete $tags{public};
176     delete $tags{internal};
177
178     my $tags_as_key = join(':', sort keys %tags);
179
180     cluck  "DEBUG[files]: This is how we got here!" if $debug;
181     print STDERR "DEBUG[files]: tags: $tags_as_key\n" if $debug;
182
183     my %tags_to_collect = ( map { $_ => 1 }
184                             grep { !exists $collected_tags{$_} }
185                             keys %tags );
186
187     if ($tags_to_collect{public_manual}) {
188         print STDERR "DEBUG[files]: collecting public manuals\n"
189             if $debug;
190
191         # The structure in configdata.pm is that $unified_info{mandocs}
192         # contains lists of man files, and in turn, $unified_info{depends}
193         # contains hash tables showing which POD file each of those man
194         # files depend on.  We use that information to find the POD files,
195         # and to attach the man section they belong to as tags
196         foreach my $mansect ( @sections ) {
197             foreach ( map { @{$unified_info{depends}->{$_}} }
198                       @{$unified_info{mandocs}->{$mansect}} ) {
199                 $files{$_} = { $mansect => 1, public_manual => 1 };
200             }
201         }
202         $collected_tags{public_manual} = 1;
203     }
204
205     if ($tags_to_collect{internal_manual}) {
206         print STDERR "DEBUG[files]: collecting internal manuals\n"
207             if $debug;
208
209         # We don't have the internal docs in configdata.pm.  However, they
210         # are all in the source tree, so they're easy to find.
211         foreach my $mansect ( @sections ) {
212             foreach ( glob(catfile($config{sourcedir},
213                                    'doc', 'internal', $mansect, '*.pod')) ) {
214                 $files{$_} = { $mansect => 1, internal_manual => 1 };
215             }
216         }
217         $collected_tags{internal_manual} = 1;
218     }
219
220     if ($tags_to_collect{public_header}) {
221         print STDERR "DEBUG[files]: collecting public headers\n"
222             if $debug;
223
224         foreach ( glob(catfile($config{sourcedir},
225                                'include', 'openssl', '*.h')) ) {
226             $files{$_} = { public_header => 1 };
227         }
228     }
229
230     my @result = @{$collected_results{$tags_as_key} // []};
231
232     if (!@result) {
233         # Produce a result based on caller tags
234         foreach my $type ( ( 'public_manual', 'internal_manual' ) ) {
235             next unless $tags{$type};
236
237             # If caller asked for specific sections, we care about sections.
238             # Otherwise, we give back all of them.
239             my @selected_sections =
240                 grep { $tags{$_} } @sections;
241             @selected_sections = @sections unless @selected_sections;
242
243             foreach my $section ( ( @selected_sections ) ) {
244                 push @result,
245                     ( sort { basename($a) cmp basename($b) }
246                       grep { $files{$_}->{$type} && $files{$_}->{$section} }
247                       keys %files );
248             }
249         }
250         if ($tags{public_header}) {
251             push @result,
252                 ( sort { basename($a) cmp basename($b) }
253                   grep { $files{$_}->{public_header} }
254                   keys %files );
255         }
256
257         if ($debug) {
258             print STDERR "DEBUG[files]: result:\n";
259             print STDERR "DEBUG[files]:     $_\n" foreach @result;
260         }
261         $collected_results{$tags_as_key} = [ @result ];
262     }
263
264     return @result;
265 }
266
267 # Print error message, set $status.
268 sub err {
269     print join(" ", @_), "\n";
270     $status = 1
271 }
272
273 # Cross-check functions in the NAME and SYNOPSIS section.
274 sub name_synopsis {
275     my $id = shift;
276     my $filename = shift;
277     my $contents = shift;
278
279     # Get NAME section and all words in it.
280     return unless $contents =~ /=head1 NAME(.*)=head1 SYNOPSIS/ms;
281     my $tmp = $1;
282     $tmp =~ tr/\n/ /;
283     err($id, "Trailing comma before - in NAME")
284         if $tmp =~ /, *-/;
285     $tmp =~ s/ -.*//g;
286     err($id, "POD markup among the names in NAME")
287         if $tmp =~ /[<>]/;
288     $tmp =~ s/  */ /g;
289     err($id, "Missing comma in NAME")
290         if $tmp =~ /[^,] /;
291
292     my $dirname = dirname($filename);
293     my $section = basename($dirname);
294     my $simplename = basename($filename, ".pod");
295     my $foundfilename = 0;
296     my %foundfilenames = ();
297     my %names;
298     foreach my $n ( split ',', $tmp ) {
299         $n =~ s/^\s+//;
300         $n =~ s/\s+$//;
301         err($id, "The name '$n' contains white-space")
302             if $n =~ /\s/;
303         $names{$n} = 1;
304         $foundfilename++ if $n eq $simplename;
305         $foundfilenames{$n} = 1
306             if ( ( grep { basename($_) eq "$n.pod" }
307                    files(TAGS => [ 'manual', $section ]) )
308                  && $n ne $simplename );
309     }
310     err($id, "The following exist as other .pod files:",
311          sort keys %foundfilenames)
312         if %foundfilenames;
313     err($id, "$simplename (filename) missing from NAME section")
314         unless $foundfilename;
315
316     # Find all functions in SYNOPSIS
317     return unless $contents =~ /=head1 SYNOPSIS(.*)=head1 DESCRIPTION/ms;
318     my $syn = $1;
319     my $ignore_until = undef;   # If defined, this is a regexp
320     # Remove all non-code lines
321     $syn =~ s/^(?:\s*?|\S.*?)$//msg;
322     # Remove all comments
323     $syn =~ s/\/\*.*?\*\///msg;
324     while ( $syn ) {
325         # "env" lines end at a newline.
326         # Preprocessor lines start with a # and end at a newline.
327         # Other lines end with a semicolon, and may cover more than
328         # one physical line.
329         if ( $syn !~ /^ \s*(env .*?|#.*?|.*?;)\s*$/ms ) {
330             err($id, "Can't parse rest of synopsis:\n$syn\n(declarations not ending with a semicolon (;)?)");
331             last;
332         }
333         my $line = $1;
334         $syn = $';
335
336         print STDERR "DEBUG[name_synopsis] \$line = '$line'\n" if $debug;
337
338         # Special code to skip over documented structures
339         if ( defined $ignore_until) {
340             next if $line !~ /$ignore_until/;
341             $ignore_until = undef;
342             next;
343         }
344         if ( $line =~ /^\s*(?:typedef\s+)?struct(?:\s+\S+)\s*\{/ ) {
345             $ignore_until = qr/\}.*?;/;
346             next;
347         }
348
349         my $sym;
350         my $is_prototype = 1;
351         $line =~ s/LHASH_OF\([^)]+\)/int/g;
352         $line =~ s/STACK_OF\([^)]+\)/int/g;
353         $line =~ s/SPARSE_ARRAY_OF\([^)]+\)/int/g;
354         $line =~ s/__declspec\([^)]+\)//;
355
356         ## We don't prohibit that space, to allow typedefs looking like
357         ## this:
358         ##
359         ## typedef int (fantastically_long_name_breaks_80char_limit)
360         ##     (fantastically_long_name_breaks_80char_limit *something);
361         ##
362         #if ( $line =~ /typedef.*\(\*?\S+\)\s+\(/ ) {
363         #    # a callback function with whitespace before the argument list:
364         #    # typedef ... (*NAME) (...
365         #    # typedef ... (NAME) (...
366         #    err($id, "Function typedef has space before arg list: $line");
367         #}
368
369         if ( $line =~ /env (\S*)=/ ) {
370             # environment variable env NAME=...
371             $sym = $1;
372         } elsif ( $line =~ /typedef.*\(\*?($C_symbol)\)\s*\(/ ) {
373             # a callback function pointer: typedef ... (*NAME)(...
374             # a callback function signature: typedef ... (NAME)(...
375             $sym = $1;
376         } elsif ( $line =~ /typedef.*($C_symbol)\s*\(/ ) {
377             # a callback function signature: typedef ... NAME(...
378             $sym = $1;
379         } elsif ( $line =~ /typedef.*($C_symbol);/ ) {
380             # a simple typedef: typedef ... NAME;
381             $is_prototype = 0;
382             $sym = $1;
383         } elsif ( $line =~ /enum ($C_symbol) \{/ ) {
384             # an enumeration: enum ... {
385             $sym = $1;
386         } elsif ( $line =~ /#\s*(?:define|undef) ($C_symbol)/ ) {
387             $is_prototype = 0;
388             $sym = $1;
389         } elsif ( $line =~ /^[^\(]*?\(\*($C_symbol)\s*\(/ ) {
390             # a function returning a function pointer: TYPE (*NAME(args))(args)
391             $sym = $1;
392         } elsif ( $line =~ /^[^\(]*?($C_symbol)\s*\(/ ) {
393             # a simple function declaration
394             $sym = $1;
395         }
396         else {
397             next;
398         }
399
400         print STDERR "DEBUG[name_synopsis] \$sym = '$sym'\n" if $debug;
401
402         err($id, "$sym missing from NAME section")
403             unless defined $names{$sym};
404         $names{$sym} = 2;
405
406         # Do some sanity checks on the prototype.
407         err($id, "Prototype missing spaces around commas: $line")
408             if $is_prototype && $line =~ /[a-z0-9],[^\s]/;
409     }
410
411     foreach my $n ( keys %names ) {
412         next if $names{$n} == 2;
413         err($id, "$n missing from SYNOPSIS")
414     }
415 }
416
417 # Check if SECTION ($3) is located before BEFORE ($4)
418 sub check_section_location {
419     my $id = shift;
420     my $contents = shift;
421     my $section = shift;
422     my $before = shift;
423
424     return unless $contents =~ /=head1 $section/
425         and $contents =~ /=head1 $before/;
426     err($id, "$section should appear before $before section")
427         if $contents =~ /=head1 $before.*=head1 $section/ms;
428 }
429
430 # Check if a =head1 is duplicated, or a =headX is duplicated within a
431 # =head1.  Treats =head2 =head3 as equivalent -- it doesn't reset the head3
432 # sets if it finds a =head2 -- but that is good enough for now. Also check
433 # for proper capitalization, trailing periods, etc.
434 sub check_head_style {
435     my $id = shift;
436     my $contents = shift;
437     my %head1;
438     my %subheads;
439
440     foreach my $line ( split /\n+/, $contents ) {
441         next unless $line =~ /^=head/;
442         if ( $line =~ /head1/ ) {
443             err($id, "Duplicate section $line")
444                 if defined $head1{$line};
445             $head1{$line} = 1;
446             %subheads = ();
447         } else {
448             err($id, "Duplicate subsection $line")
449                 if defined $subheads{$line};
450             $subheads{$line} = 1;
451         }
452         err($id, "Period in =head")
453             if $line =~ /\.[^\w]/ or $line =~ /\.$/;
454         err($id, "not all uppercase in =head1")
455             if $line =~ /head1.*[a-z]/;
456         err($id, "All uppercase in subhead")
457             if $line =~ /head[234][ A-Z0-9]+$/;
458     }
459 }
460
461 # Because we have options and symbols with extra markup, we need
462 # to take that into account, so we need a regexp that extracts
463 # markup chunks, including recursive markup.
464 # please read up on /(?R)/ in perlre(1)
465 # (note: order is important, (?R) needs to come before .)
466 # (note: non-greedy is important, or something like 'B<foo> and B<bar>'
467 # will be captured as one item)
468 my $markup_re =
469     qr/(                        # Capture group
470            [BIL]<               # The start of what we recurse on
471            (?:(?-1)|.)*?        # recurse the whole regexp (referring to
472                                 # the last opened capture group, i.e. the
473                                 # start of this regexp), or pick next
474                                 # character.  Do NOT be greedy!
475            >                    # The end of what we recurse on
476        )/x;                     # (the x allows this sort of split up regexp)
477
478 # Options must start with a dash, followed by a letter, possibly
479 # followed by letters, digits, dashes and underscores, and the last
480 # character must be a letter or a digit.
481 # We do also accept the single -? or -n, where n is a digit
482 my $option_re =
483     qr/(?:
484             \?                  # Single question mark
485             |
486             \d                  # Single digit
487             |
488             -                   # Single dash (--)
489             |
490             [[:alpha:]](?:[-_[:alnum:]]*?[[:alnum:]])?
491        )/x;
492
493 # Helper function to check if a given $thing is properly marked up
494 # option.  It returns one of these values:
495 #     undef         if it's not an option
496 #     ""            if it's a malformed option
497 #     $unwrapped    the option with the outermost B<> wrapping removed.
498 sub normalise_option {
499     my $id = shift;
500     my $filename = shift;
501     my $thing = shift;
502
503     my $unwrapped = $thing;
504     my $unmarked = $thing;
505
506     # $unwrapped is the option with the outer B<> markup removed
507     $unwrapped =~ s/^B<//;
508     $unwrapped =~ s/>$//;
509     # $unmarked is the option with *all* markup removed
510     $unmarked =~ s/[BIL]<|>//msg;
511
512
513     # If we found an option, check it, collect it
514     if ( $unwrapped =~ /^\s*-/ ) {
515         return $unwrapped       # return option with outer B<> removed
516             if $unmarked =~ /^-${option_re}$/;
517         return "";              # Malformed option
518     }
519     return undef;               # Something else
520 }
521
522 # Checks of command option (man1) formatting.  The man1 checks are
523 # restricted to the SYNOPSIS and OPTIONS sections, the rest is too
524 # free form, we simply cannot be too strict there.
525
526 sub option_check {
527     my $id = shift;
528     my $filename = shift;
529     my $contents = shift;
530
531     my $synopsis = ($contents =~ /=head1\s+SYNOPSIS(.*?)=head1/s, $1);
532
533     # Some pages have more than one OPTIONS section, let's make sure
534     # to get them all
535     my $options = '';
536     while ( $contents =~ /=head1\s+[A-Z ]*?OPTIONS$(.*?)(?==head1)/msg ) {
537         $options .= $1;
538     }
539
540     # Look for options with no or incorrect markup
541     while ( $synopsis =~
542             /(?<![-<[:alnum:]])-(?:$markup_re|.)*(?![->[:alnum:]])/msg ) {
543         err($id, "Malformed option [1] in SYNOPSIS: $&");
544     }
545
546     while ( $synopsis =~ /$markup_re/msg ) {
547         my $found = $&;
548         print STDERR "$id:DEBUG[option_check] SYNOPSIS: found $found\n"
549             if $debug;
550         my $option_uw = normalise_option($id, $filename, $found);
551         err($id, "Malformed option [2] in SYNOPSIS: $found")
552             if defined $option_uw && $option_uw eq '';
553     }
554
555     # In OPTIONS, we look for =item paragraphs.
556     # (?=^\s*$) detects an empty line.
557     while ( $options =~ /=item\s+(.*?)(?=^\s*$)/msg ) {
558         my $item = $&;
559
560         while ( $item =~ /(\[\s*)?($markup_re)/msg ) {
561             my $found = $2;
562             print STDERR "$id:DEBUG[option_check] OPTIONS: found $&\n"
563                 if $debug;
564             err($id, "Unexpected bracket in OPTIONS =item: $item")
565                 if ($1 // '') ne '' && $found =~ /^B<\s*-/;
566
567             my $option_uw = normalise_option($id, $filename, $found);
568             err($id, "Malformed option in OPTIONS: $found")
569                 if defined $option_uw && $option_uw eq '';
570         }
571     }
572 }
573
574 # Normal symbol form
575 my $symbol_re = qr/[[:alpha:]_][_[:alnum:]]*?/;
576
577 # Checks of function name (man3) formatting.  The man3 checks are
578 # easier than the man1 checks, we only check the names followed by (),
579 # and only the names that have POD markup.
580 sub functionname_check {
581     my $id = shift;
582     my $filename = shift;
583     my $contents = shift;
584
585     while ( $contents =~ /($markup_re)\(\)/msg ) {
586         print STDERR "$id:DEBUG[functionname_check] SYNOPSIS: found $&\n"
587             if $debug;
588
589         my $symbol = $1;
590         my $unmarked = $symbol;
591         $unmarked =~ s/[BIL]<|>//msg;
592
593         err($id, "Malformed symbol: $symbol")
594             unless $symbol =~ /^B<.*?>$/ && $unmarked =~ /^${symbol_re}$/
595     }
596
597     # We can't do the kind of collecting coolness that option_check()
598     # does, because there are too many things that can't be found in
599     # name repositories like the NAME sections, such as symbol names
600     # with a variable part (typically marked up as B<foo_I<TYPE>_bar>
601 }
602
603 # This is from http://man7.org/linux/man-pages/man7/man-pages.7.html
604 my %preferred_words = (
605     '16bit'         => '16-bit',
606     'a.k.a.'        => 'aka',
607     'bitmask'       => 'bit mask',
608     'builtin'       => 'built-in',
609    #'epoch'         => 'Epoch', # handled specially, below
610     'fall-back'     => 'fallback',
611     'file name'     => 'filename',
612     'file system'   => 'filesystem',
613     'host name'     => 'hostname',
614     'i-node'        => 'inode',
615     'lower case'    => 'lowercase',
616     'lower-case'    => 'lowercase',
617     'manpage'       => 'man page',
618     'non-blocking'  => 'nonblocking',
619     'non-default'   => 'nondefault',
620     'non-empty'     => 'nonempty',
621     'non-negative'  => 'nonnegative',
622     'non-zero'      => 'nonzero',
623     'path name'     => 'pathname',
624     'pre-allocated' => 'preallocated',
625     'pseudo-terminal' => 'pseudoterminal',
626     'real time'     => 'real-time',
627     'realtime'      => 'real-time',
628     'reserved port' => 'privileged port',
629     'runtime'       => 'run time',
630     'saved group ID'=> 'saved set-group-ID',
631     'saved set-GID' => 'saved set-group-ID',
632     'saved set-UID' => 'saved set-user-ID',
633     'saved user ID' => 'saved set-user-ID',
634     'set-GID'       => 'set-group-ID',
635     'set-UID'       => 'set-user-ID',
636     'setgid'        => 'set-group-ID',
637     'setuid'        => 'set-user-ID',
638     'sub-system'    => 'subsystem',
639     'super block'   => 'superblock',
640     'super-block'   => 'superblock',
641     'super user'    => 'superuser',
642     'super-user'    => 'superuser',
643     'system port'   => 'privileged port',
644     'time stamp'    => 'timestamp',
645     'time zone'     => 'timezone',
646     'upper case'    => 'uppercase',
647     'upper-case'    => 'uppercase',
648     'useable'       => 'usable',
649     'user name'     => 'username',
650     'userspace'     => 'user space',
651     'zeroes'        => 'zeros'
652 );
653
654 # Search manpage for words that have a different preferred use.
655 sub wording {
656     my $id = shift;
657     my $contents = shift;
658
659     foreach my $k ( keys %preferred_words ) {
660         # Sigh, trademark
661         next if $k eq 'file system'
662             and $contents =~ /Microsoft Encrypted File System/;
663         err($id, "Found '$k' should use '$preferred_words{$k}'")
664             if $contents =~ /\b\Q$k\E\b/i;
665     }
666     err($id, "Found 'epoch' should use 'Epoch'")
667         if $contents =~ /\bepoch\b/;
668     if ( $id =~ m@man1/@ ) {
669         err($id, "found 'tool' in NAME, should use 'command'")
670             if $contents =~ /=head1 NAME.*\btool\b.*=head1 SYNOPSIS/s;
671         err($id, "found 'utility' in NAME, should use 'command'")
672             if $contents =~ /NAME.*\butility\b.*=head1 SYNOPSIS/s;
673
674     }
675 }
676
677 # Perform all sorts of nit/error checks on a manpage
678 sub check {
679     my %podinfo = @_;
680     my $filename = $podinfo{filename};
681     my $dirname = basename(dirname($filename));
682     my $contents = $podinfo{contents};
683
684     my $id = "${filename}:1:";
685     check_head_style($id, $contents);
686
687     # Check ordering of some sections in man3
688     if ( $filename =~ m|man3/| ) {
689         check_section_location($id, $contents, "RETURN VALUES", "EXAMPLES");
690         check_section_location($id, $contents, "SEE ALSO", "HISTORY");
691         check_section_location($id, $contents, "EXAMPLES", "SEE ALSO");
692     }
693
694     # Make sure every link has a section.
695     while ( $contents =~ /$markup_re/msg ) {
696         my $target = $1;
697         next unless $target =~ /^L<(.*)>$/;     # Skip if not L<...>
698         $target = $1;                           # Peal away L< and >
699         $target =~ s/\/[^\/]*$//;               # Peal away possible anchor
700         $target =~ s/.*\|//g;                   # Peal away possible link text
701         next if $target eq '';                  # Skip if links within page, or
702         next if $target =~ /::/;                #   links to a Perl module, or
703         next if $target =~ /^https?:/;          #   is a URL link, or
704         next if $target =~ /\([1357]\)$/;       #   it has a section
705         err($id, "Section missing in $target")
706     }
707     # Check for proper links to commands.
708     while ( $contents =~ /L<([^>]*)\(1\)(?:\/.*)?>/g ) {
709         my $target = $1;
710         next if $target =~ /openssl-?/;
711         next if ( grep { basename($_) eq "$target.pod" }
712                   files(TAGS => [ 'manual', 'man1' ]) );
713         # TODO: Filter out "foreign manual" links.
714         next if $target =~ /ps|apropos|sha1sum|procmail|perl/;
715         err($id, "Bad command link L<$target(1)>");
716     }
717     # Check for proper in-man-3 API links.
718     while ( $contents =~ /L<([^>]*)\(3\)(?:\/.*)?>/g ) {
719         my $target = $1;
720         err($id, "Bad L<$target>")
721             unless $target =~ /^[_[:alpha:]][_[:alnum:]]*$/
722     }
723
724     unless ( $contents =~ /^=for openssl generic/ms ) {
725         if ( $filename =~ m|man3/| ) {
726             name_synopsis($id, $filename, $contents);
727             functionname_check($id, $filename, $contents);
728         } elsif ( $filename =~ m|man1/| ) {
729             option_check($id, $filename, $contents)
730         }
731     }
732
733     wording($id, $contents);
734
735     err($id, "Doesn't start with =pod")
736         if $contents !~ /^=pod/;
737     err($id, "Doesn't end with =cut")
738         if $contents !~ /=cut\n$/;
739     err($id, "More than one cut line.")
740         if $contents =~ /=cut.*=cut/ms;
741     err($id, "EXAMPLE not EXAMPLES section.")
742         if $contents =~ /=head1 EXAMPLE[^S]/;
743     err($id, "WARNING not WARNINGS section.")
744         if $contents =~ /=head1 WARNING[^S]/;
745     err($id, "Missing copyright")
746         if $contents !~ /Copyright .* The OpenSSL Project Authors/;
747     err($id, "Copyright not last")
748         if $contents =~ /head1 COPYRIGHT.*=head/ms;
749     err($id, "head2 in All uppercase")
750         if $contents =~ /head2\s+[A-Z ]+\n/;
751     err($id, "Extra space after head")
752         if $contents =~ /=head\d\s\s+/;
753     err($id, "Period in NAME section")
754         if $contents =~ /=head1 NAME.*\.\n.*=head1 SYNOPSIS/ms;
755     err($id, "Duplicate $1 in L<>")
756         if $contents =~ /L<([^>]*)\|([^>]*)>/ && $1 eq $2;
757     err($id, "Bad =over $1")
758         if $contents =~ /=over([^ ][^24])/;
759     err($id, "Possible version style issue")
760         if $contents =~ /OpenSSL version [019]/;
761
762     if ( $contents !~ /=for openssl multiple includes/ ) {
763         # Look for multiple consecutive openssl #include lines
764         # (non-consecutive lines are okay; see man3/MD5.pod).
765         if ( $contents =~ /=head1 SYNOPSIS(.*)=head1 DESCRIPTION/ms ) {
766             my $count = 0;
767             foreach my $line ( split /\n+/, $1 ) {
768                 if ( $line =~ m@include <openssl/@ ) {
769                     err($id, "Has multiple includes")
770                         if ++$count == 2;
771                 } else {
772                     $count = 0;
773                 }
774             }
775         }
776     }
777
778     open my $OUT, '>', $temp
779         or die "Can't open $temp, $!";
780     err($id, "POD errors")
781         if podchecker($filename, $OUT) != 0;
782     close $OUT;
783     open $OUT, '<', $temp
784         or die "Can't read $temp, $!";
785     while ( <$OUT> ) {
786         next if /\(section\) in.*deprecated/;
787         print;
788     }
789     close $OUT;
790     unlink $temp || warn "Can't remove $temp, $!";
791
792     # Find what section this page is in; assume 3.
793     my $section = 3;
794     $section = $1 if $dirname =~ /man([1-9])/;
795
796     foreach ( (@{$mandatory_sections{'*'}}, @{$mandatory_sections{$section}}) ) {
797         err($id, "Missing $_ head1 section")
798             if $contents !~ /^=head1\s+${_}\s*$/m;
799     }
800 }
801
802 # Information database ###############################################
803
804 # Map of links in each POD file; filename => [ "foo(1)", "bar(3)", ... ]
805 my %link_map = ();
806 # Map of names in each POD file or from "missing" files; possible values are:
807 # If found in a POD files, "name(s)" => filename
808 # If found in a "missing" file or external, "name(s)" => ''
809 my %name_map = ();
810
811 # State of man-page names.
812 # %state is affected by loading util/*.num and util/*.syms
813 # Values may be one of:
814 # 'crypto' : belongs in libcrypto (loaded from libcrypto.num)
815 # 'ssl' : belongs in libssl (loaded from libssl.num)
816 # 'other' : belongs in libcrypto or libssl (loaded from other.syms)
817 # 'internal' : Internal
818 # 'public' : Public (generic name or external documentation)
819 # Any of these values except 'public' may be prefixed with 'missing_'
820 # to indicate that they are known to be missing.
821 my %state;
822 # %missing is affected by loading util/missing*.txt.  Values may be one of:
823 # 'crypto' : belongs in libcrypto (loaded from libcrypto.num)
824 # 'ssl' : belongs in libssl (loaded from libssl.num)
825 # 'other' : belongs in libcrypto or libssl (loaded from other.syms)
826 # 'internal' : Internal
827 my %missing;
828
829 # Parse libcrypto.num, etc., and return sorted list of what's there.
830 sub loadnum ($;$) {
831     my $file = shift;
832     my $type = shift;
833     my @symbols;
834
835     open my $IN, '<', catfile($config{sourcedir}, $file)
836         or die "Can't open $file, $!, stopped";
837
838     while ( <$IN> ) {
839         next if /^#/;
840         next if /\bNOEXIST\b/;
841         my @fields = split();
842         die "Malformed line $. in $file: $_"
843             if scalar @fields != 2 && scalar @fields != 4;
844         $state{$fields[0].'(3)'} = $type // 'internal';
845     }
846     close $IN;
847 }
848
849 # Load file of symbol names that we know aren't documented.
850 sub loadmissing($;$)
851 {
852     my $missingfile = shift;
853     my $type = shift;
854
855     open FH, catfile($config{sourcedir}, $missingfile)
856         or die "Can't open $missingfile";
857     while ( <FH> ) {
858         chomp;
859         next if /^#/;
860         $missing{$_} = $type // 'internal';
861     }
862     close FH;
863 }
864
865 # Check that we have consistent public / internal documentation and declaration
866 sub checkstate () {
867     # Collect all known names, no matter where they come from
868     my %names = map { $_ => 1 } (keys %name_map, keys %state, keys %missing);
869
870     # Check section 3, i.e. functions and macros
871     foreach ( grep { $_ =~ /\(3\)$/ } sort keys %names ) {
872         next if ( $name_map{$_} // '') eq '' || $_ =~ /$ignored/;
873
874         # If a man-page isn't recorded public or if it's recorded missing
875         # and internal, it's declared to be internal.
876         my $declared_internal =
877             ($state{$_} // 'internal') eq 'internal'
878             || ($missing{$_} // '') eq 'internal';
879         # If a man-page isn't recorded internal or if it's recorded missing
880         # and not internal, it's declared to be public
881         my $declared_public =
882             ($state{$_} // 'internal') ne 'internal'
883             || ($missing{$_} // 'internal') ne 'internal';
884
885         err("$_ is supposedly public but is documented as internal")
886             if ( $declared_public && $name_map{$_} =~ /\/internal\// );
887         err("$_ is supposedly internal (maybe missing from other.syms) but is documented as public")
888             if ( $declared_internal && $name_map{$_} !~ /\/internal\// );
889     }
890 }
891
892 # Check for undocumented macros; ignore those in the "missing" file
893 # and do simple check for #define in our header files.
894 sub checkmacros {
895     my $count = 0;
896     my %seen;
897
898     foreach my $f ( files(TAGS => 'public_header') ) {
899         # Skip some internals we don't want to document yet.
900         my $b = basename($f);
901         next if $b eq 'asn1.h';
902         next if $b eq 'asn1t.h';
903         next if $b eq 'err.h';
904         open(IN, $f)
905             or die "Can't open $f, $!";
906         while ( <IN> ) {
907             next unless /^#\s*define\s*(\S+)\(/;
908             my $macro = "$1(3)"; # We know they're all in section 3
909             next if defined $name_map{$macro}
910                 || defined $missing{$macro}
911                 || defined $seen{$macro}
912                 || $macro =~ /$ignored/;
913
914             err("$f:", "macro $macro undocumented")
915                 if $opt_d || $opt_e;
916             $count++;
917             $seen{$macro} = 1;
918         }
919         close(IN);
920     }
921     err("# $count macros undocumented (count is approximate)")
922         if $count > 0;
923 }
924
925 # Find out what is undocumented (filtering out the known missing ones)
926 # and display them.
927 sub printem ($) {
928     my $type = shift;
929     my $count = 0;
930
931     foreach my $func ( grep { $state{$_} eq $type } sort keys %state ) {
932         next if defined $name_map{$func}
933             || defined $missing{$func};
934
935         err("$type:", "function $func undocumented")
936             if $opt_d || $opt_e;
937         $count++;
938     }
939     err("# $count lib$type names are not documented")
940         if $count > 0;
941 }
942
943 # Collect all the names in a manpage.
944 sub collectnames {
945     my %podinfo = @_;
946     my $filename = $podinfo{filename};
947     $filename =~ m|man(\d)/|;
948     my $section = $1;
949     my $simplename = basename($filename, ".pod");
950     my $id = "${filename}:1:";
951     my $is_generic = $podinfo{contents} =~ /^=for openssl generic/ms;
952
953     unless ( grep { $simplename eq $_ } @{$podinfo{names}} ) {
954         err($id, "$simplename not in NAME section");
955         push @{$podinfo{names}}, $simplename;
956     }
957     foreach my $name ( @{$podinfo{names}} ) {
958         next if $name eq "";
959         err($id, "'$name' contains whitespace")
960             if $name =~ /\s/;
961         my $name_sec = "$name($section)";
962         if ( !defined $name_map{$name_sec} ) {
963             $name_map{$name_sec} = $filename;
964             $state{$name_sec} //=
965                 ( $filename =~ /\/internal\// ? 'internal' : 'public' )
966                 if $is_generic;
967         } elsif ( $filename eq $name_map{$name_sec} ) {
968             err($id, "$name_sec duplicated in NAME section of",
969                  $name_map{$name_sec});
970         } elsif ( $name_map{$name_sec} ne '' ) {
971             err($id, "$name_sec also in NAME section of",
972                  $name_map{$name_sec});
973         }
974     }
975
976     if ( $podinfo{contents} =~ /=for openssl foreign manual (.*)\n/ ) {
977         foreach my $f ( split / /, $1 ) {
978             $name_map{$f} = ''; # It still exists!
979             $state{$f} = 'public'; # We assume!
980         }
981     }
982
983     my @links =
984         $podinfo{contents} =~ /L<
985                               # if the link is of the form L<something|name(s)>,
986                               # then remove 'something'.  Note that 'something'
987                               # may contain POD codes as well...
988                               (?:(?:[^\|]|<[^>]*>)*\|)?
989                               # we're only interested in references that have
990                               # a one digit section number
991                               ([^\/>\(]+\(\d\))
992                              /gx;
993     $link_map{$filename} = [ @links ];
994 }
995
996 # Look for L<> ("link") references that point to files that do not exist.
997 sub checklinks {
998     foreach my $filename ( sort keys %link_map ) {
999         foreach my $link ( @{$link_map{$filename}} ) {
1000             err("${filename}:1:", "reference to non-existing $link")
1001                 unless defined $name_map{$link} || defined $missing{$link};
1002             err("${filename}:1:", "reference of internal $link in public documentation $filename")
1003                 if ( ( ($state{$link} // '') eq 'internal'
1004                        || ($missing{$link} // '') eq 'internal' )
1005                      && $filename !~ /\/internal\// );
1006         }
1007     }
1008 }
1009
1010 # Cipher/digests to skip if they show up as "not implemented"
1011 # because they are, via the "-*" construct.
1012 my %skips = (
1013     'aes128' => 1,
1014     'aes192' => 1,
1015     'aes256' => 1,
1016     'aria128' => 1,
1017     'aria192' => 1,
1018     'aria256' => 1,
1019     'camellia128' => 1,
1020     'camellia192' => 1,
1021     'camellia256' => 1,
1022     'des' => 1,
1023     'des3' => 1,
1024     'idea' => 1,
1025     'cipher' => 1,
1026     'digest' => 1,
1027 );
1028
1029 my %genopts; # generic options parsed from apps/include/opt.h
1030
1031 # Check the flags of a command and see if everything is in the manpage
1032 sub checkflags {
1033     my $cmd = shift;
1034     my $doc = shift;
1035     my @cmdopts;
1036     my %docopts;
1037
1038     # Get the list of options in the command source file.
1039     my $active = 0;
1040     my $expect_helpstr = "";
1041     open CFH, "apps/$cmd.c"
1042         or die "Can't open apps/$cmd.c to list options for $cmd, $!";
1043     while ( <CFH> ) {
1044         chop;
1045         if ($active) {
1046             last if m/^\s*};/;
1047             if ($expect_helpstr ne "") {
1048                 next if m/^\s*#\s*if/;
1049                 err("$cmd does not implement help for -$expect_helpstr") unless m/^\s*"/;
1050                 $expect_helpstr = "";
1051             }
1052             if (m/\{\s*"([^"]+)"\s*,\s*OPT_[A-Z0-9_]+\s*,\s*('[-\/:<>cEfFlMnNpsuU]'|0)\s*,(.*)$/
1053                        && !($cmd eq "s_client" && $1 eq "wdebug")) {
1054                 push @cmdopts, $1;
1055                 $expect_helpstr = $1;
1056                 $expect_helpstr = "" if $3 =~ m/^\s*"/;
1057             } elsif (m/[\s,](OPT_[A-Z]+_OPTIONS?)\s*(,|$)/) {
1058                 push @cmdopts, @{ $genopts{$1} };
1059             }
1060         } elsif (m/^const\s+OPTIONS\s*/) {
1061             $active = 1;
1062         }
1063     }
1064     close CFH;
1065
1066     # Get the list of flags from the synopsis
1067     open CFH, "<$doc"
1068         or die "Can't open $doc, $!";
1069     while ( <CFH> ) {
1070         chop;
1071         last if /DESCRIPTION/;
1072         my $opt;
1073         if ( /\[B<-([^ >]+)/ ) {
1074             $opt = $1;
1075         } elsif ( /^B<-([^ >]+)/ ) {
1076             $opt = $1;
1077         } else {
1078             next;
1079         }
1080         $opt = $1 if $opt =~ /I<(.*)/;
1081         $docopts{$1} = 1;
1082     }
1083     close CFH;
1084
1085     # See what's in the command not the manpage.
1086     my @undocced = sort grep { !defined $docopts{$_} } @cmdopts;
1087     foreach ( @undocced ) {
1088         err("$doc: undocumented $cmd option -$_");
1089     }
1090
1091     # See what's in the command not the manpage.
1092     my @unimpl = sort grep { my $e = $_; !(grep /^\Q$e\E$/, @cmdopts) } keys %docopts;
1093     foreach ( @unimpl ) {
1094         next if $_ eq "-"; # Skip the -- end-of-flags marker
1095         next if defined $skips{$_};
1096         err("$doc: $cmd does not implement -$_");
1097     }
1098 }
1099
1100 ##
1101 ##  MAIN()
1102 ##  Do the work requested by the various getopt flags.
1103 ##  The flags are parsed in alphabetical order, just because we have
1104 ##  to have *some way* of listing them.
1105 ##
1106
1107 if ( $opt_c ) {
1108     my @commands = ();
1109
1110     # Get the lists of generic options.
1111     my $active = "";
1112     open OFH, "apps/include/opt.h"
1113         or die "Can't open apps/include/opt.h to list generic options, $!";
1114     while ( <OFH> ) {
1115         chop;
1116         push @{ $genopts{$active} }, $1 if $active ne "" && m/^\s+\{\s*"([^"]+)"\s*,\s*OPT_/;
1117         $active = $1 if m/^\s*#\s*define\s+(OPT_[A-Z]+_OPTIONS?)\s*\\\s*$/;
1118         $active = "" if m/^\s*$/;
1119     }
1120     close OFH;
1121
1122     # Get list of commands.
1123     opendir(DIR, "apps");
1124     @commands = grep(/\.c$/, readdir(DIR));
1125     closedir(DIR);
1126
1127     # See if each has a manpage.
1128     foreach my $cmd ( @commands ) {
1129         $cmd =~ s/\.c$//;
1130         next if $cmd eq 'progs' || $cmd eq 'vms_decc_init';
1131         my @doc = ( grep { basename($_) eq "openssl-$cmd.pod"
1132                            # For "tsget" and "CA.pl" pod pages
1133                            || basename($_) eq "$cmd.pod" }
1134                     files(TAGS => [ 'manual', 'man1' ]) );
1135         my $num = scalar @doc;
1136         if ($num > 1) {
1137             err("$num manuals for 'openssl $cmd': ".join(", ", @doc));
1138         } elsif ($num < 1) {
1139             err("no manual for 'openssl $cmd'");
1140         } else {
1141             checkflags($cmd, @doc);
1142         }
1143     }
1144 }
1145
1146 # Populate %state
1147 loadnum('util/libcrypto.num', 'crypto');
1148 loadnum('util/libssl.num', 'ssl');
1149 loadnum('util/other.syms', 'other');
1150 loadnum('util/other-internal.syms');
1151 if ( $opt_o ) {
1152     loadmissing('util/missingmacro111.txt', 'crypto');
1153     loadmissing('util/missingcrypto111.txt', 'crypto');
1154     loadmissing('util/missingssl111.txt', 'ssl');
1155 } elsif ( !$opt_u ) {
1156     loadmissing('util/missingmacro.txt', 'crypto');
1157     loadmissing('util/missingcrypto.txt', 'crypto');
1158     loadmissing('util/missingssl.txt', 'ssl');
1159     loadmissing('util/missingcrypto-internal.txt');
1160     loadmissing('util/missingssl-internal.txt');
1161 }
1162
1163 if ( $opt_n || $opt_l || $opt_u || $opt_v ) {
1164     my @files_to_read = ( $opt_n && @ARGV ) ? @ARGV : files(TAGS => 'manual');
1165
1166     foreach (@files_to_read) {
1167         my %podinfo = extract_pod_info($_, { debug => $debug });
1168
1169         collectnames(%podinfo)
1170             if ( $opt_l || $opt_u || $opt_v );
1171
1172         check(%podinfo)
1173             if ( $opt_n );
1174     }
1175 }
1176
1177 if ( $opt_l ) {
1178     checklinks();
1179 }
1180
1181 if ( $opt_n ) {
1182     # If not given args, check that all man1 commands are named properly.
1183     if ( scalar @ARGV == 0 ) {
1184         foreach ( files(TAGS => [ 'public_manual', 'man1' ]) ) {
1185             next if /openssl\.pod/
1186                 || /CA\.pl/ || /tsget\.pod/; # these commands are special cases
1187             err("$_ doesn't start with openssl-") unless /openssl-/;
1188         }
1189     }
1190 }
1191
1192 checkstate();
1193
1194 if ( $opt_u || $opt_v) {
1195     printem('crypto');
1196     printem('ssl');
1197     checkmacros();
1198 }
1199
1200 exit $status;