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
|
#include <sys/mman.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <stdint.h>
#include <stdio.h>
#include "package.h"
#include "extract.h"
#define MMAPSIZE (100*1024*1024)
#define BUFSIZE (1024*1024)
int copy_file(const char *src, const char *dst, uint32_t l) {
int sfd = -1, dfd = -1, r = -1;
uint32_t m;
off_t o;
void *src_p, *dst_p;
void *buf = NULL;
if ((sfd = open(src, O_RDONLY)) < 0) {
fprintf(stderr, "open(%s, O_RDONLY): %s\n", src, strerror(errno));
goto finish;
}
if ((dfd = open(dst, O_RDWR|O_TRUNC|O_CREAT, 0666)) < 0) {
fprintf(stderr, "open(%s, O_WRONLY): %s\n", dst, strerror(errno));
goto finish;
}
if (ftruncate(dfd, l) < 0) {
fprintf(stderr, "ftruncate(): %s\n", strerror(errno));
goto finish;
}
o = 0;
m = l < MMAPSIZE ? l : MMAPSIZE;
while (l > 0) {
if ((src_p = mmap(NULL, m, PROT_READ, MAP_SHARED, sfd, o)) == MAP_FAILED)
break;
if ((dst_p = mmap(NULL, m, PROT_READ|PROT_WRITE, MAP_SHARED, dfd, o)) == MAP_FAILED) {
munmap(src_p, m);
break;
}
memcpy(dst_p, src_p, m);
munmap(src_p, m);
munmap(dst_p, m);
o += m;
l -= m;
m = l < MMAPSIZE ? l : MMAPSIZE;
}
if (l > 0) {
fprintf(stderr, "mmap() failed: %s\n", strerror(errno));
if (!(buf = malloc(BUFSIZE)))
goto finish;
for (;;) {
ssize_t r;
if ((m = read(sfd, buf, BUFSIZE)) < 0) {
fprintf(stderr, "read(): %s\n", strerror(errno));
goto finish;
}
if (!m)
break;
if ((r = write(dfd, buf, m)) < 0) {
fprintf(stderr, "write(): %s\n", strerror(errno));
goto finish;
}
}
}
r = 0;
finish:
if (sfd >= 0)
close(sfd);
if (dfd >= 0)
close(dfd);
return r;
}
static int cb(struct package *p, const char *name, const char *path, void *u) {
struct stat st;
uint32_t size;
if (stat(path, &st) < 0) {
if (errno == ENOENT)
size = 0;
else {
fprintf(stderr, "stat(%s) failed: %s\n", path, strerror(errno));
return -1;
}
} else
size = (uint32_t) st.st_size;
if (size)
return copy_file(path, name, size);
return 0;
}
int extract(struct syrep_db_context *context) {
return package_foreach(context->package, cb, NULL);
}
|