]> git.ipfire.org Git - thirdparty/openssl.git/blob - util/find-doc-nits
util/find-doc-nits: Add a regexp for C symbols and use it
[thirdparty/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 | ^sk_
102 | ^SKM_DEFINE_STACK_OF_INTERNAL
103 | ^lh_
104 | ^DEFINE_LHASH_OF_INTERNAL
105 )/x;
106
107 # A common regexp for C symbol names
108 my $C_symbol = qr/\b[[:alpha:]][_[:alnum:]]*\b/;
109
110 # Collect all POD files, both internal and public, and regardless of location
111 # We collect them in a hash table with each file being a key, so we can attach
112 # tags to them. For example, internal docs will have the word "internal"
113 # attached to them.
114 my %files = ();
115 # We collect files names on the fly, on known tag basis
116 my %collected_tags = ();
117 # We cache results based on tags
118 my %collected_results = ();
119
120 # files OPTIONS
121 #
122 # Example:
123 #
124 # files(TAGS => 'manual');
125 # files(TAGS => [ 'manual', 'man1' ]);
126 #
127 # This function returns an array of files corresponding to a set of tags
128 # given with the options "TAGS". The value of this option can be a single
129 # word, or an array of several words, which work as inclusive or exclusive
130 # selectors. Inclusive selectors are used to add one more set of files to
131 # the returned array, while exclusive selectors limit the set of files added
132 # to the array. The recognised tag values are:
133 #
134 # 'public_manual' - inclusive selector, adds public manuals to the
135 # returned array of files.
136 # 'internal_manual' - inclusive selector, adds internal manuals to the
137 # returned array of files.
138 # 'manual' - inclusive selector, adds any manual to the returned
139 # array of files. This is really a shorthand for
140 # 'public_manual' and 'internal_manual' combined.
141 # 'public_header' - inclusive selector, adds public headers to the
142 # returned array of files.
143 # 'header' - inclusive selector, adds any header file to the
144 # returned array of files. Since we currently only
145 # care about public headers, this is exactly
146 # equivalent to 'public_header', but is present for
147 # consistency.
148 #
149 # 'man1', 'man3', 'man5', 'man7'
150 # - exclusive selectors, only applicable together with
151 # any of the manual selectors. If any of these are
152 # present, only the manuals from the given sections
153 # will be include. If none of these are present,
154 # the manuals from all sections will be returned.
155 #
156 # All returned manual files come from configdata.pm.
157 # All returned header files come from looking inside
158 # "$config{sourcedir}/include/openssl"
159 #
160 sub files {
161 my %opts = ( @_ ); # Make a copy of the arguments
162
163 $opts{TAGS} = [ $opts{TAGS} ] if ref($opts{TAGS}) eq '';
164
165 croak "No tags given, or not an array"
166 unless exists $opts{TAGS} && ref($opts{TAGS}) eq 'ARRAY';
167
168 my %tags = map { $_ => 1 } @{$opts{TAGS}};
169 $tags{public_manual} = 1
170 if $tags{manual} && ($tags{public} // !$tags{internal});
171 $tags{internal_manual} = 1
172 if $tags{manual} && ($tags{internal} // !$tags{public});
173 $tags{public_header} = 1
174 if $tags{header} && ($tags{public} // !$tags{internal});
175 delete $tags{manual};
176 delete $tags{header};
177 delete $tags{public};
178 delete $tags{internal};
179
180 my $tags_as_key = join(':', sort keys %tags);
181
182 cluck "DEBUG[files]: This is how we got here!" if $debug;
183 print STDERR "DEBUG[files]: tags: $tags_as_key\n" if $debug;
184
185 my %tags_to_collect = ( map { $_ => 1 }
186 grep { !exists $collected_tags{$_} }
187 keys %tags );
188
189 if ($tags_to_collect{public_manual}) {
190 print STDERR "DEBUG[files]: collecting public manuals\n"
191 if $debug;
192
193 # The structure in configdata.pm is that $unified_info{mandocs}
194 # contains lists of man files, and in turn, $unified_info{depends}
195 # contains hash tables showing which POD file each of those man
196 # files depend on. We use that information to find the POD files,
197 # and to attach the man section they belong to as tags
198 foreach my $mansect ( @sections ) {
199 foreach ( map { @{$unified_info{depends}->{$_}} }
200 @{$unified_info{mandocs}->{$mansect}} ) {
201 $files{$_} = { $mansect => 1, public_manual => 1 };
202 }
203 }
204 $collected_tags{public_manual} = 1;
205 }
206
207 if ($tags_to_collect{internal_manual}) {
208 print STDERR "DEBUG[files]: collecting internal manuals\n"
209 if $debug;
210
211 # We don't have the internal docs in configdata.pm. However, they
212 # are all in the source tree, so they're easy to find.
213 foreach my $mansect ( @sections ) {
214 foreach ( glob(catfile($config{sourcedir},
215 'doc', 'internal', $mansect, '*.pod')) ) {
216 $files{$_} = { $mansect => 1, internal_manual => 1 };
217 }
218 }
219 $collected_tags{internal_manual} = 1;
220 }
221
222 if ($tags_to_collect{public_header}) {
223 print STDERR "DEBUG[files]: collecting public headers\n"
224 if $debug;
225
226 foreach ( glob(catfile($config{sourcedir},
227 'include', 'openssl', '*.h')) ) {
228 $files{$_} = { public_header => 1 };
229 }
230 }
231
232 my @result = @{$collected_results{$tags_as_key} // []};
233
234 if (!@result) {
235 # Produce a result based on caller tags
236 foreach my $type ( ( 'public_manual', 'internal_manual' ) ) {
237 next unless $tags{$type};
238
239 # If caller asked for specific sections, we care about sections.
240 # Otherwise, we give back all of them.
241 my @selected_sections =
242 grep { $tags{$_} } @sections;
243 @selected_sections = @sections unless @selected_sections;
244
245 foreach my $section ( ( @selected_sections ) ) {
246 push @result,
247 ( sort { basename($a) cmp basename($b) }
248 grep { $files{$_}->{$type} && $files{$_}->{$section} }
249 keys %files );
250 }
251 }
252 if ($tags{public_header}) {
253 push @result,
254 ( sort { basename($a) cmp basename($b) }
255 grep { $files{$_}->{public_header} }
256 keys %files );
257 }
258
259 if ($debug) {
260 print STDERR "DEBUG[files]: result:\n";
261 print STDERR "DEBUG[files]: $_\n" foreach @result;
262 }
263 $collected_results{$tags_as_key} = [ @result ];
264 }
265
266 return @result;
267 }
268
269 # Print error message, set $status.
270 sub err {
271 print join(" ", @_), "\n";
272 $status = 1
273 }
274
275 # Cross-check functions in the NAME and SYNOPSIS section.
276 sub name_synopsis {
277 my $id = shift;
278 my $filename = shift;
279 my $contents = shift;
280
281 # Get NAME section and all words in it.
282 return unless $contents =~ /=head1 NAME(.*)=head1 SYNOPSIS/ms;
283 my $tmp = $1;
284 $tmp =~ tr/\n/ /;
285 err($id, "Trailing comma before - in NAME")
286 if $tmp =~ /, *-/;
287 $tmp =~ s/ -.*//g;
288 err($id, "POD markup among the names in NAME")
289 if $tmp =~ /[<>]/;
290 $tmp =~ s/ */ /g;
291 err($id, "Missing comma in NAME")
292 if $tmp =~ /[^,] /;
293
294 my $dirname = dirname($filename);
295 my $section = basename($dirname);
296 my $simplename = basename($filename, ".pod");
297 my $foundfilename = 0;
298 my %foundfilenames = ();
299 my %names;
300 foreach my $n ( split ',', $tmp ) {
301 $n =~ s/^\s+//;
302 $n =~ s/\s+$//;
303 err($id, "The name '$n' contains white-space")
304 if $n =~ /\s/;
305 $names{$n} = 1;
306 $foundfilename++ if $n eq $simplename;
307 $foundfilenames{$n} = 1
308 if ( ( grep { basename($_) eq "$n.pod" }
309 files(TAGS => [ 'manual', $section ]) )
310 && $n ne $simplename );
311 }
312 err($id, "The following exist as other .pod files:",
313 sort keys %foundfilenames)
314 if %foundfilenames;
315 err($id, "$simplename (filename) missing from NAME section")
316 unless $foundfilename;
317
318 # Find all functions in SYNOPSIS
319 return unless $contents =~ /=head1 SYNOPSIS(.*)=head1 DESCRIPTION/ms;
320 my $syn = $1;
321 my $ignore_until = undef; # If defined, this is a regexp
322 # Remove all non-code lines
323 $syn =~ s/^(?:\s*?|\S.*?)$//msg;
324 # Remove all comments
325 $syn =~ s/\/\*.*?\*\///msg;
326 while ( $syn ) {
327 # "env" lines end at a newline.
328 # Preprocessor lines start with a # and end at a newline.
329 # Other lines end with a semicolon, and may cover more than
330 # one physical line.
331 if ( $syn !~ /^ \s*(env .*?|#.*?|.*?;)\s*$/ms ) {
332 err($id, "Can't parse rest of synopsis:\n$syn\n(declarations not ending with a semicolon (;)?)");
333 last;
334 }
335 my $line = $1;
336 $syn = $';
337
338 print STDERR "DEBUG[name_synopsis] \$line = '$line'\n" if $debug;
339
340 # Special code to skip over documented structures
341 if ( defined $ignore_until) {
342 next if $line !~ /$ignore_until/;
343 $ignore_until = undef;
344 next;
345 }
346 if ( $line =~ /^\s*(?:typedef\s+)?struct(?:\s+\S+)\s*\{/ ) {
347 $ignore_until = qr/\}.*?;/;
348 next;
349 }
350
351 my $sym;
352 my $is_prototype = 1;
353 $line =~ s/STACK_OF\([^)]+\)/int/g;
354 $line =~ s/SPARSE_ARRAY_OF\([^)]+\)/int/g;
355 $line =~ s/__declspec\([^)]+\)//;
356
357 ## We don't prohibit that space, to allow typedefs looking like
358 ## this:
359 ##
360 ## typedef int (fantastically_long_name_breaks_80char_limit)
361 ## (fantastically_long_name_breaks_80char_limit *something);
362 ##
363 #if ( $line =~ /typedef.*\(\*?\S+\)\s+\(/ ) {
364 # # a callback function with whitespace before the argument list:
365 # # typedef ... (*NAME) (...
366 # # typedef ... (NAME) (...
367 # err($id, "Function typedef has space before arg list: $line");
368 #}
369
370 if ( $line =~ /env (\S*)=/ ) {
371 # environment variable env NAME=...
372 $sym = $1;
373 } elsif ( $line =~ /typedef.*\(\*?($C_symbol)\)\s*\(/ ) {
374 # a callback function pointer: typedef ... (*NAME)(...
375 # a callback function signature: typedef ... (NAME)(...
376 $sym = $1;
377 } elsif ( $line =~ /typedef.*($C_symbol)\s*\(/ ) {
378 # a callback function signature: typedef ... NAME(...
379 $sym = $1;
380 } elsif ( $line =~ /typedef.*($C_symbol);/ ) {
381 # a simple typedef: typedef ... NAME;
382 $is_prototype = 0;
383 $sym = $1;
384 } elsif ( $line =~ /enum ($C_symbol) \{/ ) {
385 # an enumeration: enum ... {
386 $sym = $1;
387 } elsif ( $line =~ /#\s*(?:define|undef) ($C_symbol)/ ) {
388 $is_prototype = 0;
389 $sym = $1;
390 } elsif ( $line =~ /^[^\(]*?\(\*($C_symbol)\s*\(/ ) {
391 # a function returning a function pointer: TYPE (*NAME(args))(args)
392 $sym = $1;
393 } elsif ( $line =~ /^[^\(]*?($C_symbol)\s*\(/ ) {
394 # a simple function declaration
395 $sym = $1;
396 }
397 else {
398 next;
399 }
400
401 print STDERR "DEBUG[name_synopsis] \$sym = '$sym'\n" if $debug;
402
403 err($id, "$sym missing from NAME section")
404 unless defined $names{$sym};
405 $names{$sym} = 2;
406
407 # Do some sanity checks on the prototype.
408 err($id, "Prototype missing spaces around commas: $line")
409 if $is_prototype && $line =~ /[a-z0-9],[^\s]/;
410 }
411
412 foreach my $n ( keys %names ) {
413 next if $names{$n} == 2;
414 err($id, "$n missing from SYNOPSIS")
415 }
416 }
417
418 # Check if SECTION ($3) is located before BEFORE ($4)
419 sub check_section_location {
420 my $id = shift;
421 my $contents = shift;
422 my $section = shift;
423 my $before = shift;
424
425 return unless $contents =~ /=head1 $section/
426 and $contents =~ /=head1 $before/;
427 err($id, "$section should appear before $before section")
428 if $contents =~ /=head1 $before.*=head1 $section/ms;
429 }
430
431 # Check if a =head1 is duplicated, or a =headX is duplicated within a
432 # =head1. Treats =head2 =head3 as equivalent -- it doesn't reset the head3
433 # sets if it finds a =head2 -- but that is good enough for now. Also check
434 # for proper capitalization, trailing periods, etc.
435 sub check_head_style {
436 my $id = shift;
437 my $contents = shift;
438 my %head1;
439 my %subheads;
440
441 foreach my $line ( split /\n+/, $contents ) {
442 next unless $line =~ /^=head/;
443 if ( $line =~ /head1/ ) {
444 err($id, "Duplicate section $line")
445 if defined $head1{$line};
446 $head1{$line} = 1;
447 %subheads = ();
448 } else {
449 err($id, "Duplicate subsection $line")
450 if defined $subheads{$line};
451 $subheads{$line} = 1;
452 }
453 err($id, "Period in =head")
454 if $line =~ /\.[^\w]/ or $line =~ /\.$/;
455 err($id, "not all uppercase in =head1")
456 if $line =~ /head1.*[a-z]/;
457 err($id, "All uppercase in subhead")
458 if $line =~ /head[234][ A-Z0-9]+$/;
459 }
460 }
461
462 # Because we have options and symbols with extra markup, we need
463 # to take that into account, so we need a regexp that extracts
464 # markup chunks, including recursive markup.
465 # please read up on /(?R)/ in perlre(1)
466 # (note: order is important, (?R) needs to come before .)
467 # (note: non-greedy is important, or something like 'B<foo> and B<bar>'
468 # will be captured as one item)
469 my $markup_re =
470 qr/( # Capture group
471 [BIL]< # The start of what we recurse on
472 (?:(?-1)|.)*? # recurse the whole regexp (referring to
473 # the last opened capture group, i.e. the
474 # start of this regexp), or pick next
475 # character. Do NOT be greedy!
476 > # The end of what we recurse on
477 )/x; # (the x allows this sort of split up regexp)
478
479 # Options must start with a dash, followed by a letter, possibly
480 # followed by letters, digits, dashes and underscores, and the last
481 # character must be a letter or a digit.
482 # We do also accept the single -? or -n, where n is a digit
483 my $option_re =
484 qr/(?:
485 \? # Single question mark
486 |
487 \d # Single digit
488 |
489 - # Single dash (--)
490 |
491 [[:alpha:]](?:[-_[:alnum:]]*?[[:alnum:]])?
492 )/x;
493
494 # Helper function to check if a given $thing is properly marked up
495 # option. It returns one of these values:
496 # undef if it's not an option
497 # "" if it's a malformed option
498 # $unwrapped the option with the outermost B<> wrapping removed.
499 sub normalise_option {
500 my $id = shift;
501 my $filename = shift;
502 my $thing = shift;
503
504 my $unwrapped = $thing;
505 my $unmarked = $thing;
506
507 # $unwrapped is the option with the outer B<> markup removed
508 $unwrapped =~ s/^B<//;
509 $unwrapped =~ s/>$//;
510 # $unmarked is the option with *all* markup removed
511 $unmarked =~ s/[BIL]<|>//msg;
512
513
514 # If we found an option, check it, collect it
515 if ( $unwrapped =~ /^\s*-/ ) {
516 return $unwrapped # return option with outer B<> removed
517 if $unmarked =~ /^-${option_re}$/;
518 return ""; # Malformed option
519 }
520 return undef; # Something else
521 }
522
523 # Checks of command option (man1) formatting. The man1 checks are
524 # restricted to the SYNOPSIS and OPTIONS sections, the rest is too
525 # free form, we simply cannot be too strict there.
526
527 sub option_check {
528 my $id = shift;
529 my $filename = shift;
530 my $contents = shift;
531
532 my $synopsis = ($contents =~ /=head1\s+SYNOPSIS(.*?)=head1/s, $1);
533
534 # Some pages have more than one OPTIONS section, let's make sure
535 # to get them all
536 my $options = '';
537 while ( $contents =~ /=head1\s+[A-Z ]*?OPTIONS$(.*?)(?==head1)/msg ) {
538 $options .= $1;
539 }
540
541 # Look for options with no or incorrect markup
542 while ( $synopsis =~
543 /(?<![-<[:alnum:]])-(?:$markup_re|.)*(?![->[:alnum:]])/msg ) {
544 err($id, "Malformed option [1] in SYNOPSIS: $&");
545 }
546
547 while ( $synopsis =~ /$markup_re/msg ) {
548 my $found = $&;
549 print STDERR "$id:DEBUG[option_check] SYNOPSIS: found $found\n"
550 if $debug;
551 my $option_uw = normalise_option($id, $filename, $found);
552 err($id, "Malformed option [2] in SYNOPSIS: $found")
553 if defined $option_uw && $option_uw eq '';
554 }
555
556 # In OPTIONS, we look for =item paragraphs.
557 # (?=^\s*$) detects an empty line.
558 while ( $options =~ /=item\s+(.*?)(?=^\s*$)/msg ) {
559 my $item = $&;
560
561 while ( $item =~ /(\[\s*)?($markup_re)/msg ) {
562 my $found = $2;
563 print STDERR "$id:DEBUG[option_check] OPTIONS: found $&\n"
564 if $debug;
565 err($id, "Unexpected bracket in OPTIONS =item: $item")
566 if ($1 // '') ne '' && $found =~ /^B<\s*-/;
567
568 my $option_uw = normalise_option($id, $filename, $found);
569 err($id, "Malformed option in OPTIONS: $found")
570 if defined $option_uw && $option_uw eq '';
571 }
572 }
573 }
574
575 # Normal symbol form
576 my $symbol_re = qr/[[:alpha:]_][_[:alnum:]]*?/;
577
578 # Checks of function name (man3) formatting. The man3 checks are
579 # easier than the man1 checks, we only check the names followed by (),
580 # and only the names that have POD markup.
581 sub functionname_check {
582 my $id = shift;
583 my $filename = shift;
584 my $contents = shift;
585
586 while ( $contents =~ /($markup_re)\(\)/msg ) {
587 print STDERR "$id:DEBUG[functionname_check] SYNOPSIS: found $&\n"
588 if $debug;
589
590 my $symbol = $1;
591 my $unmarked = $symbol;
592 $unmarked =~ s/[BIL]<|>//msg;
593
594 err($id, "Malformed symbol: $symbol")
595 unless $symbol =~ /^B<.*?>$/ && $unmarked =~ /^${symbol_re}$/
596 }
597
598 # We can't do the kind of collecting coolness that option_check()
599 # does, because there are too many things that can't be found in
600 # name repositories like the NAME sections, such as symbol names
601 # with a variable part (typically marked up as B<foo_I<TYPE>_bar>
602 }
603
604 # This is from http://man7.org/linux/man-pages/man7/man-pages.7.html
605 my %preferred_words = (
606 '16bit' => '16-bit',
607 'a.k.a.' => 'aka',
608 'bitmask' => 'bit mask',
609 'builtin' => 'built-in',
610 #'epoch' => 'Epoch', # handled specially, below
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 podchecker($filename, $OUT);
781 close $OUT;
782 open $OUT, '<', $temp
783 or die "Can't read $temp, $!";
784 while ( <$OUT> ) {
785 next if /\(section\) in.*deprecated/;
786 print;
787 }
788 close $OUT;
789 unlink $temp || warn "Can't remove $temp, $!";
790
791 # Find what section this page is in; assume 3.
792 my $section = 3;
793 $section = $1 if $dirname =~ /man([1-9])/;
794
795 foreach ( (@{$mandatory_sections{'*'}}, @{$mandatory_sections{$section}}) ) {
796 err($id, "Missing $_ head1 section")
797 if $contents !~ /^=head1\s+${_}\s*$/m;
798 }
799 }
800
801 # Information database ###############################################
802
803 # Map of links in each POD file; filename => [ "foo(1)", "bar(3)", ... ]
804 my %link_map = ();
805 # Map of names in each POD file or from "missing" files; possible values are:
806 # If found in a POD files, "name(s)" => filename
807 # If found in a "missing" file or external, "name(s)" => ''
808 my %name_map = ();
809
810 # State of man-page names.
811 # %state is affected by loading util/*.num and util/*.syms
812 # Values may be one of:
813 # 'crypto' : belongs in libcrypto (loaded from libcrypto.num)
814 # 'ssl' : belongs in libssl (loaded from libssl.num)
815 # 'other' : belongs in libcrypto or libssl (loaded from other.syms)
816 # 'internal' : Internal
817 # 'public' : Public (generic name or external documentation)
818 # Any of these values except 'public' may be prefixed with 'missing_'
819 # to indicate that they are known to be missing.
820 my %state;
821 # %missing is affected by loading util/missing*.txt. Values may be one of:
822 # 'crypto' : belongs in libcrypto (loaded from libcrypto.num)
823 # 'ssl' : belongs in libssl (loaded from libssl.num)
824 # 'other' : belongs in libcrypto or libssl (loaded from other.syms)
825 # 'internal' : Internal
826 my %missing;
827
828 # Parse libcrypto.num, etc., and return sorted list of what's there.
829 sub loadnum ($;$) {
830 my $file = shift;
831 my $type = shift;
832 my @symbols;
833
834 open my $IN, '<', catfile($config{sourcedir}, $file)
835 or die "Can't open $file, $!, stopped";
836
837 while ( <$IN> ) {
838 next if /^#/;
839 next if /\bNOEXIST\b/;
840 my @fields = split();
841 die "Malformed line $. in $file: $_"
842 if scalar @fields != 2 && scalar @fields != 4;
843 $state{$fields[0].'(3)'} = $type // 'internal';
844 }
845 close $IN;
846 }
847
848 # Load file of symbol names that we know aren't documented.
849 sub loadmissing($;$)
850 {
851 my $missingfile = shift;
852 my $type = shift;
853
854 open FH, catfile($config{sourcedir}, $missingfile)
855 or die "Can't open $missingfile";
856 while ( <FH> ) {
857 chomp;
858 next if /^#/;
859 $missing{$_} = $type // 'internal';
860 }
861 close FH;
862 }
863
864 # Check that we have consistent public / internal documentation and declaration
865 sub checkstate () {
866 # Collect all known names, no matter where they come from
867 my %names = map { $_ => 1 } (keys %name_map, keys %state, keys %missing);
868
869 # Check section 3, i.e. functions and macros
870 foreach ( grep { $_ =~ /\(3\)$/ } sort keys %names ) {
871 next if ( $name_map{$_} // '') eq '' || $_ =~ /$ignored/;
872
873 # If a man-page isn't recorded public or if it's recorded missing
874 # and internal, it's declared to be internal.
875 my $declared_internal =
876 ($state{$_} // 'internal') eq 'internal'
877 || ($missing{$_} // '') eq 'internal';
878 # If a man-page isn't recorded internal or if it's recorded missing
879 # and not internal, it's declared to be public
880 my $declared_public =
881 ($state{$_} // 'internal') ne 'internal'
882 || ($missing{$_} // 'internal') ne 'internal';
883
884 err("$_ is supposedly public but is documented as internal")
885 if ( $declared_public && $name_map{$_} =~ /\/internal\// );
886 err("$_ is supposedly internal but is documented as public")
887 if ( $declared_internal && $name_map{$_} !~ /\/internal\// );
888 }
889 }
890
891 # Check for undocumented macros; ignore those in the "missing" file
892 # and do simple check for #define in our header files.
893 sub checkmacros {
894 my $count = 0;
895 my %seen;
896
897 foreach my $f ( files(TAGS => 'public_header') ) {
898 # Skip some internals we don't want to document yet.
899 my $b = basename($f);
900 next if $b eq 'asn1.h';
901 next if $b eq 'asn1t.h';
902 next if $b eq 'err.h';
903 open(IN, $f)
904 or die "Can't open $f, $!";
905 while ( <IN> ) {
906 next unless /^#\s*define\s*(\S+)\(/;
907 my $macro = "$1(3)"; # We know they're all in section 3
908 next if defined $name_map{$macro}
909 || defined $missing{$macro}
910 || defined $seen{$macro}
911 || $macro =~ /$ignored/;
912
913 err("$f:", "macro $macro undocumented")
914 if $opt_d || $opt_e;
915 $count++;
916 $seen{$macro} = 1;
917 }
918 close(IN);
919 }
920 err("# $count macros undocumented (count is approximate)")
921 if $count > 0;
922 }
923
924 # Find out what is undocumented (filtering out the known missing ones)
925 # and display them.
926 sub printem ($) {
927 my $type = shift;
928 my $count = 0;
929
930 foreach my $func ( grep { $state{$_} eq $type } sort keys %state ) {
931 next if defined $name_map{$func}
932 || defined $missing{$func};
933
934 err("$type:", "function $func undocumented")
935 if $opt_d || $opt_e;
936 $count++;
937 }
938 err("# $count lib$type names are not documented")
939 if $count > 0;
940 }
941
942 # Collect all the names in a manpage.
943 sub collectnames {
944 my %podinfo = @_;
945 my $filename = $podinfo{filename};
946 $filename =~ m|man(\d)/|;
947 my $section = $1;
948 my $simplename = basename($filename, ".pod");
949 my $id = "${filename}:1:";
950 my $is_generic = $podinfo{contents} =~ /^=for openssl generic/ms;
951
952 unless ( grep { $simplename eq $_ } @{$podinfo{names}} ) {
953 err($id, "$simplename not in NAME section");
954 push @{$podinfo{names}}, $simplename;
955 }
956 foreach my $name ( @{$podinfo{names}} ) {
957 next if $name eq "";
958 err($id, "'$name' contains whitespace")
959 if $name =~ /\s/;
960 my $name_sec = "$name($section)";
961 if ( !defined $name_map{$name_sec} ) {
962 $name_map{$name_sec} = $filename;
963 $state{$name_sec} //=
964 ( $filename =~ /\/internal\// ? 'internal' : 'public' )
965 if $is_generic;
966 } elsif ( $filename eq $name_map{$name_sec} ) {
967 err($id, "$name_sec duplicated in NAME section of",
968 $name_map{$name_sec});
969 } elsif ( $name_map{$name_sec} ne '' ) {
970 err($id, "$name_sec also in NAME section of",
971 $name_map{$name_sec});
972 }
973 }
974
975 if ( $podinfo{contents} =~ /=for openssl foreign manual (.*)\n/ ) {
976 foreach my $f ( split / /, $1 ) {
977 $name_map{$f} = ''; # It still exists!
978 $state{$f} = 'public'; # We assume!
979 }
980 }
981
982 my @links =
983 $podinfo{contents} =~ /L<
984 # if the link is of the form L<something|name(s)>,
985 # then remove 'something'. Note that 'something'
986 # may contain POD codes as well...
987 (?:(?:[^\|]|<[^>]*>)*\|)?
988 # we're only interested in references that have
989 # a one digit section number
990 ([^\/>\(]+\(\d\))
991 /gx;
992 $link_map{$filename} = [ @links ];
993 }
994
995 # Look for L<> ("link") references that point to files that do not exist.
996 sub checklinks {
997 foreach my $filename ( sort keys %link_map ) {
998 foreach my $link ( @{$link_map{$filename}} ) {
999 err("${filename}:1:", "reference to non-existing $link")
1000 unless defined $name_map{$link} || defined $missing{$link};
1001 err("${filename}:1:", "reference of internal $link in public documentation $filename")
1002 if ( ( ($state{$link} // '') eq 'internal'
1003 || ($missing{$link} // '') eq 'internal' )
1004 && $filename !~ /\/internal\// );
1005 }
1006 }
1007 }
1008
1009 # Cipher/digests to skip if they show up as "not implemented"
1010 # because they are, via the "-*" construct.
1011 my %skips = (
1012 'aes128' => 1,
1013 'aes192' => 1,
1014 'aes256' => 1,
1015 'aria128' => 1,
1016 'aria192' => 1,
1017 'aria256' => 1,
1018 'camellia128' => 1,
1019 'camellia192' => 1,
1020 'camellia256' => 1,
1021 'des' => 1,
1022 'des3' => 1,
1023 'idea' => 1,
1024 'cipher' => 1,
1025 'digest' => 1,
1026 );
1027
1028 # Check the flags of a command and see if everything is in the manpage
1029 sub checkflags {
1030 my $cmd = shift;
1031 my $doc = shift;
1032 my %cmdopts;
1033 my %docopts;
1034 my %localskips;
1035
1036 # Get the list of options in the command.
1037 open CFH, "$openssl list --options $cmd|"
1038 or die "Can list options for $cmd, $!";
1039 while ( <CFH> ) {
1040 chop;
1041 s/ .$//;
1042 $cmdopts{$_} = 1;
1043 }
1044 close CFH;
1045
1046 # Get the list of flags from the synopsis
1047 open CFH, "<$doc"
1048 or die "Can't open $doc, $!";
1049 while ( <CFH> ) {
1050 chop;
1051 last if /DESCRIPTION/;
1052 if ( /=for openssl ifdef (.*)/ ) {
1053 foreach my $f ( split / /, $1 ) {
1054 $localskips{$f} = 1;
1055 }
1056 next;
1057 }
1058 my $opt;
1059 if ( /\[B<-([^ >]+)/ ) {
1060 $opt = $1;
1061 } elsif ( /^B<-([^ >]+)/ ) {
1062 $opt = $1;
1063 } else {
1064 next;
1065 }
1066 $opt = $1 if $opt =~ /I<(.*)/;
1067 $docopts{$1} = 1;
1068 }
1069 close CFH;
1070
1071 # See what's in the command not the manpage.
1072 my @undocced = sort grep { !defined $docopts{$_} } keys %cmdopts;
1073 foreach ( @undocced ) {
1074 next if /-/; # Skip the -- end-of-flags marker
1075 err("$doc: undocumented option -$_");
1076 }
1077
1078 # See what's in the command not the manpage.
1079 my @unimpl = sort grep { !defined $cmdopts{$_} } keys %docopts;
1080 foreach ( @unimpl ) {
1081 next if defined $skips{$_} || defined $localskips{$_};
1082 err("$doc: $cmd does not implement -$_");
1083 }
1084 }
1085
1086 ##
1087 ## MAIN()
1088 ## Do the work requested by the various getopt flags.
1089 ## The flags are parsed in alphabetical order, just because we have
1090 ## to have *some way* of listing them.
1091 ##
1092
1093 if ( $opt_c ) {
1094 my @commands = ();
1095
1096 # Get list of commands.
1097 open FH, "$openssl list -1 -commands|"
1098 or die "Can't list commands, $!";
1099 while ( <FH> ) {
1100 chop;
1101 push @commands, $_;
1102 }
1103 close FH;
1104
1105 # See if each has a manpage.
1106 foreach my $cmd ( @commands ) {
1107 next if $cmd eq 'help' || $cmd eq 'exit';
1108 my @doc = ( grep { basename($_) eq "openssl-$cmd.pod"
1109 # For "tsget" and "CA.pl" pod pages
1110 || basename($_) eq "$cmd.pod" }
1111 files(TAGS => [ 'manual', 'man1' ]) );
1112 my $num = scalar @doc;
1113 if ($num > 1) {
1114 err("$num manuals for 'openssl $cmd': ".join(", ", @doc));
1115 } elsif ($num < 1) {
1116 err("no manual for 'openssl $cmd'");
1117 } else {
1118 checkflags($cmd, @doc);
1119 }
1120 }
1121
1122 # See what help is missing.
1123 open FH, "$openssl list --missing-help |"
1124 or die "Can't list missing help, $!";
1125 while ( <FH> ) {
1126 chop;
1127 my ($cmd, $flag) = split;
1128 err("$cmd has no help for -$flag");
1129 }
1130 close FH;
1131
1132 exit $status;
1133 }
1134
1135 # Populate %state
1136 loadnum('util/libcrypto.num', 'crypto');
1137 loadnum('util/libssl.num', 'ssl');
1138 loadnum('util/other.syms', 'other');
1139 loadnum('util/other-internal.syms');
1140 if ( $opt_o ) {
1141 loadmissing('util/missingmacro111.txt', 'crypto');
1142 loadmissing('util/missingcrypto111.txt', 'crypto');
1143 loadmissing('util/missingssl111.txt', 'ssl');
1144 } elsif ( !$opt_u ) {
1145 loadmissing('util/missingmacro.txt', 'crypto');
1146 loadmissing('util/missingcrypto.txt', 'crypto');
1147 loadmissing('util/missingssl.txt', 'ssl');
1148 loadmissing('util/missingcrypto-internal.txt');
1149 loadmissing('util/missingssl-internal.txt');
1150 }
1151
1152 if ( $opt_n || $opt_l || $opt_u || $opt_v ) {
1153 my @files_to_read = ( $opt_n && @ARGV ) ? @ARGV : files(TAGS => 'manual');
1154
1155 foreach (@files_to_read) {
1156 my %podinfo = extract_pod_info($_, { debug => $debug });
1157
1158 collectnames(%podinfo)
1159 if ( $opt_l || $opt_u || $opt_v );
1160
1161 check(%podinfo)
1162 if ( $opt_n );
1163 }
1164 }
1165
1166 if ( $opt_l ) {
1167 checklinks();
1168 }
1169
1170 if ( $opt_n ) {
1171 # If not given args, check that all man1 commands are named properly.
1172 if ( scalar @ARGV == 0 ) {
1173 foreach ( files(TAGS => [ 'public_manual', 'man1' ]) ) {
1174 next if /CA.pl/ || /openssl\.pod/ || /tsget\.pod/;
1175 err("$_ doesn't start with openssl-") unless /openssl-/;
1176 }
1177 }
1178 }
1179
1180 checkstate();
1181
1182 if ( $opt_u || $opt_v) {
1183 printem('crypto');
1184 printem('ssl');
1185 checkmacros();
1186 }
1187
1188 exit $status;