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