maint: update all copyright year number ranges
[platform/upstream/coreutils.git] / src / sum.c
1 /* sum -- checksum and count the blocks in a file
2    Copyright (C) 1986-2013 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 3 of the License, or
7    (at your option) 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, see <http://www.gnu.org/licenses/>.  */
16
17 /* Like BSD sum or SysV sum -r, except like SysV sum if -s option is given. */
18
19 /* Written by Kayvan Aghaiepour and David MacKenzie. */
20
21 #include <config.h>
22
23 #include <stdio.h>
24 #include <sys/types.h>
25 #include <getopt.h>
26 #include "system.h"
27 #include "error.h"
28 #include "fadvise.h"
29 #include "human.h"
30 #include "safe-read.h"
31 #include "xfreopen.h"
32
33 /* The official name of this program (e.g., no 'g' prefix).  */
34 #define PROGRAM_NAME "sum"
35
36 #define AUTHORS \
37   proper_name ("Kayvan Aghaiepour"), \
38   proper_name ("David MacKenzie")
39
40 /* True if any of the files read were the standard input. */
41 static bool have_read_stdin;
42
43 static struct option const longopts[] =
44 {
45   {"sysv", no_argument, NULL, 's'},
46   {GETOPT_HELP_OPTION_DECL},
47   {GETOPT_VERSION_OPTION_DECL},
48   {NULL, 0, NULL, 0}
49 };
50
51 void
52 usage (int status)
53 {
54   if (status != EXIT_SUCCESS)
55     emit_try_help ();
56   else
57     {
58       printf (_("\
59 Usage: %s [OPTION]... [FILE]...\n\
60 "),
61               program_name);
62       fputs (_("\
63 Print checksum and block counts for each FILE.\n\
64 \n\
65   -r              use BSD sum algorithm, use 1K blocks\n\
66   -s, --sysv      use System V sum algorithm, use 512 bytes blocks\n\
67 "), stdout);
68       fputs (HELP_OPTION_DESCRIPTION, stdout);
69       fputs (VERSION_OPTION_DESCRIPTION, stdout);
70       fputs (_("\
71 \n\
72 With no FILE, or when FILE is -, read standard input.\n\
73 "), stdout);
74       emit_ancillary_info ();
75     }
76   exit (status);
77 }
78
79 /* Calculate and print the rotated checksum and the size in 1K blocks
80    of file FILE, or of the standard input if FILE is "-".
81    If PRINT_NAME is >1, print FILE next to the checksum and size.
82    The checksum varies depending on sizeof (int).
83    Return true if successful.  */
84
85 static bool
86 bsd_sum_file (const char *file, int print_name)
87 {
88   FILE *fp;
89   int checksum = 0;     /* The checksum mod 2^16. */
90   uintmax_t total_bytes = 0;    /* The number of bytes. */
91   int ch;               /* Each character read. */
92   char hbuf[LONGEST_HUMAN_READABLE + 1];
93   bool is_stdin = STREQ (file, "-");
94
95   if (is_stdin)
96     {
97       fp = stdin;
98       have_read_stdin = true;
99       if (O_BINARY && ! isatty (STDIN_FILENO))
100         xfreopen (NULL, "rb", stdin);
101     }
102   else
103     {
104       fp = fopen (file, (O_BINARY ? "rb" : "r"));
105       if (fp == NULL)
106         {
107           error (0, errno, "%s", file);
108           return false;
109         }
110     }
111
112   fadvise (fp, FADVISE_SEQUENTIAL);
113
114   while ((ch = getc (fp)) != EOF)
115     {
116       total_bytes++;
117       checksum = (checksum >> 1) + ((checksum & 1) << 15);
118       checksum += ch;
119       checksum &= 0xffff;       /* Keep it within bounds. */
120     }
121
122   if (ferror (fp))
123     {
124       error (0, errno, "%s", file);
125       if (!is_stdin)
126         fclose (fp);
127       return false;
128     }
129
130   if (!is_stdin && fclose (fp) != 0)
131     {
132       error (0, errno, "%s", file);
133       return false;
134     }
135
136   printf ("%05d %5s", checksum,
137           human_readable (total_bytes, hbuf, human_ceiling, 1, 1024));
138   if (print_name > 1)
139     printf (" %s", file);
140   putchar ('\n');
141
142   return true;
143 }
144
145 /* Calculate and print the checksum and the size in 512-byte blocks
146    of file FILE, or of the standard input if FILE is "-".
147    If PRINT_NAME is >0, print FILE next to the checksum and size.
148    Return true if successful.  */
149
150 static bool
151 sysv_sum_file (const char *file, int print_name)
152 {
153   int fd;
154   unsigned char buf[8192];
155   uintmax_t total_bytes = 0;
156   char hbuf[LONGEST_HUMAN_READABLE + 1];
157   int r;
158   int checksum;
159
160   /* The sum of all the input bytes, modulo (UINT_MAX + 1).  */
161   unsigned int s = 0;
162
163   bool is_stdin = STREQ (file, "-");
164
165   if (is_stdin)
166     {
167       fd = STDIN_FILENO;
168       have_read_stdin = true;
169       if (O_BINARY && ! isatty (STDIN_FILENO))
170         xfreopen (NULL, "rb", stdin);
171     }
172   else
173     {
174       fd = open (file, O_RDONLY | O_BINARY);
175       if (fd == -1)
176         {
177           error (0, errno, "%s", file);
178           return false;
179         }
180     }
181
182   while (1)
183     {
184       size_t i;
185       size_t bytes_read = safe_read (fd, buf, sizeof buf);
186
187       if (bytes_read == 0)
188         break;
189
190       if (bytes_read == SAFE_READ_ERROR)
191         {
192           error (0, errno, "%s", file);
193           if (!is_stdin)
194             close (fd);
195           return false;
196         }
197
198       for (i = 0; i < bytes_read; i++)
199         s += buf[i];
200       total_bytes += bytes_read;
201     }
202
203   if (!is_stdin && close (fd) != 0)
204     {
205       error (0, errno, "%s", file);
206       return false;
207     }
208
209   r = (s & 0xffff) + ((s & 0xffffffff) >> 16);
210   checksum = (r & 0xffff) + (r >> 16);
211
212   printf ("%d %s", checksum,
213           human_readable (total_bytes, hbuf, human_ceiling, 1, 512));
214   if (print_name)
215     printf (" %s", file);
216   putchar ('\n');
217
218   return true;
219 }
220
221 int
222 main (int argc, char **argv)
223 {
224   bool ok;
225   int optc;
226   int files_given;
227   bool (*sum_func) (const char *, int) = bsd_sum_file;
228
229   initialize_main (&argc, &argv);
230   set_program_name (argv[0]);
231   setlocale (LC_ALL, "");
232   bindtextdomain (PACKAGE, LOCALEDIR);
233   textdomain (PACKAGE);
234
235   atexit (close_stdout);
236
237   /* Line buffer stdout to ensure lines are written atomically and immediately
238      so that processes running in parallel do not intersperse their output.  */
239   setvbuf (stdout, NULL, _IOLBF, 0);
240
241   have_read_stdin = false;
242
243   while ((optc = getopt_long (argc, argv, "rs", longopts, NULL)) != -1)
244     {
245       switch (optc)
246         {
247         case 'r':               /* For SysV compatibility. */
248           sum_func = bsd_sum_file;
249           break;
250
251         case 's':
252           sum_func = sysv_sum_file;
253           break;
254
255         case_GETOPT_HELP_CHAR;
256
257         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
258
259         default:
260           usage (EXIT_FAILURE);
261         }
262     }
263
264   files_given = argc - optind;
265   if (files_given <= 0)
266     ok = sum_func ("-", files_given);
267   else
268     for (ok = true; optind < argc; optind++)
269       ok &= sum_func (argv[optind], files_given);
270
271   if (have_read_stdin && fclose (stdin) == EOF)
272     error (EXIT_FAILURE, errno, "-");
273   exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
274 }