(sysv_sum_file): Avoid overflowing 32-bit accumulator
[platform/upstream/coreutils.git] / src / sum.c
1 /* sum -- checksum and count the blocks in a file
2    Copyright (C) 86, 89, 91, 1995-2000 Free Software Foundation, Inc.
3
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.
8
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.
13
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
16    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
17
18 /* Like BSD sum or SysV sum -r, except like SysV sum if -s option is given. */
19
20 /* Written by Kayvan Aghaiepour and David MacKenzie. */
21
22 #include <config.h>
23
24 #include <stdio.h>
25 #include <sys/types.h>
26 #include <getopt.h>
27 #include "system.h"
28 #include "closeout.h"
29 #include "error.h"
30 #include "safe-read.h"
31
32 /* The official name of this program (e.g., no `g' prefix).  */
33 #define PROGRAM_NAME "sum"
34
35 #define AUTHORS "Kayvan Aghaiepour and David MacKenzie"
36
37 /* The name this program was run with. */
38 char *program_name;
39
40 /* Nonzero if any of the files read were the standard input. */
41 static int have_read_stdin;
42
43 /* Right-rotate 32-bit integer variable C. */
44 #define ROTATE_RIGHT(c) if ((c) & 01) (c) = ((c) >>1) + 0x8000; else (c) >>= 1;
45
46 static struct option const longopts[] =
47 {
48   {"sysv", no_argument, NULL, 's'},
49   {GETOPT_HELP_OPTION_DECL},
50   {GETOPT_VERSION_OPTION_DECL},
51   {NULL, 0, NULL, 0}
52 };
53
54 void
55 usage (int status)
56 {
57   if (status != 0)
58     fprintf (stderr, _("Try `%s --help' for more information.\n"),
59              program_name);
60   else
61     {
62       printf (_("\
63 Usage: %s [OPTION]... [FILE]...\n\
64 "),
65               program_name);
66       printf (_("\
67 Print checksum and block counts for each FILE.\n\
68 \n\
69   -r              defeat -s, use BSD sum algorithm, use 1K blocks\n\
70   -s, --sysv      use System V sum algorithm, use 512 bytes blocks\n\
71       --help      display this help and exit\n\
72       --version   output version information and exit\n\
73 \n\
74 With no FILE, or when FILE is -, read standard input.\n\
75 "));
76       puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
77     }
78   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
79 }
80
81 /* Calculate and print the rotated checksum and the size in 1K blocks
82    of file FILE, or of the standard input if FILE is "-".
83    If PRINT_NAME is >1, print FILE next to the checksum and size.
84    The checksum varies depending on sizeof(int).
85    Return 0 if successful, -1 if an error occurs. */
86
87 static int
88 bsd_sum_file (const char *file, int print_name)
89 {
90   register FILE *fp;
91   register unsigned long checksum = 0; /* The checksum mod 2^16. */
92   register long total_bytes = 0; /* The number of bytes. */
93   register int ch;              /* Each character read. */
94
95   if (STREQ (file, "-"))
96     {
97       fp = stdin;
98       have_read_stdin = 1;
99     }
100   else
101     {
102       fp = fopen (file, "r");
103       if (fp == NULL)
104         {
105           error (0, errno, "%s", file);
106           return -1;
107         }
108     }
109   /* Need binary I/O, or else byte counts and checksums are incorrect.  */
110   SET_BINARY (fileno(fp));
111
112   while ((ch = getc (fp)) != EOF)
113     {
114       total_bytes++;
115       ROTATE_RIGHT (checksum);
116       checksum += ch;
117       checksum &= 0xffff;       /* Keep it within bounds. */
118     }
119
120   if (ferror (fp))
121     {
122       error (0, errno, "%s", file);
123       if (!STREQ (file, "-"))
124         fclose (fp);
125       return -1;
126     }
127
128   if (!STREQ (file, "-") && fclose (fp) == EOF)
129     {
130       error (0, errno, "%s", file);
131       return -1;
132     }
133
134   printf ("%05lu %5ld", checksum, (total_bytes + 1024 - 1) / 1024);
135   if (print_name > 1)
136     printf (" %s", file);
137   putchar ('\n');
138
139   return 0;
140 }
141
142 /* Calculate and print the checksum and the size in 512-byte blocks
143    of file FILE, or of the standard input if FILE is "-".
144    If PRINT_NAME is >0, print FILE next to the checksum and size.
145    Return 0 if successful, -1 if an error occurs. */
146
147 static int
148 sysv_sum_file (const char *file, int print_name)
149 {
150   int fd;
151   unsigned char buf[8192];
152   register int bytes_read;
153   register unsigned long checksum = 0;
154   long total_bytes = 0;
155
156   if (STREQ (file, "-"))
157     {
158       fd = 0;
159       have_read_stdin = 1;
160     }
161   else
162     {
163       fd = open (file, O_RDONLY);
164       if (fd == -1)
165         {
166           error (0, errno, "%s", file);
167           return -1;
168         }
169     }
170   /* Need binary I/O, or else byte counts and checksums are incorrect.  */
171   SET_BINARY (fd);
172
173   while ((bytes_read = safe_read (fd, buf, sizeof buf)) > 0)
174     {
175       register int i;
176
177       for (i = 0; i < bytes_read; i++)
178         checksum += buf[i];
179       /* Reduce checksum mod 0xffff, to avoid overflow.  */
180       checksum = (checksum & 0xffff) + (checksum >> 16);
181
182       total_bytes += bytes_read;
183     }
184
185   if (bytes_read < 0)
186     {
187       error (0, errno, "%s", file);
188       if (!STREQ (file, "-"))
189         close (fd);
190       return -1;
191     }
192
193   if (!STREQ (file, "-") && close (fd) == -1)
194     {
195       error (0, errno, "%s", file);
196       return -1;
197     }
198
199   printf ("%lu %ld", checksum % 0xffff, (total_bytes + 512 - 1) / 512);
200   if (print_name)
201     printf (" %s", file);
202   putchar ('\n');
203
204   return 0;
205 }
206
207 int
208 main (int argc, char **argv)
209 {
210   int errors = 0;
211   int optc;
212   int files_given;
213   int (*sum_func) () = bsd_sum_file;
214
215   program_name = argv[0];
216   setlocale (LC_ALL, "");
217   bindtextdomain (PACKAGE, LOCALEDIR);
218   textdomain (PACKAGE);
219
220   atexit (close_stdout);
221
222   have_read_stdin = 0;
223
224   while ((optc = getopt_long (argc, argv, "rs", longopts, NULL)) != -1)
225     {
226       switch (optc)
227         {
228         case 0:
229           break;
230
231         case 'r':               /* For SysV compatibility. */
232           sum_func = bsd_sum_file;
233           break;
234
235         case 's':
236           sum_func = sysv_sum_file;
237           break;
238
239         case_GETOPT_HELP_CHAR;
240
241         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
242
243         default:
244           usage (1);
245         }
246     }
247
248   files_given = argc - optind;
249   if (files_given == 0)
250     {
251       if ((*sum_func) ("-", files_given) < 0)
252         errors = 1;
253     }
254   else
255     for (; optind < argc; optind++)
256       if ((*sum_func) (argv[optind], files_given) < 0)
257         errors = 1;
258
259   if (have_read_stdin && fclose (stdin) == EOF)
260     error (EXIT_FAILURE, errno, "-");
261   exit (errors == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
262 }