adjust copyright dates
[platform/upstream/coreutils.git] / src / sum.c
1 /* sum -- checksum and count the blocks in a file
2    Copyright (C) 86, 89, 91, 1995-2002, 2004, 2005, 2008
3    Free Software Foundation, Inc.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation, either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
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 "error.h"
29 #include "human.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 \
36   proper_name ("Kayvan Aghaiepour"), \
37   proper_name ("David MacKenzie")
38
39 /* The name this program was run with. */
40 char *program_name;
41
42 /* True if any of the files read were the standard input. */
43 static bool have_read_stdin;
44
45 static struct option const longopts[] =
46 {
47   {"sysv", no_argument, NULL, 's'},
48   {GETOPT_HELP_OPTION_DECL},
49   {GETOPT_VERSION_OPTION_DECL},
50   {NULL, 0, NULL, 0}
51 };
52
53 void
54 usage (int status)
55 {
56   if (status != EXIT_SUCCESS)
57     fprintf (stderr, _("Try `%s --help' for more information.\n"),
58              program_name);
59   else
60     {
61       printf (_("\
62 Usage: %s [OPTION]... [FILE]...\n\
63 "),
64               program_name);
65       fputs (_("\
66 Print checksum and block counts for each FILE.\n\
67 \n\
68   -r              defeat -s, use BSD sum algorithm, use 1K blocks\n\
69   -s, --sysv      use System V sum algorithm, use 512 bytes blocks\n\
70 "), stdout);
71       fputs (HELP_OPTION_DESCRIPTION, stdout);
72       fputs (VERSION_OPTION_DESCRIPTION, stdout);
73       fputs (_("\
74 \n\
75 With no FILE, or when FILE is -, read standard input.\n\
76 "), stdout);
77       emit_bug_reporting_address ();
78     }
79   exit (status);
80 }
81
82 /* Calculate and print the rotated checksum and the size in 1K blocks
83    of file FILE, or of the standard input if FILE is "-".
84    If PRINT_NAME is >1, print FILE next to the checksum and size.
85    The checksum varies depending on sizeof (int).
86    Return true if successful.  */
87
88 static bool
89 bsd_sum_file (const char *file, int print_name)
90 {
91   FILE *fp;
92   int checksum = 0;     /* The checksum mod 2^16. */
93   uintmax_t total_bytes = 0;    /* The number of bytes. */
94   int ch;               /* Each character read. */
95   char hbuf[LONGEST_HUMAN_READABLE + 1];
96   bool is_stdin = STREQ (file, "-");
97
98   if (is_stdin)
99     {
100       fp = stdin;
101       have_read_stdin = true;
102       if (O_BINARY && ! isatty (STDIN_FILENO))
103         freopen (NULL, "rb", stdin);
104     }
105   else
106     {
107       fp = fopen (file, (O_BINARY ? "rb" : "r"));
108       if (fp == NULL)
109         {
110           error (0, errno, "%s", file);
111           return false;
112         }
113     }
114
115   while ((ch = getc (fp)) != EOF)
116     {
117       total_bytes++;
118       checksum = (checksum >> 1) + ((checksum & 1) << 15);
119       checksum += ch;
120       checksum &= 0xffff;       /* Keep it within bounds. */
121     }
122
123   if (ferror (fp))
124     {
125       error (0, errno, "%s", file);
126       if (!is_stdin)
127         fclose (fp);
128       return false;
129     }
130
131   if (!is_stdin && fclose (fp) != 0)
132     {
133       error (0, errno, "%s", file);
134       return false;
135     }
136
137   printf ("%05d %5s", checksum,
138           human_readable (total_bytes, hbuf, human_ceiling, 1, 1024));
139   if (print_name > 1)
140     printf (" %s", file);
141   putchar ('\n');
142
143   return true;
144 }
145
146 /* Calculate and print the checksum and the size in 512-byte blocks
147    of file FILE, or of the standard input if FILE is "-".
148    If PRINT_NAME is >0, print FILE next to the checksum and size.
149    Return true if successful.  */
150
151 static bool
152 sysv_sum_file (const char *file, int print_name)
153 {
154   int fd;
155   unsigned char buf[8192];
156   uintmax_t total_bytes = 0;
157   char hbuf[LONGEST_HUMAN_READABLE + 1];
158   int r;
159   int checksum;
160
161   /* The sum of all the input bytes, modulo (UINT_MAX + 1).  */
162   unsigned int s = 0;
163
164   bool is_stdin = STREQ (file, "-");
165
166   if (is_stdin)
167     {
168       fd = STDIN_FILENO;
169       have_read_stdin = true;
170       if (O_BINARY && ! isatty (STDIN_FILENO))
171         freopen (NULL, "rb", stdin);
172     }
173   else
174     {
175       fd = open (file, O_RDONLY | O_BINARY);
176       if (fd == -1)
177         {
178           error (0, errno, "%s", file);
179           return false;
180         }
181     }
182
183   while (1)
184     {
185       size_t i;
186       size_t bytes_read = safe_read (fd, buf, sizeof buf);
187
188       if (bytes_read == 0)
189         break;
190
191       if (bytes_read == SAFE_READ_ERROR)
192         {
193           error (0, errno, "%s", file);
194           if (!is_stdin)
195             close (fd);
196           return false;
197         }
198
199       for (i = 0; i < bytes_read; i++)
200         s += buf[i];
201       total_bytes += bytes_read;
202     }
203
204   if (!is_stdin && close (fd) != 0)
205     {
206       error (0, errno, "%s", file);
207       return false;
208     }
209
210   r = (s & 0xffff) + ((s & 0xffffffff) >> 16);
211   checksum = (r & 0xffff) + (r >> 16);
212
213   printf ("%d %s", checksum,
214           human_readable (total_bytes, hbuf, human_ceiling, 1, 512));
215   if (print_name)
216     printf (" %s", file);
217   putchar ('\n');
218
219   return true;
220 }
221
222 int
223 main (int argc, char **argv)
224 {
225   bool ok;
226   int optc;
227   int files_given;
228   bool (*sum_func) (const char *, int) = bsd_sum_file;
229
230   initialize_main (&argc, &argv);
231   program_name = argv[0];
232   setlocale (LC_ALL, "");
233   bindtextdomain (PACKAGE, LOCALEDIR);
234   textdomain (PACKAGE);
235
236   atexit (close_stdout);
237
238   have_read_stdin = false;
239
240   while ((optc = getopt_long (argc, argv, "rs", longopts, NULL)) != -1)
241     {
242       switch (optc)
243         {
244         case 'r':               /* For SysV compatibility. */
245           sum_func = bsd_sum_file;
246           break;
247
248         case 's':
249           sum_func = sysv_sum_file;
250           break;
251
252         case_GETOPT_HELP_CHAR;
253
254         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
255
256         default:
257           usage (EXIT_FAILURE);
258         }
259     }
260
261   files_given = argc - optind;
262   if (files_given <= 0)
263     ok = sum_func ("-", files_given);
264   else
265     for (ok = true; optind < argc; optind++)
266       ok &= sum_func (argv[optind], files_given);
267
268   if (have_read_stdin && fclose (stdin) == EOF)
269     error (EXIT_FAILURE, errno, "-");
270   exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
271 }