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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
|
/*
*
* Connection Manager
*
* Copyright (C) 2007-2010 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#define _GNU_SOURCE
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/sendfile.h>
#include <sys/socket.h>
#include <linux/if_alg.h>
static void build_hash(int sk, int fd, size_t size, const char *pathname)
{
unsigned char hash[20];
ssize_t written, length;
int i;
written = sendfile(sk, fd, NULL, size);
if (written < 0)
perror("Failed to write data");
printf("send %zd bytes\n", written);
length = recv(sk, hash, sizeof(hash), 0);
if (length < 0)
perror("Failed to read data");
printf("recv %zd bytes\n", length);
for (i = 0; i < length; i++)
printf("%02x", hash[i]);
printf(" %s\n", pathname);
}
static int create_hash(int sk, const char *pathname)
{
struct stat st;
int fd;
fd = open(pathname, O_RDONLY | O_CLOEXEC);
if (fd < 0)
return -1;
if (fstat(fd, &st) < 0) {
close(fd);
return -1;
}
build_hash(sk, fd, st.st_size, pathname);
close(fd);
return 0;
}
static int create_socket(void)
{
struct sockaddr_alg salg = {
.salg_family = AF_ALG,
.salg_type = "hash",
.salg_name = "sha1",
};
int sk, nsk;
sk = socket(PF_ALG, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
if (sk < 0) {
perror("Failed to create socket");
return -1;
}
if (bind(sk, (struct sockaddr *) &salg, sizeof(salg)) < 0) {
perror("Failed to bind socket");
close(sk);
return -1;
}
nsk = accept(sk, NULL, 0);
if (nsk < 0) {
perror("Failed to accept socket");
close(sk);
return -1;
}
close(sk);
return nsk;
}
int main(int argc, char *argv[])
{
int sk;
if (argc < 2) {
fprintf(stderr, "Missing argument\n");
return 1;
}
sk = create_socket();
if (sk < 0)
return 1;
create_hash(sk, argv[1]);
close(sk);
return 0;
}
|