3cdb83
/* Copyright (C) 2001 Red Hat, Inc.
3cdb83
3cdb83
   Written by Jakub Jelinek <jakub@redhat.com>.
3cdb83
3cdb83
   This program is free software; you can redistribute it and/or
3cdb83
   modify it under the terms of the GNU General Public License as
3cdb83
   published by the Free Software Foundation; either version 2 of the
3cdb83
   License, or (at your option) any later version.
3cdb83
3cdb83
   This program is distributed in the hope that it will be useful,
3cdb83
   but WITHOUT ANY WARRANTY; without even the implied warranty of
3cdb83
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
3cdb83
   General Public License for more details.
3cdb83
3cdb83
   You should have received a copy of the GNU General Public
3cdb83
   License along with this program; see the file COPYING.  If not,
3cdb83
   write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
3cdb83
   Boston, MA 02111-1307, USA.  */
3cdb83
3cdb83
/*  Changes by Rémy Card to use constants and add option -n.  */
3cdb83
/*  Changes by Jindrich Novy to add option -h, -f, replace mmap(2), fix overflows */
3cdb83
3cdb83
#define _GNU_SOURCE
3cdb83
#include <sys/types.h>
3cdb83
#include <stdlib.h>
3cdb83
#include <stdio.h>
3cdb83
#include <unistd.h>
3cdb83
#include <sys/stat.h>
3cdb83
#include <sys/mman.h>
3cdb83
#include <string.h>
3cdb83
#include <dirent.h>
3cdb83
#include <fcntl.h>
3cdb83
3cdb83
#define NHASH	(1<<17)	/* Must be a power of 2! */
3cdb83
#define NIOBUF	(1<<12)
3cdb83
#define NAMELEN	4096
3cdb83
#define NBUF	64
3cdb83
3cdb83
struct _f;
3cdb83
typedef struct _h {
3cdb83
  struct _h *next;
3cdb83
  struct _f *chain;
3cdb83
  off_t size;
3cdb83
  time_t mtime;
3cdb83
} h;
3cdb83
3cdb83
typedef struct _d {
3cdb83
  struct _d *next;
3cdb83
  char name[0];
3cdb83
} d;
3cdb83
3cdb83
d *dirs;
3cdb83
3cdb83
h *hps[NHASH];
3cdb83
3cdb83
int no_link = 0;
3cdb83
int verbose = 0;
3cdb83
int content_only = 0;
3cdb83
int force = 0;
3cdb83
3cdb83
typedef struct _f {
3cdb83
  struct _f *next;
3cdb83
  ino_t ino;
3cdb83
  dev_t dev;
3cdb83
  unsigned int cksum;
3cdb83
  char name[0];
3cdb83
} f;
3cdb83
3cdb83
inline unsigned int hash(off_t size, time_t mtime)
3cdb83
{
3cdb83
  return (size ^ mtime) & (NHASH - 1);
3cdb83
}
3cdb83
3cdb83
inline int stcmp(struct stat *st1, struct stat *st2, int content_only)
3cdb83
{
3cdb83
  if (content_only)
3cdb83
    return st1->st_size != st2->st_size;
3cdb83
  return st1->st_mode != st2->st_mode || st1->st_uid != st2->st_uid ||
3cdb83
         st1->st_gid != st2->st_gid || st1->st_size != st2->st_size ||
3cdb83
         st1->st_mtime != st2->st_mtime;
3cdb83
}
3cdb83
3cdb83
long long ndirs, nobjects, nregfiles, ncomp, nlinks, nsaved;
3cdb83
3cdb83
void doexit(int i)
3cdb83
{
3cdb83
  if (verbose) {
3cdb83
    fprintf(stderr, "\n\n");
3cdb83
    fprintf(stderr, "Directories %lld\n", ndirs);
3cdb83
    fprintf(stderr, "Objects %lld\n", nobjects);
3cdb83
    fprintf(stderr, "IFREG %lld\n", nregfiles);
3cdb83
    fprintf(stderr, "Comparisons %lld\n", ncomp);
3cdb83
    fprintf(stderr, "%s %lld\n", (no_link ? "Would link" : "Linked"), nlinks);
3cdb83
    fprintf(stderr, "%s %lld\n", (no_link ? "Would save" : "saved"), nsaved);
3cdb83
  }
3cdb83
  exit(i);
3cdb83
}
3cdb83
3cdb83
void usage(char *prog)
3cdb83
{
3cdb83
  fprintf (stderr, "Usage: %s [-cnvhf] directories...\n", prog);
3cdb83
  fprintf (stderr, "  -c    When finding candidates for linking, compare only file contents.\n");
3cdb83
  fprintf (stderr, "  -n    Don't actually link anything, just report what would be done.\n");
3cdb83
  fprintf (stderr, "  -v    Print summary after hardlinking.\n");
3cdb83
  fprintf (stderr, "  -vv   Print every hardlinked file and bytes saved + summary.\n");
3cdb83
  fprintf (stderr, "  -f    Force hardlinking across filesystems.\n");
3cdb83
  fprintf (stderr, "  -h    Show help.\n");
3cdb83
  exit(255);
3cdb83
}
3cdb83
3cdb83
unsigned int buf[NBUF];
3cdb83
char iobuf1[NIOBUF], iobuf2[NIOBUF];
3cdb83
3cdb83
inline size_t add2(size_t a, size_t b)
3cdb83
{
3cdb83
  size_t sum = a + b;
3cdb83
  if (sum < a) {
3cdb83
    fprintf(stderr, "\nInteger overflow\n");
3cdb83
    doexit(5);
3cdb83
  }
3cdb83
  return sum;
3cdb83
}
3cdb83
3cdb83
inline size_t add3(size_t a, size_t b, size_t c)
3cdb83
{
3cdb83
  return add2(add2(a, b), c);
3cdb83
}
3cdb83
3cdb83
typedef struct {
3cdb83
  char *buf;
3cdb83
  size_t alloc;
3cdb83
} dynstr;
3cdb83
3cdb83
void growstr(dynstr *str, size_t newlen)
3cdb83
{
3cdb83
  if (newlen < str->alloc)
3cdb83
    return;
3cdb83
  str->buf = realloc(str->buf, str->alloc = add2(newlen, 1));
3cdb83
  if (!str->buf) {
3cdb83
    fprintf(stderr, "\nOut of memory 4\n");
3cdb83
    doexit(4);
3cdb83
  }
3cdb83
}
3cdb83
dev_t dev = 0;
3cdb83
void rf (const char *name)
3cdb83
{
3cdb83
  struct stat st, st2, st3;
3cdb83
  const size_t namelen = strlen(name);
3cdb83
  nobjects++;
3cdb83
  if (lstat (name, &st))
3cdb83
    return;
3cdb83
  if (st.st_dev != dev && !force) {
3cdb83
    if (dev) {
3cdb83
      fprintf(stderr, "%s is on different filesystem than the rest.\nUse -f option to override.\n", name);
3cdb83
      doexit(6);
3cdb83
    }
3cdb83
    dev = st.st_dev;
3cdb83
  }
3cdb83
  if (S_ISDIR (st.st_mode)) {
3cdb83
    d * dp = malloc(add3(sizeof(d), namelen, 1));
3cdb83
    if (!dp) {
3cdb83
      fprintf(stderr, "\nOut of memory 3\n");
3cdb83
      doexit(3);
3cdb83
    }
3cdb83
    memcpy(dp->name, name, namelen + 1);
3cdb83
    dp->next = dirs;
3cdb83
    dirs = dp;
3cdb83
  } else if (S_ISREG (st.st_mode)) {
3cdb83
    int fd, i;
3cdb83
    f * fp, * fp2;
3cdb83
    h * hp;
3cdb83
    const char *n1, *n2;
3cdb83
    int cksumsize = sizeof(buf);
3cdb83
    unsigned int cksum;
3cdb83
    time_t mtime = content_only ? 0 : st.st_mtime;
3cdb83
    unsigned int hsh = hash (st.st_size, mtime);
3cdb83
    off_t fsize;
3cdb83
    nregfiles++;
3cdb83
    if (verbose > 1)
3cdb83
      fprintf(stderr, "  %s", name);
3cdb83
    fd = open (name, O_RDONLY);
3cdb83
    if (fd < 0) return;
3cdb83
    if (st.st_size < sizeof(buf)) {
3cdb83
      cksumsize = st.st_size;
3cdb83
      memset (((char *)buf) + cksumsize, 0, (sizeof(buf) - cksumsize) % sizeof(buf[0]));
3cdb83
    }
3cdb83
    if (read (fd, buf, cksumsize) != cksumsize) {
3cdb83
      close(fd);
3cdb83
      if (verbose > 1 && namelen <= NAMELEN)
3cdb83
        fprintf(stderr, "\r%*s\r", (int)(namelen + 2), "");
3cdb83
      return;
3cdb83
    }
3cdb83
    cksumsize = (cksumsize + sizeof(buf[0]) - 1) / sizeof(buf[0]);
3cdb83
    for (i = 0, cksum = 0; i < cksumsize; i++) {
3cdb83
      if (cksum + buf[i] < cksum)
3cdb83
        cksum += buf[i] + 1;
3cdb83
      else
3cdb83
        cksum += buf[i];
3cdb83
    }
3cdb83
    for (hp = hps[hsh]; hp; hp = hp->next)
3cdb83
      if (hp->size == st.st_size && hp->mtime == mtime)
3cdb83
        break;
3cdb83
    if (!hp) {
3cdb83
      hp = malloc(sizeof(h));
3cdb83
      if (!hp) {
3cdb83
        fprintf(stderr, "\nOut of memory 1\n");
3cdb83
        doexit(1);
3cdb83
      }
3cdb83
      hp->size = st.st_size;
3cdb83
      hp->mtime = mtime;
3cdb83
      hp->chain = NULL;
3cdb83
      hp->next = hps[hsh];
3cdb83
      hps[hsh] = hp;
3cdb83
    }
3cdb83
    for (fp = hp->chain; fp; fp = fp->next)
3cdb83
      if (fp->cksum == cksum)
3cdb83
        break;
3cdb83
    for (fp2 = fp; fp2 && fp2->cksum == cksum; fp2 = fp2->next)
3cdb83
      if (fp2->ino == st.st_ino && fp2->dev == st.st_dev) {
3cdb83
        close(fd);
3cdb83
        if (verbose > 1 && namelen <= NAMELEN)
3cdb83
          fprintf(stderr, "\r%*s\r", (int)(namelen + 2), "");
3cdb83
        return;
3cdb83
      }
3cdb83
    for (fp2 = fp; fp2 && fp2->cksum == cksum; fp2 = fp2->next)
3cdb83
      if (!lstat (fp2->name, &st2) && S_ISREG (st2.st_mode) &&
3cdb83
          !stcmp (&st, &st2, content_only) &&
3cdb83
          st2.st_ino != st.st_ino &&
3cdb83
          st2.st_dev == st.st_dev) {
3cdb83
        int fd2 = open (fp2->name, O_RDONLY);
3cdb83
        if (fd2 < 0) continue;
3cdb83
        if (fstat (fd2, &st2) || !S_ISREG (st2.st_mode) || st2.st_size == 0) {
3cdb83
          close (fd2);
3cdb83
          continue;
3cdb83
        }
3cdb83
        ncomp++;
3cdb83
	lseek(fd, 0, SEEK_SET);
3cdb83
	for (fsize = st.st_size; fsize > 0; fsize -= NIOBUF) {
3cdb83
	  off_t rsize = fsize >= NIOBUF ? NIOBUF : fsize;
3cdb83
	  if (read (fd, iobuf1, rsize) != rsize || read (fd2, iobuf2, rsize) != rsize) {
3cdb83
	    close(fd);
3cdb83
	    close(fd2);
3cdb83
	    fprintf(stderr, "\nReading error\n");
3cdb83
	    return;
3cdb83
	  }
3cdb83
	  if (memcmp (iobuf1, iobuf2, rsize)) break;
3cdb83
	}
3cdb83
	close(fd2);
3cdb83
	if (fsize > 0) continue;
3cdb83
        if (lstat (name, &st3)) {
3cdb83
          fprintf(stderr, "\nCould not stat %s again\n", name);
3cdb83
          close(fd);
3cdb83
          return;
3cdb83
        }
3cdb83
        st3.st_atime = st.st_atime;
3cdb83
        if (stcmp (&st, &st3, 0)) {
3cdb83
          fprintf(stderr, "\nFile %s changed underneath us\n", name);
3cdb83
          close(fd);
3cdb83
          return;
3cdb83
        }
3cdb83
        n1 = fp2->name;
3cdb83
        n2 = name;
3cdb83
        if (!no_link) {
3cdb83
          const char *suffix = ".$$$___cleanit___$$$";
3cdb83
          const size_t suffixlen = strlen(suffix);
3cdb83
          size_t n2len = strlen(n2);
3cdb83
          dynstr nam2 = {NULL, 0};
3cdb83
          growstr(&nam2, add2(n2len, suffixlen));
3cdb83
          memcpy(nam2.buf, n2, n2len);
3cdb83
          memcpy(&nam2.buf[n2len], suffix, suffixlen + 1);
3cdb83
          if (rename (n2, nam2.buf)) {
3cdb83
            fprintf(stderr, "\nFailed to rename %s to %s\n", n2, nam2.buf);
3cdb83
            free(nam2.buf);
3cdb83
            continue;
3cdb83
          }
3cdb83
          if (link (n1, n2)) {
3cdb83
            fprintf(stderr, "\nFailed to hardlink %s to %s\n", n1, n2);
3cdb83
            if (rename (nam2.buf, n2)) {
3cdb83
              fprintf(stderr, "\nBad bad - failed to rename back %s to %s\n", nam2.buf, n2);
3cdb83
            }
3cdb83
            close(fd);
3cdb83
            free(nam2.buf);
3cdb83
            return;
3cdb83
          }
3cdb83
          unlink (nam2.buf);
3cdb83
          free(nam2.buf);
3cdb83
        }
3cdb83
        nlinks++;
3cdb83
        if (st3.st_nlink > 1) {
3cdb83
	  /* We actually did not save anything this time, since the link second argument
3cdb83
	     had some other links as well.  */
3cdb83
          if (verbose > 1)
3cdb83
            fprintf(stderr, "\r%*s\r%s %s to %s\n", (int)(((namelen > NAMELEN) ? 0 : namelen) + 2), "", (no_link ? "Would link" : "Linked"), n1, n2);
3cdb83
        } else {
3cdb83
          nsaved+=((st.st_size+4095)/4096)*4096;
3cdb83
          if (verbose > 1)
3cdb83
            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);
3cdb83
	}
3cdb83
        close(fd);
3cdb83
        return;
3cdb83
      }
3cdb83
    fp2 = malloc(add3(sizeof(f), namelen, 1));
3cdb83
    if (!fp2) {
3cdb83
      fprintf(stderr, "\nOut of memory 2\n");
3cdb83
      doexit(2);
3cdb83
    }
3cdb83
    close(fd);
3cdb83
    fp2->ino = st.st_ino;
3cdb83
    fp2->dev = st.st_dev;
3cdb83
    fp2->cksum = cksum;
3cdb83
    memcpy(fp2->name, name, namelen + 1);
3cdb83
    if (fp) {
3cdb83
      fp2->next = fp->next;
3cdb83
      fp->next = fp2;
3cdb83
    } else {
3cdb83
      fp2->next = hp->chain;
3cdb83
      hp->chain = fp2;
3cdb83
    }
3cdb83
    if (verbose > 1 && namelen <= NAMELEN)
3cdb83
      fprintf(stderr, "\r%*s\r", (int)(namelen + 2), "");
3cdb83
    return;
3cdb83
  }
3cdb83
}
3cdb83
3cdb83
int main(int argc, char **argv)
3cdb83
{
3cdb83
  int ch;
3cdb83
  int i;
3cdb83
  dynstr nam1 = {NULL, 0};
3cdb83
  while ((ch = getopt (argc, argv, "cnvhf")) != -1) {
3cdb83
    switch (ch) {
3cdb83
    case 'n':
3cdb83
      no_link++;
3cdb83
      break;
3cdb83
    case 'v':
3cdb83
      verbose++;
3cdb83
      break;
3cdb83
    case 'c':
3cdb83
      content_only++;
3cdb83
      break;
3cdb83
    case 'f':
3cdb83
      force=1;
3cdb83
      break;
3cdb83
    case 'h':
3cdb83
    default:
3cdb83
      usage(argv[0]);
3cdb83
    }
3cdb83
  }
3cdb83
  if (optind >= argc)
3cdb83
    usage(argv[0]);
3cdb83
  for (i = optind; i < argc; i++)
3cdb83
    rf(argv[i]);
3cdb83
  while (dirs) {
3cdb83
    DIR *dh;
3cdb83
    struct dirent *di;
3cdb83
    d * dp = dirs;
3cdb83
    size_t nam1baselen = strlen(dp->name);
3cdb83
    dirs = dp->next;
3cdb83
    growstr(&nam1, add2(nam1baselen, 1));
3cdb83
    memcpy(nam1.buf, dp->name, nam1baselen);
3cdb83
    free (dp);
3cdb83
    nam1.buf[nam1baselen++] = '/';
3cdb83
    nam1.buf[nam1baselen] = 0;
3cdb83
    dh = opendir (nam1.buf);
3cdb83
    if (dh == NULL)
3cdb83
      continue;
3cdb83
    ndirs++;
3cdb83
    while ((di = readdir (dh)) != NULL) {
3cdb83
      if (!di->d_name[0])
3cdb83
        continue;
3cdb83
      if (di->d_name[0] == '.') {
3cdb83
        char *q;
3cdb83
        if (!di->d_name[1] || !strcmp (di->d_name, "..") || !strncmp (di->d_name, ".in.", 4))
3cdb83
          continue;
3cdb83
        q = strrchr (di->d_name, '.');
3cdb83
        if (q && strlen (q) == 7 && q != di->d_name) {
3cdb83
          nam1.buf[nam1baselen] = 0;
3cdb83
          if (verbose)
3cdb83
            fprintf(stderr, "Skipping %s%s\n", nam1.buf, di->d_name);
3cdb83
          continue;
3cdb83
        }
3cdb83
      }
3cdb83
      {
3cdb83
        size_t subdirlen;
3cdb83
        growstr(&nam1, add2(nam1baselen, subdirlen = strlen(di->d_name)));
3cdb83
        memcpy(&nam1.buf[nam1baselen], di->d_name, add2(subdirlen, 1));
3cdb83
      }
3cdb83
      rf(nam1.buf);
3cdb83
    }
3cdb83
    closedir(dh);
3cdb83
  }
3cdb83
  doexit(0);
3cdb83
  return 0;
3cdb83
}