-
Notifications
You must be signed in to change notification settings - Fork 0
/
cksum.c
115 lines (91 loc) · 2.41 KB
/
cksum.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/*
* cksum - report checksum and octet count of file(s)
*
* Version: 2008-1.01
* Build: c89 -o cksum cksum.c
* Source: <http://pdcore.sourceforge.net/>
* Spec: <http://www.opengroup.org/onlinepubs/9699919799/utilities/cksum.html>
*
* This is free and unencumbered software released into the public domain,
* provided "as is", without warranty of any kind, express or implied. See the
* file UNLICENSE and the website <http://unlicense.org> for further details.
*/
#define _POSIX_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <locale.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#define BUFSIZE 4096
static void cksumfile(int fd, char *fn);
static void error(char *s);
static int exitstatus;
int main(int argc, char **argv)
{
int i, fd, hasrun = 0;
char *fn;
setlocale(LC_ALL, "");
for (i = 1; i < argc; i++)
{
fn = argv[i];
if (strcmp(fn, "--") == 0)
continue;
else
{
hasrun = 1;
if (strcmp(fn, "-") == 0)
cksumfile(STDIN_FILENO, "stdin");
else
if ((fd = open(fn, O_RDONLY)) == -1)
error(fn);
else
{
cksumfile(fd, fn);
if (close(fd) == -1)
error(fn);
}
}
}
if (! hasrun)
cksumfile(STDIN_FILENO, "stdin");
return(exitstatus);
}
void cksumfile(int fd, char *fn)
{
unsigned char buf[BUFSIZE];
ssize_t cnt, n;
uint32_t crctab[256], crc, i;
int j;
for (i = 0; i < 256; ++i)
{
for (crc = i << 24, j = 0; j < 8; j++)
crc = (crc << 1) ^ (crc & 0x80000000 ? 0x04c11db7 : 0);
crctab[i] = crc;
}
cnt = crc = 0;
while ((n = read(fd, buf, BUFSIZE)) > 0)
{
cnt += n;
for (i = 0; i < (size_t)n; i++)
crc = crctab[((crc >> 24) ^ buf[i]) & 0xFF] ^ (crc << 8);
}
if (n < 0)
error(fn);
else
{
for (i = cnt; i != 0; i >>= 8)
crc = crctab[((crc >> 24) ^ i) & 0xFF] ^ (crc << 8);
printf("%lu %lu", (unsigned long)~crc, (unsigned long)cnt);
if (fd != STDIN_FILENO)
printf(" %s", fn);
printf("\n");
}
}
void error(char *s)
{
fprintf(stderr, "cksum: %s: %s\n", s, strerror(errno));
exitstatus = 1;
}