3 // Copyright (C) 2005 Enrico Scholz <enrico.scholz@informatik.tu-chemnitz.de>
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; version 2 of the License.
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.
14 // You should have received a copy of the GNU General Public License
15 // along with this program; if not, write to the Free Software
16 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26 #include "lib/internal.h"
27 #include "lib_internal/matchlist.h"
28 #include "lib_internal/unify.h"
29 #include "ensc_vector/vector.h"
31 #include <beecrypt/beecrypt.h>
47 #define ENSC_WRAPPERS_STDLIB 1
48 #define ENSC_WRAPPERS_UNISTD 1
49 #define ENSC_WRAPPERS_FCNTL 1
50 #define ENSC_WRAPPERS_DIRENT 1
54 #define HASH_BLOCKSIZE 0x10000000u
55 #define HASH_MINSIZE 0x10
58 # error HASH_MINSIZE must be not '0'
62 #define CMD_HELP 0x8000
63 #define CMD_VERSION 0x8001
65 #define CMD_DESTINATION 0x1000
66 #define CMD_INSECURE 0x1001
67 #define CMD_SLEDGE 0x1002
68 #define CMD_MANUALLY 0x1003
69 #define CMD_REFRESH 0x1004
73 { "help", no_argument, 0, CMD_HELP },
74 { "version", no_argument, 0, CMD_VERSION },
75 { "destination", required_argument, 0, CMD_DESTINATION },
76 { "insecure", no_argument, 0, CMD_INSECURE },
77 { "sledgehammer", no_argument, 0, CMD_SLEDGE },
78 { "manually", no_argument, 0, CMD_MANUALLY },
79 { "refresh", no_argument, 0, CMD_REFRESH },
80 { "dry-run", no_argument, 0, 'n' },
81 { "verbose", no_argument, 0, 'v' },
85 // SHA1, grouped by 4 digits + hash-collision counter + 2* '/' + NULL
86 typedef char HashPath[160/4 + (160/4/4) + sizeof(unsigned int)*2 + 3];
91 struct MatchList dst_list;
92 HashDirCollection hash_dirs;
93 size_t hash_dirs_max_size;
95 hashFunctionContext hash_context;
98 int wrapper_exit_code = 1;
99 struct Arguments const *global_args;
100 struct WalkdownInfo global_info;
101 static struct SkipReason skip_reason;
103 #include "vhashify-init.hc"
105 int Global_getVerbosity() {
106 return global_args->verbosity;
109 int Global_doRenew() {
113 int Global_isVserverRunning() {
115 return global_args->insecure<2;
119 showHelp(char const *cmd)
121 WRITE_MSG(1, "Usage:\n ");
124 " [-nv] [--refresh] <vserver>\n or\n ");
127 " --manually [-nv] [--] <hashdir> <path> <excludelist>\n\n"
128 " --manually ... hashify generic paths; excludelists must be generated\n"
130 " --refresh ... hashify already hashified files also\n"
131 " -n ... do not modify anything; just show what there will be\n"
132 " done (in combination with '-v')\n"
133 " -v ... verbose mode\n"
134 "Please report bugs to " PACKAGE_BUGREPORT "\n");
143 "vhashify " VERSION " -- hashifies vservers and/or directories\n"
144 "This program is part of " PACKAGE_STRING "\n\n"
145 "Copyright (C) 2005 Enrico Scholz\n"
146 VERSION_COPYRIGHT_DISCLAIMER);
151 HashDirInfo_compareDevice(void const *lhs_v, void const *rhs_v)
153 struct HashDirInfo const * const lhs = lhs_v;
154 dev_t const * const rhs = rhs_v;
156 assert(lhs!=0 && rhs!=0);
157 return lhs->device - *rhs;
161 HashDirInfo_findDevice(HashDirCollection const *coll, dev_t dev)
163 struct HashDirInfo const *res;
165 res = Vector_searchSelfOrg_const(coll, &dev,
166 HashDirInfo_compareDevice, vecSHIFT_ONCE);
168 if (res!=0) return &res->path;
172 #include "vserver-visitdir.hc"
175 checkFstat(PathInfo const * const basename,
176 struct stat * const st)
178 assert(basename->d[0] != '/');
180 // local file does not exist... strange
182 skip_reason.r = rsFSTAT;
183 if (lstat(basename->d, st)==-1) return false;
185 // this is a directory and succeeds everytime
186 if (S_ISDIR(st->st_mode))
190 skip_reason.r = rsSYMLINK;
191 if (S_ISLNK(st->st_mode)) return false;
193 // ignore special files
194 skip_reason.r = rsSPECIAL;
195 if (!S_ISREG(st->st_mode) &&
196 !S_ISDIR(st->st_mode)) return false;
198 // ignore small files
199 skip_reason.r = rsTOOSMALL;
200 if (st->st_size < HASH_MINSIZE) return false;
202 switch (Unify_isIUnlinkable(basename->d)) {
203 case unifyUNSUPPORTED : skip_reason.r = rsUNSUPPORTED; return false;
205 // do an implicit refresh on busy files when there are no active links
206 if (st->st_nlink>1 && !global_args->do_refresh) {
208 skip_reason.r = rsUNIFIED;
218 static jmp_buf bus_error_restore;
219 static volatile sig_atomic_t bus_error;
222 handlerSIGBUS(int UNUSED num)
225 longjmp(bus_error_restore, 1);
229 convertDigest(HashPath d_path)
231 static char const HEX_DIGIT[] = "0123456789abcdef";
232 hashFunctionContext * const h_ctx = &global_info.hash_context;
233 size_t d_size = h_ctx->algo->digestsize;
235 unsigned char digest[d_size];
238 if (hashFunctionContextDigest(h_ctx, digest)==-1)
242 out+1<sizeof(HashPath)-(sizeof(unsigned int)*2 + 2) && in<d_size;
244 if (in%2 == 0 && in>0) d_path[out++]='/';
245 d_path[out++] = HEX_DIGIT[digest[in] >> 4];
246 d_path[out++] = HEX_DIGIT[digest[in] & 0x0f];
248 d_path[out++] = '\0';
254 addStatHash(hashFunctionContext *h_ctx, struct stat const * const st)
256 #define DECL_ATTR(X) __typeof__(st->st_##X) X
257 #define SET_ATTR(X) .X = st->st_##X
259 struct __attribute__((__packed__)) {
275 return hashFunctionContextUpdate(h_ctx, (void *)&tmp, sizeof tmp)!=-1;
279 calculateHashFromFD(int fd, HashPath d_path, struct stat const * const st)
281 hashFunctionContext * const h_ctx = &global_info.hash_context;
285 off_t size = st->st_size;
289 if (hashFunctionContextReset(h_ctx)==-1 ||
290 !addStatHash(h_ctx, st))
294 if (setjmp(bus_error_restore)!=0) goto out;
296 while (offset < size) {
297 cur_size = size-offset;
298 if (cur_size>HASH_BLOCKSIZE) cur_size = HASH_BLOCKSIZE;
300 buf = mmap(0, cur_size, PROT_READ, MAP_SHARED, fd, offset);
301 if (buf==0) goto out;
304 madvise(buf, cur_size, MADV_SEQUENTIAL); // ignore error...
306 if (hashFunctionContextUpdate(h_ctx, buf, cur_size)==-1) goto out;
308 munmap(buf, cur_size);
312 if (!convertDigest(d_path)) goto out;
317 if (buf!=0) munmap(buf, cur_size);
322 calculateHash(PathInfo const *filename, HashPath d_path, struct stat const * const st)
324 int fd = open(filename->d, O_NOFOLLOW|O_NONBLOCK|O_RDONLY|O_NOCTTY);
330 int old_errno = errno;
331 WRITE_MSG(2, "Failed to open '");
332 WRITE_STR(2, filename->d);
338 if (fstat(fd, &fst)==-1 ||
339 fst.st_dev!=st->st_dev || fst.st_ino!=st->st_ino) {
340 WRITE_MSG(2, "An unexpected event occured while stating '");
341 WRITE_STR(2, filename->d);
342 WRITE_MSG(2, "'.\n");
346 if (!calculateHashFromFD(fd, d_path, st)) {
347 WRITE_MSG(2, "Failed to calculate hash for '");
348 WRITE_STR(2, filename->d);
349 WRITE_MSG(2, "'.\n");
356 if (fd!=-1) close(fd);
361 mkdirRecursive(char const *path)
365 if (path[0]!='/') return false; // only absolute paths
366 if (lstat(path,&st)!=-1) return true;
368 char buf[strlen(path)+1];
373 while ((ptr = strchr(ptr, '/'))!=0) {
375 if (mkdir(buf, 0700)==-1 && errno!=EEXIST) {
376 int old_errno = errno;
377 WRITE_MSG(2, "mkdir('");
391 resolveCollisions(char *result, PathInfo const *root, HashPath d_path,
392 struct stat *st, struct stat *hash_st)
394 strcpy(result, root->d); // 'root' ends on '/' already (see initHashList())
395 strcat(result, d_path);
397 char *ptr = result + strlen(result);
398 unsigned int idx = 0;
399 char buf[sizeof(int)*2 + 1];
404 ptr[sizeof(int)*2] = '\0';
406 if (!global_args->dry_run &&
407 !mkdirRecursive(result))
411 len = utilvserver_fmt_xuint(buf, idx);
412 memset(ptr, '0', sizeof(int)*2 - len);
413 memcpy(ptr + sizeof(int)*2 - len, buf, len);
415 if (lstat(result, hash_st)==-1) {
416 if (global_args->dry_run && errno!=ENOENT) {
417 int old_errno = errno;
418 WRITE_MSG(2, "lstat('");
425 else if (Unify_isUnified(st, hash_st)) {
426 skip_reason.r = rsUNIFIED;
429 else if (!Unify_isUnifyable(st, hash_st))
430 continue; // continue with next number*****
432 break; // ok, we finish here
434 if (!global_args->dry_run) {
435 int fd = open(result, O_NOFOLLOW|O_EXCL|O_CREAT|O_WRONLY, 0200);
437 if (global_args->dry_run && fd==-1) {
438 int old_errno = errno;
439 WRITE_MSG(2, "open('");
449 // HACK: avoid an additional lstat on the resulting hash-file
450 hash_st->st_size = 0;
458 checkDirEntry(PathInfo const *path, PathInfo const *basename,
460 struct stat *st, struct stat *hash_st,
463 //printf("checkDirEntry(%s, %s, %u)\n", path->d, d_path, is_dir);
465 struct WalkdownInfo const * const info = &global_info;
467 // Check if it is in the exclude/include list of the destination vserver and
468 // abort when it is not matching an allowed entry
469 skip_reason.r = rsEXCL;
470 if (MatchList_compare(&info->dst_list, path->d)!=stINCLUDE) return 0;
472 if (checkFstat(basename, st)) {
473 PathInfo const *hash_root_path;
476 *is_dir = S_ISDIR(st->st_mode);
479 !((skip_reason.r = rsWRONGDEV,
480 (hash_root_path = HashDirInfo_findDevice(&info->hash_dirs, st->st_dev))!=0) &&
481 (skip_reason.r = rsGENERAL,
482 calculateHash(basename, d_path, st)) &&
483 resolveCollisions(result_buf, hash_root_path, d_path, st, hash_st)))
496 switch (skip_reason.r) {
497 case rsDOTFILE : WRITE_MSG(1, "dotfile"); break;
498 case rsEXCL : WRITE_MSG(1, "excluded"); break;
499 case rsTOOSMALL : WRITE_MSG(1, "too small"); break;
500 case rsUNSUPPORTED : WRITE_MSG(1, "operation not supported"); break;
501 case rsFSTAT : WRITE_MSG(1, "fstat error"); break;
502 case rsSYMLINK : WRITE_MSG(1, "symlink"); break;
503 case rsUNIFIED : WRITE_MSG(1, "already unified"); break;
504 case rsSPECIAL : WRITE_MSG(1, "non regular file"); break;
505 case rsWRONGDEV : WRITE_MSG(1, "no matching device"); break;
506 case rsGENERAL : WRITE_MSG(1, "general error"); break;
507 default : assert(false); abort();
513 doit(char const *src, char const *dst,
514 struct stat const *src_st, struct stat const *dst_st,
515 PathInfo const *path)
517 if (global_args->dry_run || Global_getVerbosity()>=2) {
518 WRITE_MSG(1, "unifying '");
519 (void)write(1, path->d, path->l);
522 if (Global_getVerbosity()>=4) {
523 WRITE_MSG(1, " (to '");
531 // abort here in dry-run mode
532 if (global_args->dry_run) return true;
534 if (dst_st->st_size==0) {
535 // file was not unified yet
537 if (Global_isVserverRunning()) {
539 if (Unify_copy (src, src_st, dst) &&
540 // the mixed 'dst' and 'src_st' params are intentionally...
541 Unify_unify(dst, src_st, src, false))
544 else if (Unify_unify(src, src_st, dst, true))
547 (void)unlink(dst); // cleanup in error-case
549 // there exists already a reference-file
550 else if (Unify_unify(dst, dst_st, src, false))
557 visitDirEntry(struct dirent const *ent)
560 char const * dirname = ent->d_name;
561 PathInfo path = global_info.state;
562 PathInfo tmp_path = {
566 char path_buf[ENSC_PI_APPSZ(path, tmp_path)];
567 char const *match = 0;
570 PathInfo_append(&path, &tmp_path, path_buf);
572 bool is_dotfile = isDotfile(dirname);
574 struct stat src_stat = { .st_mode=0 };
575 struct stat hash_stat;
576 char tmpbuf[global_info.hash_dirs_max_size +
577 sizeof(HashPath) + 2];
579 skip_reason.r = rsDOTFILE;
582 (match=checkDirEntry(&path, &tmp_path,
583 &is_dir, &src_stat, &hash_stat,
586 bool is_link = !is_dotfile && S_ISLNK(src_stat.st_mode);
588 if (Global_getVerbosity()>=1 &&
589 (Global_getVerbosity()>=3 || skip_reason.r!=rsUNIFIED) &&
590 ((!is_dotfile && !is_link) ||
591 (Global_getVerbosity()>=6 && is_dotfile) ||
592 (Global_getVerbosity()>=6 && is_link)) ) {
593 WRITE_MSG(1, " skipping '");
594 write(1, path.d, path.l);
596 if (Global_getVerbosity()>=2) printSkipReason();
604 res = visitDir(dirname, &src_stat);
606 else if (doit(dirname, match, &src_stat, &hash_stat, &path))
617 int main(int argc, char *argv[])
619 struct Arguments args = {
628 Vector_init(&global_info.hash_dirs, sizeof(struct HashDirInfo));
630 if (hashFunctionContextInit(&global_info.hash_context,
631 hashFunctionDefault())==-1)
637 int c = getopt_long(argc, argv, "+nv",
642 case CMD_HELP : showHelp(argv[0]);
643 case CMD_VERSION : showVersion();
644 case CMD_DESTINATION : args.hash_dir = optarg; break;
645 case CMD_MANUALLY : args.mode = mdMANUALLY; break;
646 case CMD_INSECURE : args.insecure = 1; break;
647 case CMD_SLEDGE : args.insecure = 2; break;
648 case CMD_REFRESH : args.do_refresh = true; break;
649 case 'n' : args.dry_run = true; break;
650 case 'v' : ++args.verbosity; break;
652 WRITE_MSG(2, "Try '");
653 WRITE_STR(2, argv[0]);
654 WRITE_MSG(2, " --help\" for more information.\n");
661 WRITE_MSG(2, "No directory/vserver given\n");
665 if (args.hash_dir==0 && args.mode==mdMANUALLY) {
666 WRITE_MSG(2, "'--manually' requires '--destination'\n");
671 case mdMANUALLY : initModeManually(&args, argc-optind, argv+optind); break;
672 case mdVSERVER : initModeVserver (&args, argc-optind, argv+optind); break;
673 default : assert(false); return EXIT_FAILURE;
676 if (Global_getVerbosity()>=1)
677 WRITE_MSG(1, "Starting to traverse directories...\n");
679 signal(SIGBUS, handlerSIGBUS);
681 Echdir(global_info.dst_list.root.d);
685 MatchList_destroy(&global_info.dst_list);
686 freeHashList(&global_info.hash_dirs);
687 hashFunctionContextFree(&global_info.hash_context);