Check for input size, and do not overallocate memory.
[coreutils.git] / src / nl.c
blob26f2e4763b0a33c0897f52a634977b5b2c754623
1 /* nl -- number lines of files
2 Copyright (C) 89, 92, 1995-2000 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
7 any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Written by Scott Bartram (nancy!scott@uunet.uu.net)
19 Revised by David MacKenzie (djm@gnu.ai.mit.edu) */
21 #include <config.h>
23 #include <stdio.h>
24 #include <sys/types.h>
25 #include <getopt.h>
27 #include "system.h"
28 #include "closeout.h"
30 #include <regex.h>
32 #include "error.h"
33 #include "linebuffer.h"
34 #include "xstrtol.h"
36 /* The official name of this program (e.g., no `g' prefix). */
37 #define PROGRAM_NAME "nl"
39 #define AUTHORS "Scott Bartram and David MacKenzie"
41 #ifndef TRUE
42 # define TRUE 1
43 # define FALSE 0
44 #endif
46 /* Line-number formats. */
47 enum number_format
49 FORMAT_RIGHT_NOLZ, /* Right justified, no leading zeroes. */
50 FORMAT_RIGHT_LZ, /* Right justified, leading zeroes. */
51 FORMAT_LEFT /* Left justified, no leading zeroes. */
54 /* Default section delimiter characters. */
55 #define DEFAULT_SECTION_DELIMITERS "\\:"
57 /* Types of input lines: either one of the section delimiters,
58 or text to output. */
59 enum section
61 Header, Body, Footer, Text
64 /* The name this program was run with. */
65 char *program_name;
67 /* Format of body lines (-b). */
68 static char *body_type = "t";
70 /* Format of header lines (-h). */
71 static char *header_type = "n";
73 /* Format of footer lines (-f). */
74 static char *footer_type = "n";
76 /* Format currently being used (body, header, or footer). */
77 static char *current_type;
79 /* Regex for body lines to number (-bp). */
80 static struct re_pattern_buffer body_regex;
82 /* Regex for header lines to number (-hp). */
83 static struct re_pattern_buffer header_regex;
85 /* Regex for footer lines to number (-fp). */
86 static struct re_pattern_buffer footer_regex;
88 /* Pointer to current regex, if any. */
89 static struct re_pattern_buffer *current_regex = NULL;
91 /* Separator string to print after line number (-s). */
92 static char *separator_str = "\t";
94 /* Input section delimiter string (-d). */
95 static char *section_del = DEFAULT_SECTION_DELIMITERS;
97 /* Header delimiter string. */
98 static char *header_del = NULL;
100 /* Header section delimiter length. */
101 static size_t header_del_len;
103 /* Body delimiter string. */
104 static char *body_del = NULL;
106 /* Body section delimiter length. */
107 static size_t body_del_len;
109 /* Footer delimiter string. */
110 static char *footer_del = NULL;
112 /* Footer section delimiter length. */
113 static size_t footer_del_len;
115 /* Input buffer. */
116 static struct linebuffer line_buf;
118 /* printf format string for line number. */
119 static char *print_fmt;
121 /* printf format string for unnumbered lines. */
122 static char *print_no_line_fmt = NULL;
124 /* Starting line number on each page (-v). */
125 static int starting_line_number = 1;
127 /* Line number increment (-i). */
128 static int page_incr = 1;
130 /* If TRUE, reset line number at start of each page (-p). */
131 static int reset_numbers = TRUE;
133 /* Number of blank lines to consider to be one line for numbering (-l). */
134 static int blank_join = 1;
136 /* Width of line numbers (-w). */
137 static int lineno_width = 6;
139 /* Line number format (-n). */
140 static enum number_format lineno_format = FORMAT_RIGHT_NOLZ;
142 /* Current print line number. */
143 static int line_no;
145 /* Nonzero if we have ever read standard input. */
146 static int have_read_stdin;
148 static struct option const longopts[] =
150 {"header-numbering", required_argument, NULL, 'h'},
151 {"body-numbering", required_argument, NULL, 'b'},
152 {"footer-numbering", required_argument, NULL, 'f'},
153 {"starting-line-number", required_argument, NULL, 'v'},
154 {"page-increment", required_argument, NULL, 'i'},
155 {"no-renumber", no_argument, NULL, 'p'},
156 {"join-blank-lines", required_argument, NULL, 'l'},
157 {"number-separator", required_argument, NULL, 's'},
158 {"number-width", required_argument, NULL, 'w'},
159 {"number-format", required_argument, NULL, 'n'},
160 {"section-delimiter", required_argument, NULL, 'd'},
161 {GETOPT_HELP_OPTION_DECL},
162 {GETOPT_VERSION_OPTION_DECL},
163 {NULL, 0, NULL, 0}
166 /* Print a usage message and quit. */
168 void
169 usage (int status)
171 if (status != 0)
172 fprintf (stderr, _("Try `%s --help' for more information.\n"),
173 program_name);
174 else
176 printf (_("\
177 Usage: %s [OPTION]... [FILE]...\n\
179 program_name);
180 printf (_("\
181 Write each FILE to standard output, with line numbers added.\n\
182 With no FILE, or when FILE is -, read standard input.\n\
184 -b, --body-numbering=STYLE use STYLE for numbering body lines\n\
185 -d, --section-delimiter=CC use CC for separating logical pages\n\
186 -f, --footer-numbering=STYLE use STYLE for numbering footer lines\n\
187 -h, --header-numbering=STYLE use STYLE for numbering header lines\n\
188 -i, --page-increment=NUMBER line number increment at each line\n\
189 -l, --join-blank-lines=NUMBER group of NUMBER empty lines counted as one\n\
190 -n, --number-format=FORMAT insert line numbers according to FORMAT\n\
191 -p, --no-renumber do not reset line numbers at logical pages\n\
192 -s, --number-separator=STRING add STRING after (possible) line number\n\
193 -v, --first-page=NUMBER first line number on each logical page\n\
194 -w, --number-width=NUMBER use NUMBER columns for line numbers\n\
195 --help display this help and exit\n\
196 --version output version information and exit\n\
198 By default, selects -v1 -i1 -l1 -sTAB -w6 -nrn -hn -bt -fn. CC are\n\
199 two delimiter characters for separating logical pages, a missing\n\
200 second character implies :. Type \\\\ for \\. STYLE is one of:\n\
202 a number all lines\n\
203 t number only nonempty lines\n\
204 n number no lines\n\
205 pREGEXP number only lines that contain a match for REGEXP\n\
207 FORMAT is one of:\n\
209 ln left justified, no leading zeros\n\
210 rn right justified, no leading zeros\n\
211 rz right justified, leading zeros\n\
213 "));
214 puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
216 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
219 /* Build the printf format string, based on `lineno_format'. */
221 static void
222 build_print_fmt (void)
224 /* 12 = 10 chars for lineno_width, 1 for %, 1 for \0. */
225 print_fmt = xmalloc (strlen (separator_str) + 12);
226 switch (lineno_format)
228 case FORMAT_RIGHT_NOLZ:
229 sprintf (print_fmt, "%%%dd%s", lineno_width, separator_str);
230 break;
231 case FORMAT_RIGHT_LZ:
232 sprintf (print_fmt, "%%0%dd%s", lineno_width, separator_str);
233 break;
234 case FORMAT_LEFT:
235 sprintf (print_fmt, "%%-%dd%s", lineno_width, separator_str);
236 break;
240 /* Set the command line flag TYPEP and possibly the regex pointer REGEXP,
241 according to `optarg'. */
243 static int
244 build_type_arg (char **typep, struct re_pattern_buffer *regexp)
246 const char *errmsg;
247 int rval = TRUE;
248 int optlen;
250 switch (*optarg)
252 case 'a':
253 case 't':
254 case 'n':
255 *typep = optarg;
256 break;
257 case 'p':
258 *typep = optarg++;
259 optlen = strlen (optarg);
260 regexp->allocated = optlen * 2;
261 regexp->buffer = (unsigned char *) xmalloc (regexp->allocated);
262 regexp->translate = NULL;
263 regexp->fastmap = xmalloc (256);
264 regexp->fastmap_accurate = 0;
265 errmsg = re_compile_pattern (optarg, optlen, regexp);
266 if (errmsg)
267 error (EXIT_FAILURE, 0, "%s", errmsg);
268 break;
269 default:
270 rval = FALSE;
271 break;
273 return rval;
276 /* Print and increment the line number. */
278 static void
279 print_lineno (void)
281 printf (print_fmt, line_no);
282 line_no += page_incr;
285 /* Switch to a header section. */
287 static void
288 proc_header (void)
290 current_type = header_type;
291 current_regex = &header_regex;
292 if (reset_numbers)
293 line_no = starting_line_number;
294 putchar ('\n');
297 /* Switch to a body section. */
299 static void
300 proc_body (void)
302 current_type = body_type;
303 current_regex = &body_regex;
304 putchar ('\n');
307 /* Switch to a footer section. */
309 static void
310 proc_footer (void)
312 current_type = footer_type;
313 current_regex = &footer_regex;
314 putchar ('\n');
317 /* Process a regular text line in `line_buf'. */
319 static void
320 proc_text (void)
322 static int blank_lines = 0; /* Consecutive blank lines so far. */
324 switch (*current_type)
326 case 'a':
327 if (blank_join > 1)
329 if (1 < line_buf.length || ++blank_lines == blank_join)
331 print_lineno ();
332 blank_lines = 0;
334 else
335 printf (print_no_line_fmt);
337 else
338 print_lineno ();
339 break;
340 case 't':
341 if (1 < line_buf.length)
342 print_lineno ();
343 else
344 printf (print_no_line_fmt);
345 break;
346 case 'n':
347 printf (print_no_line_fmt);
348 break;
349 case 'p':
350 if (re_search (current_regex, line_buf.buffer, line_buf.length - 1,
351 0, line_buf.length - 1, (struct re_registers *) 0) < 0)
352 printf (print_no_line_fmt);
353 else
354 print_lineno ();
355 break;
357 fwrite (line_buf.buffer, sizeof (char), line_buf.length, stdout);
360 /* Return the type of line in `line_buf'. */
362 static enum section
363 check_section (void)
365 size_t len = line_buf.length - 1;
367 if (len < 2 || memcmp (line_buf.buffer, section_del, 2))
368 return Text;
369 if (len == header_del_len
370 && !memcmp (line_buf.buffer, header_del, header_del_len))
371 return Header;
372 if (len == body_del_len
373 && !memcmp (line_buf.buffer, body_del, body_del_len))
374 return Body;
375 if (len == footer_del_len
376 && !memcmp (line_buf.buffer, footer_del, footer_del_len))
377 return Footer;
378 return Text;
381 /* Read and process the file pointed to by FP. */
383 static void
384 process_file (FILE *fp)
386 while (readline (&line_buf, fp))
388 switch ((int) check_section ())
390 case Header:
391 proc_header ();
392 break;
393 case Body:
394 proc_body ();
395 break;
396 case Footer:
397 proc_footer ();
398 break;
399 case Text:
400 proc_text ();
401 break;
406 /* Process file FILE to standard output.
407 Return 0 if successful, 1 if not. */
409 static int
410 nl_file (const char *file)
412 FILE *stream;
414 if (STREQ (file, "-"))
416 have_read_stdin = 1;
417 stream = stdin;
419 else
421 stream = fopen (file, "r");
422 if (stream == NULL)
424 error (0, errno, "%s", file);
425 return 1;
429 process_file (stream);
431 if (ferror (stream))
433 error (0, errno, "%s", file);
434 return 1;
436 if (STREQ (file, "-"))
437 clearerr (stream); /* Also clear EOF. */
438 else if (fclose (stream) == EOF)
440 error (0, errno, "%s", file);
441 return 1;
443 return 0;
447 main (int argc, char **argv)
449 int c, exit_status = 0;
450 size_t len;
452 program_name = argv[0];
453 setlocale (LC_ALL, "");
454 bindtextdomain (PACKAGE, LOCALEDIR);
455 textdomain (PACKAGE);
457 atexit (close_stdout);
459 have_read_stdin = 0;
461 while ((c = getopt_long (argc, argv, "h:b:f:v:i:pl:s:w:n:d:", longopts,
462 NULL)) != -1)
464 switch (c)
466 case 0:
467 break;
469 case 'h':
470 if (build_type_arg (&header_type, &header_regex) != TRUE)
471 usage (2);
472 break;
473 case 'b':
474 if (build_type_arg (&body_type, &body_regex) != TRUE)
475 usage (2);
476 break;
477 case 'f':
478 if (build_type_arg (&footer_type, &footer_regex) != TRUE)
479 usage (2);
480 break;
481 case 'v':
483 long int tmp_long;
484 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
485 /* Allow it to be negative. */
486 || tmp_long > INT_MAX)
487 error (EXIT_FAILURE, 0, _("invalid starting line number: `%s'"),
488 optarg);
489 starting_line_number = (int) tmp_long;
491 break;
492 case 'i':
494 long int tmp_long;
495 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
496 || tmp_long <= 0 || tmp_long > INT_MAX)
497 error (EXIT_FAILURE, 0, _("invalid line number increment: `%s'"),
498 optarg);
499 page_incr = (int) tmp_long;
501 break;
502 case 'p':
503 reset_numbers = FALSE;
504 break;
505 case 'l':
507 long int tmp_long;
508 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
509 || tmp_long <= 0 || tmp_long > INT_MAX)
510 error (EXIT_FAILURE, 0, _("invalid number of blank lines: `%s'"),
511 optarg);
512 blank_join = (int) tmp_long;
514 break;
515 case 's':
516 separator_str = optarg;
517 break;
518 case 'w':
520 long int tmp_long;
521 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
522 || tmp_long <= 0 || tmp_long > INT_MAX)
523 error (EXIT_FAILURE, 0,
524 _("invalid line number field width: `%s'"),
525 optarg);
526 lineno_width = (int) tmp_long;
528 break;
529 case 'n':
530 switch (*optarg)
532 case 'l':
533 if (optarg[1] == 'n')
534 lineno_format = FORMAT_LEFT;
535 else
536 usage (2);
537 break;
538 case 'r':
539 switch (optarg[1])
541 case 'n':
542 lineno_format = FORMAT_RIGHT_NOLZ;
543 break;
544 case 'z':
545 lineno_format = FORMAT_RIGHT_LZ;
546 break;
547 default:
548 usage (2);
549 break;
551 break;
552 default:
553 usage (2);
554 break;
556 break;
557 case 'd':
558 section_del = optarg;
559 break;
560 case_GETOPT_HELP_CHAR;
561 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
562 default:
563 usage (2);
564 break;
568 /* Initialize the section delimiters. */
569 len = strlen (section_del);
571 header_del_len = len * 3;
572 header_del = xmalloc (header_del_len + 1);
573 strcat (strcat (strcpy (header_del, section_del), section_del), section_del);
575 body_del_len = len * 2;
576 body_del = xmalloc (body_del_len + 1);
577 strcat (strcpy (body_del, section_del), section_del);
579 footer_del_len = len;
580 footer_del = xmalloc (footer_del_len + 1);
581 strcpy (footer_del, section_del);
583 /* Initialize the input buffer. */
584 initbuffer (&line_buf);
586 /* Initialize the printf format for unnumbered lines. */
587 len = strlen (separator_str);
588 print_no_line_fmt = xmalloc (lineno_width + len + 1);
589 memset (print_no_line_fmt, ' ', lineno_width + len);
590 print_no_line_fmt[lineno_width + len] = '\0';
592 line_no = starting_line_number;
593 current_type = body_type;
594 current_regex = &body_regex;
595 build_print_fmt ();
597 /* Main processing. */
599 if (optind == argc)
600 exit_status |= nl_file ("-");
601 else
602 for (; optind < argc; optind++)
603 exit_status |= nl_file (argv[optind]);
605 if (have_read_stdin && fclose (stdin) == EOF)
607 error (0, errno, "-");
608 exit_status = 1;
611 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);