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