404c10
/* Copyright (C) 2001 Red Hat, Inc.
404c10
404c10
   Written by Jakub Jelinek <jakub@redhat.com>.
404c10
404c10
   This program is free software; you can redistribute it and/or
404c10
   modify it under the terms of the GNU General Public License as
404c10
   published by the Free Software Foundation; either version 2 of the
404c10
   License, or (at your option) any later version.
404c10
404c10
   This program is distributed in the hope that it will be useful,
404c10
   but WITHOUT ANY WARRANTY; without even the implied warranty of
404c10
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
404c10
   General Public License for more details.
404c10
404c10
   You should have received a copy of the GNU General Public License 
404c10
   along with this program; if not, write to the Free Software Foundation, 
404c10
   Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */
404c10
404c10
/*  Changes by Rémy Card to use constants and add option -n.  */
404c10
/*  Changes by Jindrich Novy to add option -h, -f, replace mmap(2), fix overflows */
404c10
/*  Changes by Travers Carter to make atomic hardlinking */
404c10
/*  Changes by Todd Lewis that adds option -x to exclude files with pcre lib */
404c10
404c10
#define _GNU_SOURCE
404c10
#define PCRE2_CODE_UNIT_WIDTH 8
404c10
#include <sys/types.h>
404c10
#include <stdlib.h>
404c10
#include <stdio.h>
404c10
#include <unistd.h>
404c10
#include <sys/stat.h>
404c10
#include <sys/mman.h>
404c10
#include <string.h>
404c10
#include <dirent.h>
404c10
#include <fcntl.h>
404c10
#include <errno.h>
404c10
#include <pcre2.h>
404c10
404c10
#define NHASH	(1<<17)	/* Must be a power of 2! */
404c10
#define NIOBUF	(1<<12)
404c10
#define NAMELEN	4096
404c10
#define NBUF	64
404c10
404c10
pcre2_code *re;
404c10
PCRE2_SPTR exclude_pattern;
404c10
pcre2_match_data *match_data;
404c10
404c10
struct _f;
404c10
typedef struct _h {
404c10
  struct _h *next;
404c10
  struct _f *chain;
404c10
  off_t size;
404c10
  time_t mtime;
404c10
} h;
404c10
404c10
typedef struct _d {
404c10
  struct _d *next;
404c10
  char name[0];
404c10
} d;
404c10
404c10
d *dirs;
404c10
404c10
h *hps[NHASH];
404c10
404c10
int no_link = 0;
404c10
int verbose = 0;
404c10
int content_only = 0;
404c10
int force = 0;
404c10
404c10
typedef struct _f {
404c10
  struct _f *next;
404c10
  ino_t ino;
404c10
  dev_t dev;
404c10
  unsigned int cksum;
404c10
  char name[0];
404c10
} f;
404c10
404c10
__attribute__((always_inline)) inline unsigned int hash(off_t size, time_t mtime)
404c10
{
404c10
  return (size ^ mtime) & (NHASH - 1);
404c10
}
404c10
404c10
__attribute__((always_inline)) inline int stcmp(struct stat *st1, struct stat *st2, int content_only)
404c10
{
404c10
  if (content_only)
404c10
    return st1->st_size != st2->st_size;
404c10
  return st1->st_mode != st2->st_mode || st1->st_uid != st2->st_uid ||
404c10
         st1->st_gid != st2->st_gid || st1->st_size != st2->st_size ||
404c10
         st1->st_mtime != st2->st_mtime;
404c10
}
404c10
404c10
long long ndirs, nobjects, nregfiles, ncomp, nlinks, nsaved;
404c10
404c10
void doexit(int i)
404c10
{
404c10
  if (verbose) {
404c10
    fprintf(stderr, "\n\n");
404c10
    fprintf(stderr, "Directories %lld\n", ndirs);
404c10
    fprintf(stderr, "Objects %lld\n", nobjects);
404c10
    fprintf(stderr, "IFREG %lld\n", nregfiles);
404c10
    fprintf(stderr, "Comparisons %lld\n", ncomp);
404c10
    fprintf(stderr, "%s %lld\n", (no_link ? "Would link" : "Linked"), nlinks);
404c10
    fprintf(stderr, "%s %lld\n", (no_link ? "Would save" : "saved"), nsaved);
404c10
  }
404c10
  exit(i);
404c10
}
404c10
404c10
void usage(char *prog)
404c10
{
404c10
  fprintf (stderr, "Usage: %s [-cnvhf] [-x pat] directories...\n", prog);
404c10
  fprintf (stderr, "  -c    When finding candidates for linking, compare only file contents.\n");
404c10
  fprintf (stderr, "  -n    Don't actually link anything, just report what would be done.\n");
404c10
  fprintf (stderr, "  -v    Print summary after hardlinking.\n");
404c10
  fprintf (stderr, "  -vv   Print every hardlinked file and bytes saved + summary.\n");
404c10
  fprintf (stderr, "  -f    Force hardlinking across filesystems.\n");
404c10
  fprintf (stderr, "  -x pat Exclude files matching pattern.\n");
404c10
  fprintf (stderr, "  -h    Show help.\n");
404c10
  exit(255);
404c10
}
404c10
404c10
unsigned int buf[NBUF];
404c10
char iobuf1[NIOBUF], iobuf2[NIOBUF];
404c10
404c10
__attribute__((always_inline)) inline size_t add2(size_t a, size_t b)
404c10
{
404c10
  size_t sum = a + b;
404c10
  if (sum < a) {
404c10
    fprintf(stderr, "\nInteger overflow\n");
404c10
    doexit(5);
404c10
  }
404c10
  return sum;
404c10
}
404c10
404c10
__attribute__((always_inline)) inline size_t add3(size_t a, size_t b, size_t c) 
404c10
{
404c10
  return add2(add2(a, b), c);
404c10
}
404c10
404c10
typedef struct {
404c10
  char *buf;
404c10
  size_t alloc;
404c10
} dynstr;
404c10
404c10
void growstr(dynstr *str, size_t newlen)
404c10
{
404c10
  if (newlen < str->alloc)
404c10
    return;
404c10
  str->buf = realloc(str->buf, str->alloc = add2(newlen, 1));
404c10
  if (!str->buf) {
404c10
    fprintf(stderr, "\nOut of memory 4\n");
404c10
    doexit(4);
404c10
  }
404c10
}
404c10
dev_t dev = 0;
404c10
void rf (const char *name)
404c10
{
404c10
  struct stat st, st2, st3;
404c10
  const size_t namelen = strlen(name);
404c10
  nobjects++;
404c10
  if (lstat (name, &st))
404c10
    return;
404c10
  if (st.st_dev != dev && !force) {
404c10
    if (dev) {
404c10
      fprintf(stderr, "%s is on different filesystem than the rest.\nUse -f option to override.\n", name);
404c10
      doexit(6);
404c10
    }
404c10
    dev = st.st_dev;
404c10
  }
404c10
  if (S_ISDIR (st.st_mode)) {
404c10
    d * dp = malloc(add3(sizeof(d), namelen, 1));
404c10
    if (!dp) {
404c10
      fprintf(stderr, "\nOut of memory 3\n");
404c10
      doexit(3);
404c10
    }
404c10
    memcpy(dp->name, name, namelen + 1);
404c10
    dp->next = dirs;
404c10
    dirs = dp;
404c10
  } else if (S_ISREG (st.st_mode)) {
404c10
    int fd, i;
404c10
    f * fp, * fp2;
404c10
    h * hp;
404c10
    const char *n1, *n2;
404c10
    int cksumsize = sizeof(buf);
404c10
    unsigned int cksum;
404c10
    time_t mtime = content_only ? 0 : st.st_mtime;
404c10
    unsigned int hsh = hash (st.st_size, mtime);
404c10
    off_t fsize;
404c10
    nregfiles++;
404c10
    if (verbose > 1)
404c10
      fprintf(stderr, "  %s", name);
404c10
    fd = open (name, O_RDONLY);
404c10
    if (fd < 0) return;
404c10
    if (st.st_size < sizeof(buf)) {
404c10
      cksumsize = st.st_size;
404c10
      memset (((char *)buf) + cksumsize, 0, (sizeof(buf) - cksumsize) % sizeof(buf[0]));
404c10
    }
404c10
    if (read (fd, buf, cksumsize) != cksumsize) {
404c10
      close(fd);
404c10
      if (verbose > 1 && namelen <= NAMELEN)
404c10
        fprintf(stderr, "\r%*s\r", (int)(namelen + 2), "");
404c10
      return;
404c10
    }
404c10
    cksumsize = (cksumsize + sizeof(buf[0]) - 1) / sizeof(buf[0]);
404c10
    for (i = 0, cksum = 0; i < cksumsize; i++) {
404c10
      if (cksum + buf[i] < cksum)
404c10
        cksum += buf[i] + 1;
404c10
      else
404c10
        cksum += buf[i];
404c10
    }
404c10
    for (hp = hps[hsh]; hp; hp = hp->next)
404c10
      if (hp->size == st.st_size && hp->mtime == mtime)
404c10
        break;
404c10
    if (!hp) {
404c10
      hp = malloc(sizeof(h));
404c10
      if (!hp) {
404c10
        fprintf(stderr, "\nOut of memory 1\n");
404c10
        doexit(1);
404c10
      }
404c10
      hp->size = st.st_size;
404c10
      hp->mtime = mtime;
404c10
      hp->chain = NULL;
404c10
      hp->next = hps[hsh];
404c10
      hps[hsh] = hp;
404c10
    }
404c10
    for (fp = hp->chain; fp; fp = fp->next)
404c10
      if (fp->cksum == cksum)
404c10
        break;
404c10
    for (fp2 = fp; fp2 && fp2->cksum == cksum; fp2 = fp2->next)
404c10
      if (fp2->ino == st.st_ino && fp2->dev == st.st_dev) {
404c10
        close(fd);
404c10
        if (verbose > 1 && namelen <= NAMELEN)
404c10
          fprintf(stderr, "\r%*s\r", (int)(namelen + 2), "");
404c10
        return;
404c10
      }
404c10
    for (fp2 = fp; fp2 && fp2->cksum == cksum; fp2 = fp2->next)
404c10
      if (!lstat (fp2->name, &st2) && S_ISREG (st2.st_mode) &&
404c10
          !stcmp (&st, &st2, content_only) &&
404c10
          st2.st_ino != st.st_ino &&
404c10
          st2.st_dev == st.st_dev) {
404c10
        int fd2 = open (fp2->name, O_RDONLY);
404c10
        if (fd2 < 0) continue;
404c10
        if (fstat (fd2, &st2) || !S_ISREG (st2.st_mode) || st2.st_size == 0) {
404c10
          close (fd2);
404c10
          continue;
404c10
        }
404c10
        ncomp++;
404c10
	lseek(fd, 0, SEEK_SET);
404c10
	for (fsize = st.st_size; fsize > 0; fsize -= NIOBUF) {
404c10
	  off_t rsize = fsize >= NIOBUF ? NIOBUF : fsize;
404c10
	  if (read (fd, iobuf1, rsize) != rsize || read (fd2, iobuf2, rsize) != rsize) {
404c10
	    close(fd);
404c10
	    close(fd2);
404c10
	    fprintf(stderr, "\nReading error\n");
404c10
	    return;
404c10
	  }
404c10
	  if (memcmp (iobuf1, iobuf2, rsize)) break;
404c10
	}
404c10
	close(fd2);
404c10
	if (fsize > 0) continue;
404c10
        if (lstat (name, &st3)) {
404c10
          fprintf(stderr, "\nCould not stat %s again\n", name);
404c10
          close(fd);
404c10
          return;
404c10
        }
404c10
        st3.st_atime = st.st_atime;
404c10
        if (stcmp (&st, &st3, 0)) {
404c10
          fprintf(stderr, "\nFile %s changed underneath us\n", name);
404c10
          close(fd);
404c10
          return;
404c10
        }
404c10
        n1 = fp2->name;
404c10
        n2 = name;
404c10
        if (!no_link) {
404c10
          const char *suffix = ".$$$___cleanit___$$$";
404c10
          const size_t suffixlen = strlen(suffix);
404c10
          size_t n2len = strlen(n2);
404c10
          dynstr nam2 = {NULL, 0};
404c10
          growstr(&nam2, add2(n2len, suffixlen));
404c10
          memcpy(nam2.buf, n2, n2len);
404c10
          memcpy(&nam2.buf[n2len], suffix, suffixlen + 1);
404c10
          /* First create a temporary link to n1 under a new name */
404c10
          if (link(n1, nam2.buf)) {
404c10
            fprintf(stderr, "\nFailed to hardlink %s to %s (create temporary link as %s failed - %s)\n", n1, n2, nam2.buf, strerror(errno));
404c10
            free(nam2.buf);
404c10
            continue;
404c10
          }
404c10
          /* Then rename into place over the existing n2 */
404c10
          if (rename (nam2.buf, n2)) {
404c10
            fprintf(stderr, "\nFailed to hardlink %s to %s (rename temporary link to %s failed - %s)\n", n1, n2, n2, strerror(errno));
404c10
            /* Something went wrong, try to remove the now redundant temporary link */
404c10
            if (unlink(nam2.buf)) {
404c10
              fprintf(stderr, "\nFailed to remove temporary link %s - %s\n", nam2.buf, strerror(errno));
404c10
            }
404c10
            free(nam2.buf);
404c10
            continue;
404c10
          }
404c10
          free(nam2.buf);
404c10
        }
404c10
        nlinks++;
404c10
        if (st3.st_nlink > 1) {
404c10
	  /* We actually did not save anything this time, since the link second argument
404c10
	     had some other links as well.  */
404c10
          if (verbose > 1)
404c10
            fprintf(stderr, "\r%*s\r%s %s to %s\n", (int)(((namelen > NAMELEN) ? 0 : namelen) + 2), "", (no_link ? "Would link" : "Linked"), n1, n2);
404c10
        } else {
404c10
          nsaved+=((st.st_size+4095)/4096)*4096;
404c10
          if (verbose > 1)
404c10
            fprintf(stderr, "\r%*s\r%s %s to %s, %s %ld\n", (int)(((namelen > NAMELEN) ? 0 : namelen) + 2), "", (no_link ? "Would link" : "Linked"), n1, n2, (no_link ? "would save" : "saved"), st.st_size);
404c10
	}
404c10
        close(fd);
404c10
        return;
404c10
      }
404c10
    fp2 = malloc(add3(sizeof(f), namelen, 1));
404c10
    if (!fp2) {
404c10
      fprintf(stderr, "\nOut of memory 2\n");
404c10
      doexit(2);
404c10
    }
404c10
    close(fd);
404c10
    fp2->ino = st.st_ino;
404c10
    fp2->dev = st.st_dev;
404c10
    fp2->cksum = cksum;
404c10
    memcpy(fp2->name, name, namelen + 1);
404c10
    if (fp) {
404c10
      fp2->next = fp->next;
404c10
      fp->next = fp2;
404c10
    } else {
404c10
      fp2->next = hp->chain;
404c10
      hp->chain = fp2;
404c10
    }
404c10
    if (verbose > 1 && namelen <= NAMELEN)
404c10
      fprintf(stderr, "\r%*s\r", (int)(namelen + 2), "");
404c10
    return;
404c10
  }
404c10
}
404c10
404c10
int main(int argc, char **argv)
404c10
{
404c10
  int ch;
404c10
  int i;
404c10
  int errornumber;
404c10
  PCRE2_SIZE erroroffset;
404c10
  dynstr nam1 = {NULL, 0};
404c10
  while ((ch = getopt (argc, argv, "cnvhfx:")) != -1) {
404c10
    switch (ch) {
404c10
    case 'n':
404c10
      no_link++;
404c10
      break;
404c10
    case 'v':
404c10
      verbose++;
404c10
      break;
404c10
    case 'c':
404c10
      content_only++;
404c10
      break;
404c10
    case 'f':
404c10
      force=1;
404c10
      break;
404c10
    case 'x':
404c10
    	exclude_pattern = (PCRE2_SPTR)optarg;
404c10
    	break;
404c10
    case 'h':
404c10
    default:
404c10
      usage(argv[0]);
404c10
    }
404c10
  }
404c10
  if (optind >= argc)
404c10
    usage(argv[0]);
404c10
  if (exclude_pattern) {
404c10
    re = pcre2_compile(
404c10
          exclude_pattern,       /* the pattern */
404c10
          PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminate */
404c10
          0,                     /* default options */
404c10
          &errornumber,
404c10
          &erroroffset,
404c10
          NULL);                 /* use default compile context */
404c10
    if (!re) {
404c10
      PCRE2_UCHAR buffer[256];
404c10
      pcre2_get_error_message(errornumber, buffer, sizeof(buffer));
404c10
      fprintf(stderr, "pattern error at offset %d: %s\n", (int)erroroffset, buffer);
404c10
      usage(argv[0]);
404c10
    }
404c10
    match_data = pcre2_match_data_create_from_pattern(re, NULL);
404c10
  }
404c10
  for (i = optind; i < argc; i++)
404c10
    rf(argv[i]);
404c10
  while (dirs) {
404c10
    DIR *dh;
404c10
    struct dirent *di;
404c10
    d * dp = dirs;
404c10
    size_t nam1baselen = strlen(dp->name);
404c10
    dirs = dp->next;
404c10
    growstr(&nam1, add2(nam1baselen, 1));
404c10
    memcpy(nam1.buf, dp->name, nam1baselen);
404c10
    free (dp);
404c10
    nam1.buf[nam1baselen++] = '/';
404c10
    nam1.buf[nam1baselen] = 0;
404c10
    dh = opendir (nam1.buf);
404c10
    if (dh == NULL)
404c10
      continue;
404c10
    ndirs++;
404c10
    while ((di = readdir (dh)) != NULL) {
404c10
      if (!di->d_name[0])
404c10
        continue;
404c10
      if (di->d_name[0] == '.') {
404c10
        if (!di->d_name[1] || !strcmp(di->d_name, ".."))
404c10
          continue;
404c10
      }
404c10
      if (re && pcre2_match(
404c10
                  re,                 /* compiled regex */
404c10
                  (PCRE2_SPTR)di->d_name,
404c10
                  strlen(di->d_name),
404c10
                  0,                  /* start at offset 0 */
404c10
                  0,                  /* default options */
404c10
                  match_data,         /* block for storing the result */
404c10
                  NULL)              /* use default match context */
404c10
                        >= 0) {
404c10
        if (verbose) {
404c10
          nam1.buf[nam1baselen] = 0;
404c10
          fprintf(stderr,"Skipping %s%s\n", nam1.buf, di->d_name);
404c10
        }
404c10
        continue; 
404c10
      }
404c10
      {
404c10
        size_t subdirlen;
404c10
        growstr(&nam1, add2(nam1baselen, subdirlen = strlen(di->d_name)));
404c10
        memcpy(&nam1.buf[nam1baselen], di->d_name, add2(subdirlen, 1));
404c10
      }
404c10
      rf(nam1.buf);
404c10
    }
404c10
    closedir(dh);
404c10
  }
404c10
  doexit(0);
404c10
  return 0;
404c10
}