added lots of new code...
[util-vserver.git] / util-vserver / src / vhashify.c
1 // $Id$    --*- c -*--
2
3 // Copyright (C) 2005 Enrico Scholz <enrico.scholz@informatik.tu-chemnitz.de>
4 //  
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.
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, write to the Free Software
16 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17
18
19 #ifdef HAVE_CONFIG_H
20 #  include <config.h>
21 #endif
22
23 #include "vhashify.h"
24 #include "util.h"
25
26 #include "lib/internal.h"
27 #include "lib_internal/matchlist.h"
28 #include "lib_internal/unify.h"
29 #include "ensc_vector/vector.h"
30
31 #include <beecrypt/beecrypt.h>
32
33 #include <setjmp.h>
34 #include <unistd.h>
35 #include <getopt.h>
36 #include <string.h>
37 #include <assert.h>
38 #include <stdlib.h>
39 #include <fcntl.h>
40 #include <dirent.h>
41 #include <errno.h>
42 #include <signal.h>
43 #include <limits.h>
44 #include <sys/mman.h>
45 #include <sys/stat.h>
46
47 #define ENSC_WRAPPERS_STDLIB    1
48 #define ENSC_WRAPPERS_UNISTD    1
49 #define ENSC_WRAPPERS_FCNTL     1
50 #define ENSC_WRAPPERS_DIRENT    1
51 #define ENSC_WRAPPERS_IO        1
52 #include <wrappers.h>
53
54
55 #define HASH_BLOCKSIZE          0x10000000u
56 #define HASH_MINSIZE            0x10
57 #define HASH_MAXBITS            256             // we have to take care about
58                                                 // max filename-length...
59
60 #if HASH_MINSIZE<=0
61 #  error HASH_MINSIZE must be not '0'
62 #endif
63
64
65 #define CMD_HELP                0x8000
66 #define CMD_VERSION             0x8001
67
68 #define CMD_DESTINATION         0x1000
69 #define CMD_INSECURE            0x1001
70 #define CMD_SLEDGE              0x1002
71 #define CMD_MANUALLY            0x1003
72 #define CMD_REFRESH             0x1004
73
74 struct option const
75 CMDLINE_OPTIONS[] = {
76   { "help",         no_argument,        0, CMD_HELP },
77   { "version",      no_argument,        0, CMD_VERSION },
78   { "destination",  required_argument,  0, CMD_DESTINATION },
79   { "insecure",     no_argument,        0, CMD_INSECURE },
80   { "sledgehammer", no_argument,        0, CMD_SLEDGE },
81   { "manually",     no_argument,        0, CMD_MANUALLY },
82   { "refresh",      no_argument,        0, CMD_REFRESH },
83   { "dry-run",      no_argument,        0, 'n' },
84   { "verbose",      no_argument,        0, 'v' },
85   { 0,0,0,0 }
86 };
87
88   // hash digest grouped by 2 digits + hash-collision counter + 2* '/' + NULL
89 typedef char                    HashPath[HASH_MAXBITS/4 + (HASH_MAXBITS/4/2) +
90                                          sizeof(unsigned int)*2 + 3];
91
92 struct HashDirConfiguration
93 {
94     hashFunction const                          *method;
95     enum { hshALL=0, hshSTART = 1, hshMIDDLE=2,
96            hshEND = 4, hshINVALID = -1 }        blocks;
97     size_t                                      blocksize;
98 };
99
100 struct WalkdownInfo
101 {
102     PathInfo                    state;
103     struct MatchList            dst_list;
104     struct HashDirConfiguration hash_conf;
105     HashDirCollection           hash_dirs;
106     size_t                      hash_dirs_max_size;
107
108     hashFunctionContext         hash_context;
109 };
110
111 int                             wrapper_exit_code = 1;
112 struct Arguments const          *global_args;
113 static struct SkipReason        skip_reason;
114
115 struct WalkdownInfo             global_info = {
116   .hash_conf = { .method     = 0,
117                  .blocks     = hshALL,
118                  .blocksize  = 0x10000 }
119 };
120
121 #include "vhashify-init.hc"
122
123 int Global_getVerbosity() {
124   return global_args->verbosity;
125 }
126
127 int Global_doRenew() {
128   return true;
129 }
130
131 int Global_isVserverRunning() {
132     // TODO
133   return global_args->insecure<2;
134 }
135
136 static void
137 showHelp(char const *cmd)
138 {
139   WRITE_MSG(1, "Usage:\n  ");
140   WRITE_STR(1, cmd);
141   WRITE_MSG(1,
142             " [-nv] [--refresh] <vserver>\n    or\n  ");
143   WRITE_STR(1, cmd);
144   WRITE_MSG(1,
145             " --manually [-nv] [--] <hashdir> <path> <excludelist>\n\n"
146             "  --manually      ...  hashify generic paths; excludelists must be generated\n"
147             "                       manually\n"
148             "  --refresh       ...  hashify already hashified files also\n"
149             "  -n              ...  do not modify anything; just show what there will be\n"
150             "                       done (in combination with '-v')\n"
151             "  -v              ...  verbose mode\n"
152             "Please report bugs to " PACKAGE_BUGREPORT "\n");
153
154   exit(0);
155 }
156
157 static void
158 showVersion()
159 {
160   WRITE_MSG(1,
161             "vhashify " VERSION " -- hashifies vservers and/or directories\n"
162             "This program is part of " PACKAGE_STRING "\n\n"
163             "Copyright (C) 2005 Enrico Scholz\n"
164             VERSION_COPYRIGHT_DISCLAIMER);
165   exit(0);
166 }
167
168 int
169 HashDirInfo_compareDevice(void const *lhs_v, void const *rhs_v)
170 {
171   struct HashDirInfo const * const      lhs = lhs_v;
172   dev_t const * const                   rhs = rhs_v;
173
174   assert(lhs!=0 && rhs!=0);
175   return lhs->device - *rhs;
176 }
177
178 PathInfo const *
179 HashDirInfo_findDevice(HashDirCollection const *coll, dev_t dev)
180 {
181   struct HashDirInfo const      *res;
182
183   res = Vector_searchSelfOrg_const(coll, &dev,
184                                    HashDirInfo_compareDevice, vecSHIFT_ONCE);
185
186   if (res!=0) return &res->path;
187   else        return 0;
188 }
189
190 #include "vserver-visitdir.hc"
191
192 static bool
193 checkFstat(PathInfo const * const basename,
194            struct stat * const st)
195 {
196   assert(basename->d[0] != '/');
197
198     // local file does not exist... strange
199     // TODO: message
200   skip_reason.r = rsFSTAT;
201   if (lstat(basename->d, st)==-1) return false;
202
203     // this is a directory and succeeds everytime
204   if (S_ISDIR(st->st_mode))
205     return true;
206
207     // ignore symlinks
208   skip_reason.r = rsSYMLINK;
209   if (S_ISLNK(st->st_mode))       return false;
210
211     // ignore special files
212   skip_reason.r = rsSPECIAL;
213   if (!S_ISREG(st->st_mode) &&
214       !S_ISDIR(st->st_mode))      return false;
215   
216     // ignore small files
217   skip_reason.r = rsTOOSMALL;
218   if (st->st_size < HASH_MINSIZE) return false;
219   
220   switch (Unify_isIUnlinkable(basename->d)) {
221     case unifyUNSUPPORTED       :  skip_reason.r = rsUNSUPPORTED; return false;
222     case unifyBUSY              :
223         // do an implicit refresh on busy files when there are no active links
224       if (st->st_nlink>1 && !global_args->do_refresh) {
225           // TODO: message
226         skip_reason.r = rsUNIFIED;
227         return false;
228       }
229       break;
230     default                     :  break;
231   }
232
233   return true;
234 }
235
236 static jmp_buf                  bus_error_restore;
237 static volatile sig_atomic_t    bus_error;
238
239 static void
240 handlerSIGBUS(int UNUSED num)
241 {
242   bus_error = 1;
243   longjmp(bus_error_restore, 1);
244 }
245
246 static bool
247 convertDigest(HashPath d_path)
248 {
249   static char const             HEX_DIGIT[] = "0123456789abcdef";
250   hashFunctionContext * const   h_ctx    = &global_info.hash_context;
251   size_t                        d_size   = h_ctx->algo->digestsize;
252     
253   unsigned char                 digest[d_size];
254   size_t                        out = 0;
255
256   if (hashFunctionContextDigest(h_ctx, digest)==-1)
257     return false;
258   
259   for (size_t in=0;
260        out+1<sizeof(HashPath)-(sizeof(unsigned int)*2 + 2) && in<d_size;
261        ++in) {
262     if ((in+254)%(in<=2 ? 1 : 256) == 0 && in>0)
263       d_path[out++]='/';
264     d_path[out++]  = HEX_DIGIT[digest[in] >>    4];
265     d_path[out++]  = HEX_DIGIT[digest[in] &  0x0f];
266   }
267   d_path[out++] = '\0';
268   
269   return true;
270 }
271
272 static bool
273 addStatHash(hashFunctionContext *h_ctx, struct stat const * const st)
274 {
275 #define DECL_ATTR(X)    __typeof__(st->st_##X)  X
276 #define SET_ATTR(X)     .X = st->st_##X
277   
278   struct __attribute__((__packed__)) {
279     DECL_ATTR(mode);
280     DECL_ATTR(uid);
281     DECL_ATTR(gid);
282     DECL_ATTR(rdev);
283     DECL_ATTR(size);
284     DECL_ATTR(mtime);
285   }             tmp = {
286     SET_ATTR(mode),
287     SET_ATTR(uid),
288     SET_ATTR(gid),
289     SET_ATTR(rdev),
290     SET_ATTR(size),
291     SET_ATTR(mtime)
292   };
293
294   return hashFunctionContextUpdate(h_ctx, (void *)&tmp, sizeof tmp)!=-1;
295 }
296
297 static bool
298 calculateHashFromFD(int fd, HashPath d_path, struct stat const * const st)
299 {
300   hashFunctionContext * const   h_ctx    = &global_info.hash_context;
301   bool                          res      = false;
302   loff_t                        offset   = 0;
303   void                          *buf     = 0;
304   off_t                         size     = st->st_size;
305   loff_t                        cur_size = 0;
306
307
308   if (hashFunctionContextReset(h_ctx)==-1 ||
309       !addStatHash(h_ctx, st))
310     return false;
311
312   bus_error = 0;
313   if (setjmp(bus_error_restore)!=0) goto out;
314
315   while (offset < size) {
316     cur_size = size-offset;
317     if (cur_size>HASH_BLOCKSIZE) cur_size = HASH_BLOCKSIZE;
318
319     buf     = mmap(0, cur_size, PROT_READ, MAP_SHARED, fd, offset);
320     if (buf==0) goto out;
321     
322     offset += cur_size;
323     madvise(buf, cur_size, MADV_SEQUENTIAL);    // ignore error...
324
325     if (hashFunctionContextUpdate(h_ctx, buf, cur_size)==-1) goto out;
326
327     munmap(buf, cur_size);
328     buf = 0;
329   }
330
331   if (!convertDigest(d_path)) goto out;
332     
333   res = true;
334
335   out:
336   if (buf!=0) munmap(buf, cur_size);
337   return res;
338 }
339
340 static bool
341 calculateHash(PathInfo const *filename, HashPath d_path, struct stat const * const st)
342 {
343   int           fd  = open(filename->d, O_NOFOLLOW|O_NONBLOCK|O_RDONLY|O_NOCTTY);
344   struct stat   fst;
345   bool          res = false;
346
347   do {
348     if (fd==-1) {
349       int       old_errno = errno;
350       WRITE_MSG(2, "Failed to open '");
351       WRITE_STR(2, filename->d);
352       errno = old_errno;
353       perror("'");
354       break;;
355     }
356   
357     if (fstat(fd, &fst)==-1 ||
358         fst.st_dev!=st->st_dev || fst.st_ino!=st->st_ino) {
359       WRITE_MSG(2, "An unexpected event occured while stating '");
360       WRITE_STR(2, filename->d);
361       WRITE_MSG(2, "'.\n");
362       break;
363     }
364
365     if (!calculateHashFromFD(fd, d_path, st)) {
366       WRITE_MSG(2, "Failed to calculate hash for '");
367       WRITE_STR(2, filename->d);
368       WRITE_MSG(2, "'.\n");
369       break;
370     }
371
372     res = true;
373   } while (false);
374   
375   if (fd!=-1) close(fd);
376   return res;
377 }
378
379 static bool
380 mkdirRecursive(char const *path)
381 {
382   struct stat           st;
383
384   if (path[0]!='/')        return false; // only absolute paths
385   if (lstat(path,&st)!=-1) return true;
386
387   char                  buf[strlen(path)+1];
388   char *                ptr = buf+1;
389   
390   strcpy(buf, path);
391
392   while ((ptr = strchr(ptr, '/'))!=0) {
393     *ptr = '\0';
394     if (mkdir(buf, 0700)==-1 && errno!=EEXIST) {
395       int               old_errno = errno;
396       WRITE_MSG(2, "mkdir('");
397       WRITE_STR(2, buf);
398       errno = old_errno;
399       perror("')");
400       return false;
401     }
402     *ptr = '/';
403     ++ptr;
404   }
405
406   return true;
407 }
408
409 static bool
410 resolveCollisions(char *result, PathInfo const *root, HashPath d_path,
411                   struct stat *st, struct stat *hash_st)
412 {
413   strcpy(result, root->d);      // 'root' ends on '/' already (see initHashList())
414   strcat(result, d_path);
415   
416   char                  *ptr = result + strlen(result);
417   unsigned int          idx  = 0;
418   char                  buf[sizeof(int)*2 + 1];
419   size_t                len;
420
421   *ptr++             = '-';
422   *ptr               = '\0';
423   ptr[sizeof(int)*2] = '\0';
424
425   if (!global_args->dry_run &&
426       !mkdirRecursive(result))
427     return false;
428
429   for (;; ++idx) {
430     len = utilvserver_fmt_xuint(buf, idx);
431     memset(ptr, '0', sizeof(int)*2 - len);
432     memcpy(ptr + sizeof(int)*2 - len, buf, len);
433
434     if (lstat(result, hash_st)==-1) {
435       if (global_args->dry_run && errno!=ENOENT) {
436         int             old_errno = errno;
437         WRITE_MSG(2, "lstat('");
438         WRITE_STR(2, buf);
439         errno = old_errno;
440         perror("')");
441         return false;
442       }
443     }
444     else if (Unify_isUnified(st, hash_st)) {
445       skip_reason.r = rsUNIFIED;
446       return false;
447     }
448     else if (!Unify_isUnifyable(st, hash_st))
449       continue;         // continue with next number*****
450     else
451       break;            // ok, we finish here
452
453     if (!global_args->dry_run) {
454       int               fd = open(result, O_NOFOLLOW|O_EXCL|O_CREAT|O_WRONLY, 0200);
455
456       if (global_args->dry_run && fd==-1) {
457         int             old_errno = errno;
458         WRITE_MSG(2, "open('");
459         WRITE_STR(2, buf);
460         errno = old_errno;
461         perror("')");
462         return false;
463       }
464
465       close(fd);
466     }
467
468       // HACK: avoid an additional lstat on the resulting hash-file
469     hash_st->st_size = 0;
470     break;
471   }
472
473   return true;
474 }
475
476 static char const *
477 checkDirEntry(PathInfo const *path, PathInfo const *basename,
478               bool *is_dir,
479               struct stat *st, struct stat *hash_st,
480               char *result_buf)
481 {
482     //printf("checkDirEntry(%s, %s, %u)\n", path->d, d_path, is_dir);
483
484   struct WalkdownInfo const * const     info       = &global_info;
485
486   // Check if it is in the exclude/include list of the destination vserver and
487   // abort when it is not matching an allowed entry
488   skip_reason.r      = rsEXCL;
489   if (MatchList_compare(&info->dst_list, path->d)!=stINCLUDE) return 0;
490
491   if (checkFstat(basename, st)) {
492     PathInfo const      *hash_root_path;
493     HashPath            d_path;
494     
495     *is_dir = S_ISDIR(st->st_mode);
496
497     if (!*is_dir &&
498         !((skip_reason.r = rsWRONGDEV,
499            (hash_root_path = HashDirInfo_findDevice(&info->hash_dirs, st->st_dev))!=0) &&
500           (skip_reason.r = rsGENERAL,
501            calculateHash(basename, d_path, st)) &&
502           resolveCollisions(result_buf, hash_root_path, d_path, st, hash_st)))
503       return 0;
504
505     return result_buf;
506   }
507
508   return 0;
509 }
510
511 static void
512 printSkipReason()
513 {
514   WRITE_MSG(1, " (");
515   switch (skip_reason.r) {
516     case rsDOTFILE      :  WRITE_MSG(1, "dotfile"); break;
517     case rsEXCL         :  WRITE_MSG(1, "excluded"); break;
518     case rsTOOSMALL     :  WRITE_MSG(1, "too small"); break;
519     case rsUNSUPPORTED  :  WRITE_MSG(1, "operation not supported"); break;
520     case rsFSTAT        :  WRITE_MSG(1, "fstat error"); break;
521     case rsSYMLINK      :  WRITE_MSG(1, "symlink"); break;
522     case rsUNIFIED      :  WRITE_MSG(1, "already unified"); break;
523     case rsSPECIAL      :  WRITE_MSG(1, "non regular file"); break;
524     case rsWRONGDEV     :  WRITE_MSG(1, "no matching device"); break;
525     case rsGENERAL      :  WRITE_MSG(1, "general error"); break;
526     default             :  assert(false); abort();
527   }
528   WRITE_MSG(1, ")");
529 }
530
531 static bool
532 doit(char const *src, char const *dst,
533      struct stat const *src_st, struct stat const *dst_st,
534      PathInfo const *path)
535 {
536   if (global_args->dry_run || Global_getVerbosity()>=2) {
537     WRITE_MSG(1, "unifying   '");
538     Vwrite(1, path->d, path->l);
539     WRITE_MSG(1, "'");
540     
541     if (Global_getVerbosity()>=4) {
542       WRITE_MSG(1, " (to '");
543       WRITE_STR(1, dst);
544       WRITE_MSG(1, "')");
545     }
546
547     WRITE_MSG(1, "\n");
548   }
549
550     // abort here in dry-run mode
551   if (global_args->dry_run) return true;
552
553   if (dst_st->st_size==0) {
554       // file was not unified yet
555     
556     if (Global_isVserverRunning()) {
557       (void)unlink(dst);
558       if (Unify_copy (src, src_st, dst) &&
559           // the mixed 'dst' and 'src_st' params are intentionally...
560           Unify_unify(dst, src_st, src, false))
561         return true;
562     }
563     else if (Unify_unify(src, src_st, dst, true))
564       return true;
565
566     (void)unlink(dst);  // cleanup in error-case
567   }
568     // there exists already a reference-file
569   else if (Unify_unify(dst, dst_st, src, false))
570     return true;
571
572   return false;
573 }
574
575 static uint64_t
576 visitDirEntry(struct dirent const *ent)
577 {
578   uint64_t                      res      = 0;
579   char const *                  dirname  = ent->d_name;
580   PathInfo                      path     = global_info.state;
581   PathInfo                      tmp_path = {
582     .d = dirname,
583     .l = strlen(dirname)
584   };
585   char                          path_buf[ENSC_PI_APPSZ(path, tmp_path)];
586   char const                    *match = 0;
587
588   
589   PathInfo_append(&path, &tmp_path, path_buf);
590
591   bool                          is_dotfile    = isDotfile(dirname);
592   bool                          is_dir;
593   struct stat                   src_stat = { .st_mode=0 };
594   struct stat                   hash_stat;
595   char                          tmpbuf[global_info.hash_dirs_max_size +
596                                        sizeof(HashPath) + 2];
597   
598   skip_reason.r = rsDOTFILE;
599
600   if (is_dotfile ||
601       (match=checkDirEntry(&path, &tmp_path,
602                            &is_dir, &src_stat, &hash_stat,
603                            tmpbuf))==0) {
604
605     bool        is_link = !is_dotfile && S_ISLNK(src_stat.st_mode);
606
607     if (Global_getVerbosity()>=1 &&
608         (Global_getVerbosity()>=3 || skip_reason.r!=rsUNIFIED) &&
609         ((!is_dotfile && !is_link) ||
610          (Global_getVerbosity()>=6 && is_dotfile) ||
611          (Global_getVerbosity()>=6 && is_link)) ) {
612       WRITE_MSG(1, "  skipping '");
613       Vwrite(1, path.d, path.l);
614       WRITE_MSG(1, "'");
615       if (Global_getVerbosity()>=2) printSkipReason();
616       WRITE_MSG(1, "\n");
617     }
618
619     return 0;
620   }
621
622   if (is_dir) {
623     res = visitDir(dirname, &src_stat);
624   }
625   else if (doit(dirname, match, &src_stat, &hash_stat, &path))
626     res = 1;
627   else {
628       // TODO: message
629     res = 0;
630   }
631
632   return res;
633     
634 }
635
636 int main(int argc, char *argv[])
637 {
638   struct Arguments      args = {
639     .mode               =  mdVSERVER,
640     .hash_dir           =  0,
641     .verbosity          =  0,
642     .insecure           =  0,
643     .dry_run            =  false,
644     .do_refresh         =  false,
645   };
646
647   Vector_init(&global_info.hash_dirs, sizeof(struct HashDirInfo));
648
649   global_args = &args;
650   while (1) {
651     int         c = getopt_long(argc, argv, "+nv",
652                                 CMDLINE_OPTIONS, 0);
653     if (c==-1) break;
654
655     switch (c) {
656       case CMD_HELP             :  showHelp(argv[0]);
657       case CMD_VERSION          :  showVersion();
658       case CMD_DESTINATION      :  args.hash_dir    = optarg; break;
659       case CMD_MANUALLY         :  args.mode        = mdMANUALLY; break;
660       case CMD_INSECURE         :  args.insecure    = 1;    break;
661       case CMD_SLEDGE           :  args.insecure    = 2;    break;
662       case CMD_REFRESH          :  args.do_refresh  = true; break;
663       case 'n'                  :  args.dry_run     = true; break;
664       case 'v'                  :  ++args.verbosity; break;
665       default           :
666         WRITE_MSG(2, "Try '");
667         WRITE_STR(2, argv[0]);
668         WRITE_MSG(2, " --help\" for more information.\n");
669         return EXIT_FAILURE;
670         break;
671     }
672   }
673
674   if (argc==optind) {
675     WRITE_MSG(2, "No directory/vserver given\n");
676     return EXIT_FAILURE;
677   }
678
679   if (args.hash_dir==0 && args.mode==mdMANUALLY) {
680     WRITE_MSG(2, "'--manually' requires '--destination'\n");
681     return EXIT_FAILURE;
682   }
683
684   switch (args.mode) {
685     case mdMANUALLY     :  initModeManually(&args, argc-optind, argv+optind); break;
686     case mdVSERVER      :  initModeVserver (&args, argc-optind, argv+optind); break;
687     default             :  assert(false); return EXIT_FAILURE;
688   };
689
690   if (hashFunctionContextInit(&global_info.hash_context,
691                               global_info.hash_conf.method)==-1) {
692     WRITE_MSG(2, "Failed to initialize hash-context\n");
693     return EXIT_FAILURE;
694   }
695
696   if (Global_getVerbosity()>=1)
697     WRITE_MSG(1, "Starting to traverse directories...\n");
698
699   signal(SIGBUS, handlerSIGBUS);
700   
701   Echdir(global_info.dst_list.root.d);
702   visitDir("/", 0);
703
704 #ifndef NDEBUG
705   MatchList_destroy(&global_info.dst_list);
706   freeHashList(&global_info.hash_dirs);
707   hashFunctionContextFree(&global_info.hash_context);
708 #endif
709 }