jdupes.c 56.4 KB
Newer Older
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
/* jdupes (C) 2015-2016 Jody Bruchon <jody@jodybruchon.com>
   Derived from fdupes (C) 1999-2016 Adrian Lopez

   Permission is hereby granted, free of charge, to any person
   obtaining a copy of this software and associated documentation files
   (the "Software"), to deal in the Software without restriction,
   including without limitation the rights to use, copy, modify, merge,
   publish, distribute, sublicense, and/or sell copies of the Software,
   and to permit persons to whom the Software is furnished to do so,
   subject to the following conditions:

   The above copyright notice and this permission notice shall be
   included in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
   IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
   CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
   TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
   SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <dirent.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#ifndef OMIT_GETOPT_LONG
 #include <getopt.h>
#endif
#include <string.h>
#include <errno.h>
#include <libgen.h>
40
#include "jdupes.h"
41 42
#include "string_malloc.h"
#include "jody_hash.h"
43
#include "jody_sort.h"
44
#include "jody_win_unicode.h"
45 46
#include "version.h"

47 48 49 50 51 52
/* Headers for post-scanning actions */
#include "act_deletefiles.h"
#include "act_dedupefiles.h"
#include "act_linkfiles.h"
#include "act_printmatches.h"
#include "act_summarize.h"
53 54 55

/* Detect Windows and modify as needed */
#if defined _WIN32 || defined __CYGWIN__
56
 const char dir_sep = '\\';
57
 #ifdef UNICODE
58
  const wchar_t *FILE_MODE_RO = L"rbS";
59
 #else
60
  const char *FILE_MODE_RO = "rbS";
61 62 63
 #endif /* UNICODE */

#else /* Not Windows */
64 65
 const char *FILE_MODE_RO = "rb";
 const char dir_sep = '/';
66 67 68 69
 #ifdef UNICODE
  #error Do not define UNICODE on non-Windows platforms.
  #undef UNICODE
 #endif
70 71 72 73
#endif /* _WIN32 || __CYGWIN__ */

/* Windows + Unicode compilation */
#ifdef UNICODE
74 75 76 77
wchar_t wname[PATH_MAX];
wchar_t wname2[PATH_MAX];
wchar_t wstr[PATH_MAX];
int out_mode = _O_TEXT;
78 79 80 81
 #define M2W(a,b) MultiByteToWideChar(CP_UTF8, 0, a, -1, (LPWSTR)b, PATH_MAX)
 #define W2M(a,b) WideCharToMultiByte(CP_UTF8, 0, a, -1, (LPSTR)b, PATH_MAX, NULL, NULL)
#endif /* UNICODE */

82 83 84 85
#ifndef NO_SYMLINKS
#include "jody_paths.h"
#endif

86 87
#define ISFLAG(a,b) ((a & b) == b)
#define SETFLAG(a,b) (a |= b)
88
#define CLEARFLAG(a,b) (a &= (~b))
89

90 91 92 93 94 95 96 97 98 99
/* Low memory option overrides */
#ifdef LOW_MEMORY
 #undef DEBUG
 #undef LOUD_DEBUG
 #undef USE_TREE_REBALANCE
 #ifndef NO_PERMS
  #define NO_PERMS 1
 #endif
#endif

100 101 102 103 104 105 106
/* Tree rebalance requires tree stats */
#ifdef USE_TREE_REBALANCE
 #ifndef TREE_DEPTH_STATS
  #define TREE_DEPTH_STATS
 #endif
#endif

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
/* Aggressive verbosity for deep debugging */
#ifdef LOUD_DEBUG
 #ifndef DEBUG
  #define DEBUG
 #endif
 #define LOUD(...) if ISFLAG(flags, F_LOUD) __VA_ARGS__
#else
 #define LOUD(a)
#endif

/* Compile out debugging stat counters unless requested */
#ifdef DEBUG
 #define DBG(a) a
 #ifndef TREE_DEPTH_STATS
  #define TREE_DEPTH_STATS
 #endif
#else
 #define DBG(a)
#endif


/* How many operations to wait before updating progress counters */
#define DELAY_COUNT 256

/* Behavior modification flags */
132
uint_fast32_t flags = 0;
133 134 135 136 137

static const char *program_name;

/* This gets used in many functions */
#ifdef ON_WINDOWS
138
struct winstat ws;
139
#else
140
struct stat s;
141 142
#endif

143
static uintmax_t excludesize = 0;
144 145 146 147 148 149 150
static enum {
  SMALLERTHAN,
  LARGERTHAN
} excludetype = SMALLERTHAN;

/* Larger chunk size makes large files process faster but uses more RAM */
#ifndef CHUNK_SIZE
151
 #define CHUNK_SIZE 32768
152 153 154 155
#endif
#ifndef PARTIAL_HASH_SIZE
 #define PARTIAL_HASH_SIZE 4096
#endif
156 157 158 159 160 161 162 163 164 165

/* Maximum path buffer size to use; must be large enough for a path plus
 * any work that might be done to the array it's stored in. PATH_MAX is
 * not always true. Read this article on the false promises of PATH_MAX:
 * http://insanecoding.blogspot.com/2007/11/pathmax-simply-isnt.html
 * Windows + Unicode needs a lot more space than UTF-8 in Linux/Mac OS X
 */
#ifndef PATHBUF_SIZE
#define PATHBUF_SIZE 4096
#endif
166 167 168 169 170 171 172 173
/* Refuse to build if PATHBUF_SIZE is too small */
#if PATHBUF_SIZE < PATH_MAX
#error "PATHBUF_SIZE can't be less than PATH_MAX"
#endif

#ifndef INITIAL_DEPTH_THRESHOLD
#define INITIAL_DEPTH_THRESHOLD 8
#endif
174

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
/* For interactive deletion input */
#define INPUT_SIZE 512

/* Assemble extension string from compile-time options */
static const char *extensions[] = {
  #ifdef ON_WINDOWS
    "windows",
    #endif
    #ifdef UNICODE
    "unicode",
    #endif
    #ifdef OMIT_GETOPT_LONG
    "nolong",
    #endif
    #ifdef __FAST_MATH__
    "fastmath",
    #endif
    #ifdef DEBUG
    "debug",
    #endif
    #ifdef LOUD_DEBUG
    "loud",
    #endif
    #ifdef ENABLE_BTRFS
    "btrfs",
    #endif
201 202 203
    #ifdef LOW_MEMORY
    "lowmem",
    #endif
204 205 206
    #ifdef SMA_PAGE_SIZE
    "smapage",
    #endif
207 208 209 210 211 212
    #if JODY_HASH_WIDTH == 32
    "hash32",
    #endif
    #if JODY_HASH_WIDTH == 16
    "hash16",
    #endif
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
    #ifdef NO_PERMS
    "noperm",
    #endif
    #ifdef NO_SYMLINKS
    "nosymlink",
    #endif
    #ifdef USE_TREE_REBALANCE
    "rebal",
    #endif
    #ifdef CONSIDER_IMBALANCE
    "ci",
    #endif
    #ifdef BALANCE_THRESHOLD
    "bt",
    #endif
    NULL
};

231 232 233 234 235 236 237 238 239
/* Tree to track each directory traversed */
struct travdone {
  struct travdone *left;
  struct travdone *right;
  jdupes_ino_t inode;
  dev_t device;
};
static struct travdone *travdone_head = NULL;

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
static uintmax_t filecount = 0; // Required for progress indicator code
static int did_long_work = 0; // To tell progress indicator to go faster

/* Hash/compare performance statistics (debug mode) */
#ifdef DEBUG
static unsigned int small_file = 0, partial_hash = 0, partial_elim = 0;
static unsigned int full_hash = 0, partial_to_full = 0, hash_fail = 0;
static uintmax_t comparisons = 0;
static unsigned int left_branch = 0, right_branch = 0;
 #ifdef ON_WINDOWS
  #ifndef NO_HARDLINKS
static unsigned int hll_exclude = 0;
  #endif
 #endif
#endif /* DEBUG */

#ifdef TREE_DEPTH_STATS
257 258
static unsigned int tree_depth = 0;
static unsigned int max_depth = 0;
259 260
#endif

261 262 263
/* File tree head */
static filetree_t *checktree = NULL;

264 265 266 267 268 269 270 271 272 273 274 275
/* Directory parameter position counter */
static unsigned int user_dir_count = 1;

/* registerfile() direction options */
enum tree_direction { NONE, LEFT, RIGHT };

/* Sort order reversal */
static int sort_direction = 1;

/* Signal handler */
static int interrupt = 0;

276

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
/***** End definitions, begin code *****/


/* Catch CTRL-C and either notify or terminate */
void sighandler(const int signum)
{
  (void)signum;
  if (interrupt || !ISFLAG(flags, F_SOFTABORT)) {
    fprintf(stderr, "\n");
    exit(EXIT_FAILURE);
  }
  interrupt = 1;
  return;
}


/* Out of memory */
294
extern void oom(const char * const restrict msg)
295
{
296
  fprintf(stderr, "\nout of memory: %s\n", msg);
297 298 299 300 301 302 303 304 305 306 307 308 309
  exit(EXIT_FAILURE);
}


/* Compare two jody_hashes like memcmp() */
#define HASH_COMPARE(a,b) ((a > b) ? 1:((a == b) ? 0:-1))


static inline char **cloneargs(const int argc, char **argv)
{
  static int x;
  static char **args;

310
  args = (char **)string_malloc(sizeof(char *) * (unsigned int)argc);
311
  if (args == NULL) oom("cloneargs() start");
312 313 314

  for (x = 0; x < argc; x++) {
    args[x] = (char *)string_malloc(strlen(argv[x]) + 1);
315
    if (args[x] == NULL) oom("cloneargs() loop");
316 317 318 319 320 321 322 323 324 325
    strcpy(args[x], argv[x]);
  }

  return args;
}


static int findarg(const char * const arg, const int start,
                const int argc, char **argv)
{
326
  int x;
327 328 329 330 331 332 333 334 335 336 337 338

  for (x = start; x < argc; x++)
    if (strcmp(argv[x], arg) == 0)
      return x;

  return x;
}

/* Find the first non-option argument after specified option. */
static int nonoptafter(const char *option, const int argc,
                char **oldargv, char **newargv, int optind)
{
339 340 341 342
  int x;
  int targetind;
  int testind;
  int startat = 1;
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357

  targetind = findarg(option, 1, argc, oldargv);

  for (x = optind; x < argc; x++) {
    testind = findarg(newargv[x], startat, argc, oldargv);
    if (testind > targetind) return x;
    else startat = testind;
  }

  return x;
}


/* Check file's stat() info to make sure nothing has changed
 * Returns 1 if changed, 0 if not changed, negative if error */
358
extern int file_has_changed(file_t * const restrict file)
359
{
360
  if (!ISFLAG(file->flags, F_VALID_STAT)) return -66;
361 362

#ifdef ON_WINDOWS
363
  int i;
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
  if ((i = win_stat(file->d_name, &ws)) != 0) return i;
  if (file->inode != ws.inode) return 1;
  if (file->size != ws.size) return 1;
  if (file->device != ws.device) return 1;
  if (file->mtime != ws.mtime) return 1;
  if (file->mode != ws.mode) return 1;
#else
  if (stat(file->d_name, &s) != 0) return -2;
  if (file->inode != s.st_ino) return 1;
  if (file->size != s.st_size) return 1;
  if (file->device != s.st_dev) return 1;
  if (file->mtime != s.st_mtime) return 1;
  if (file->mode != s.st_mode) return 1;
 #ifndef NO_PERMS
  if (file->uid != s.st_uid) return 1;
  if (file->gid != s.st_gid) return 1;
 #endif
 #ifndef NO_SYMLINKS
  if (lstat(file->d_name, &s) != 0) return -3;
383
  if ((S_ISLNK(s.st_mode) > 0) ^ ISFLAG(file->flags, F_IS_SYMLINK)) return 1;
384 385 386 387 388 389 390
 #endif
#endif /* ON_WINDOWS */

  return 0;
}


391
extern inline int getfilestats(file_t * const restrict file)
392 393
{
  /* Don't stat the same file more than once */
394 395
  if (ISFLAG(file->flags, F_VALID_STAT)) return 0;
  SETFLAG(file->flags, F_VALID_STAT);
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419

#ifdef ON_WINDOWS
  if (win_stat(file->d_name, &ws) != 0) return -1;
  file->inode = ws.inode;
  file->size = ws.size;
  file->device = ws.device;
  file->mtime = ws.mtime;
  file->mode = ws.mode;
 #ifndef NO_HARDLINKS
  file->nlink = ws.nlink;
 #endif /* NO_HARDLINKS */
#else
  if (stat(file->d_name, &s) != 0) return -1;
  file->inode = s.st_ino;
  file->size = s.st_size;
  file->device = s.st_dev;
  file->mtime = s.st_mtime;
  file->mode = s.st_mode;
 #ifndef NO_PERMS
  file->uid = s.st_uid;
  file->gid = s.st_gid;
 #endif
 #ifndef NO_SYMLINKS
  if (lstat(file->d_name, &s) != 0) return -1;
420
  if (S_ISLNK(s.st_mode) > 0) SETFLAG(file->flags, F_IS_SYMLINK);
421 422 423 424 425 426
 #endif
#endif /* ON_WINDOWS */
  return 0;
}


427
extern int getdirstats(const char * const restrict name,
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
        jdupes_ino_t * const restrict inode, dev_t * const restrict dev)
{
#ifdef ON_WINDOWS
  if (win_stat(name, &ws) != 0) return -1;
  *inode = ws.inode;
  *dev = ws.device;
#else
  if (stat(name, &s) != 0) return -1;
  *inode = s.st_ino;
  *dev = s.st_dev;
#endif /* ON_WINDOWS */
  return 0;
}


443 444 445 446 447 448
/* Check a pair of files for match exclusion conditions
 * Returns:
 *  0 if all condition checks pass
 * -1 or 1 on compare result less/more
 * -2 on an absolute exclusion condition met
 *  2 on an absolute match condition met */
449
extern int check_conditions(const file_t * const restrict file1, const file_t * const restrict file2)
450 451 452 453 454 455 456
{
  /* Null pointer sanity check */
  if (!file1 || !file2) {
    LOUD(fprintf(stderr, "internal error: null pointer passed to check_conditions()\n");)
    exit(EXIT_FAILURE);
  }

457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
  /* Exclude based on -I/--isolate */
  if (ISFLAG(flags, F_ISOLATE) && (file1->user_order == file2->user_order)) {
    LOUD(fprintf(stderr, "check_conditions: files ignored: parameter isolation\n"));
    return -1;
  }

 /* Exclude files by permissions if requested */
  if (ISFLAG(flags, F_PERMISSIONS) &&
          (file1->mode != file2->mode
#ifndef NO_PERMS
          || file1->uid != file2->uid
          || file1->gid != file2->gid
#endif
          )) {
    return -1;
    LOUD(fprintf(stderr, "check_conditions: no match: permissions/ownership differ (-p on)\n"));
  }

475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
  /* Hard link and symlink + '-s' check */
#ifndef NO_HARDLINKS
  if ((file1->inode == file2->inode) && (file1->device == file2->device)) {
    if (ISFLAG(flags, F_CONSIDERHARDLINKS)) {
      LOUD(fprintf(stderr, "check_conditions: files match: hard/soft linked (-H on)\n"));
      return 2;
    } else {
      LOUD(fprintf(stderr, "check_conditions: files ignored: hard/soft linked (-H off)\n"));
      return -2;
    }
  }
#endif

  /* Exclude files that are not the same size */
  if (file1->size > file2->size) {
    LOUD(fprintf(stderr, "check_conditions: no match: file1 > file2 (%jd < %jd)\n", (intmax_t)file1->size, (intmax_t)file2->size));
    return -1;
  }
  if (file1->size < file2->size) {
    LOUD(fprintf(stderr, "check_conditions: no match: file1 < file2 (%jd > %jd)\n", (intmax_t)file1->size, (intmax_t)file2->size));
    return 1;
  }

  /* Fall through: all checks passed */
  LOUD(fprintf(stderr, "check_conditions: all condition checks passed\n"));
  return 0;
}


504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
/* Create a new traversal check object */
static int travdone_alloc(struct travdone **trav, const char * const restrict dir)
{
  *trav = string_malloc(sizeof(struct travdone));
  if (*trav == NULL) {
    LOUD(fprintf(stderr, "travdone_alloc: malloc returned NULL\n");)
    return -1;
  }
  (*trav)->left = NULL;
  (*trav)->right = NULL;
  if (getdirstats(dir, &((*trav)->inode), &((*trav)->device)) != 0) return -1;
  return 0;
}


519
/* Load a directory's contents into the file tree, recursing as needed */
520 521 522 523 524 525 526 527 528 529 530 531
static void grokdir(const char * const restrict dir,
                file_t * restrict * const restrict filelistp,
                int recurse)
{
  file_t * restrict newfile;
#ifndef NO_SYMLINKS
  static struct stat linfo;
#endif
  struct dirent *dirinfo;
  static uintmax_t progress = 0, dir_progress = 0;
  static int grokdir_level = 0;
  static int delay = DELAY_COUNT;
532
  static char tempname[PATHBUF_SIZE * 2];
533
  size_t dirlen;
534 535 536
  struct travdone *traverse;
  jdupes_ino_t inode;
  dev_t device;
537 538 539 540 541 542 543 544 545
#ifdef UNICODE
  WIN32_FIND_DATA ffd;
  HANDLE hFind = INVALID_HANDLE_VALUE;
  char *p;
#else
  DIR *cd;
#endif

  LOUD(fprintf(stderr, "grokdir: scanning '%s' (order %d)\n", dir, user_dir_count));
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580

  /* Double traversal prevention tree */
  if (travdone_head == NULL) {
    if (travdone_alloc(&travdone_head, dir) != 0) goto error_travdone;
  } else {
    if (getdirstats(dir, &inode, &device) != 0) goto error_travdone;
    traverse = travdone_head;
    while (1) {
      /* Don't re-traverse directories we've already seen */
      if (inode == traverse->inode && device == traverse->device) {
        LOUD(fprintf(stderr, "already seen dir '%s', skipping\n", dir);)
        return;
      }
      if (inode >= traverse->inode) {
        /* Traverse right */
        if (traverse->right == NULL) {
          LOUD(fprintf(stderr, "traverse dir right '%s'\n", dir);)
          if (travdone_alloc(&(traverse->right), dir) != 0) goto error_travdone;
          break;
        }
        traverse = traverse->right;
        continue;
      } else {
        /* Traverse left */
        if (traverse->left == NULL) {
          LOUD(fprintf(stderr, "traverse dir left '%s'\n", dir);)
          if (travdone_alloc(&(traverse->left), dir) != 0) goto error_travdone;
          break;
        }
        traverse = traverse->left;
        continue;
      }
    }
  }

581 582 583 584 585
  dir_progress++;
  grokdir_level++;

#ifdef UNICODE
  /* Windows requires \* at the end of directory names */
586
  strncpy(tempname, dir, PATHBUF_SIZE * 2);
587 588 589
  dirlen = strlen(tempname) - 1;
  p = tempname + dirlen;
  if (*p == '/' || *p == '\\') *p = '\0';
590
  strncat(tempname, "\\*", PATHBUF_SIZE * 2);
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627

  if (!M2W(tempname, wname)) goto error_cd;

  LOUD(fprintf(stderr, "FindFirstFile: %s\n", dir));
  hFind = FindFirstFile((LPCWSTR)wname, &ffd);
  if (hFind == INVALID_HANDLE_VALUE) { fprintf(stderr, "handle bad\n"); goto error_cd; }
  LOUD(fprintf(stderr, "Loop start\n"));
  do {
    char * restrict tp = tempname;
    size_t d_name_len;

    /* Get necessary length and allocate d_name */
    dirinfo = (struct dirent *)string_malloc(sizeof(struct dirent));
    if (!W2M(ffd.cFileName, dirinfo->d_name)) continue;
#else
  cd = opendir(dir);
  if (!cd) goto error_cd;

  while ((dirinfo = readdir(cd)) != NULL) {
    char * restrict tp = tempname;
    size_t d_name_len;
#endif /* UNICODE */

    LOUD(fprintf(stderr, "grokdir: readdir: '%s'\n", dirinfo->d_name));
    if (strcmp(dirinfo->d_name, ".") && strcmp(dirinfo->d_name, "..")) {
      if (!ISFLAG(flags, F_HIDEPROGRESS)) {
        if (delay >= DELAY_COUNT) {
          delay = 0;
          fprintf(stderr, "\rScanning: %ju files, %ju dirs (in %u specified)",
              progress, dir_progress, user_dir_count);
        } else delay++;
      }

      /* Assemble the file's full path name, optimized to avoid strcat() */
      dirlen = strlen(dir);
      d_name_len = strlen(dirinfo->d_name);
      memcpy(tp, dir, dirlen+1);
628 629
      if (dirlen != 0 && tp[dirlen-1] != dir_sep) {
        tp[dirlen] = dir_sep;
630 631
        dirlen++;
      }
632
      if (dirlen + d_name_len + 1 >= (PATHBUF_SIZE * 2)) goto error_overflow;
633 634 635 636 637 638
      tp += dirlen;
      memcpy(tp, dirinfo->d_name, d_name_len);
      tp += d_name_len;
      *tp = '\0';
      d_name_len++;

639 640 641 642 643
      /* Allocate the file_t and the d_name entries */
      newfile = (file_t *)string_malloc(sizeof(file_t));
      if (!newfile) oom("grokdir() file structure");
      newfile->d_name = (char *)string_malloc(dirlen + d_name_len + 2);
      if (!newfile->d_name) oom("grokdir() filename");
644

645
      newfile->next = *filelistp;
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
      newfile->user_order = user_dir_count;
      newfile->size = -1;
      newfile->device = 0;
      newfile->inode = 0;
      newfile->mtime = 0;
      newfile->mode = 0;
#ifdef ON_WINDOWS
 #ifndef NO_HARDLINKS
      newfile->nlink = 0;
 #endif
#endif
#ifndef NO_PERMS
      newfile->uid = 0;
      newfile->gid = 0;
#endif
      newfile->filehash = 0;
      newfile->filehash_partial = 0;
      newfile->duplicates = NULL;
664
      newfile->flags = 0;
665 666 667 668 669 670

      tp = tempname;
      memcpy(newfile->d_name, tp, dirlen + d_name_len);

      if (ISFLAG(flags, F_EXCLUDEHIDDEN)) {
        /* WARNING: Re-used tp here to eliminate a strdup() */
671
        strncpy(tp, newfile->d_name, dirlen + d_name_len);
672 673 674
        tp = basename(tp);
        if (tp[0] == '.' && strcmp(tp, ".") && strcmp(tp, "..")) {
          LOUD(fprintf(stderr, "grokdir: excluding hidden file (-A on)\n"));
675 676
          string_free(newfile->d_name);
          string_free(newfile);
677 678 679 680 681
          continue;
        }
      }

      /* Get file information and check for validity */
682
      const int i = getfilestats(newfile);
683 684
      if (i || newfile->size == -1) {
        LOUD(fprintf(stderr, "grokdir: excluding due to bad stat()\n"));
685 686
        string_free(newfile->d_name);
        string_free(newfile);
687 688 689 690
        continue;
      }

      /* Exclude zero-length files if requested */
691 692
      if (!S_ISDIR(newfile->mode) && newfile->size == 0 && !ISFLAG(flags, F_INCLUDEEMPTY)) {
        LOUD(fprintf(stderr, "grokdir: excluding zero-length empty file (-z not set)\n"));
693 694
        string_free(newfile->d_name);
        string_free(newfile);
695 696 697 698 699 700
        continue;
      }

      /* Exclude files below --xsize parameter */
      if (!S_ISDIR(newfile->mode) && ISFLAG(flags, F_EXCLUDESIZE)) {
        if (
701 702
            ((excludetype == SMALLERTHAN) && (newfile->size < (off_t)excludesize)) ||
            ((excludetype == LARGERTHAN) && (newfile->size > (off_t)excludesize))
703 704
        ) {
          LOUD(fprintf(stderr, "grokdir: excluding based on xsize limit (-x set)\n"));
705 706
          string_free(newfile->d_name);
          string_free(newfile);
707 708 709 710 711 712 713 714
          continue;
        }
      }

#ifndef NO_SYMLINKS
      /* Get lstat() information */
      if (lstat(newfile->d_name, &linfo) == -1) {
        LOUD(fprintf(stderr, "grokdir: excluding due to bad lstat()\n"));
715 716
        string_free(newfile->d_name);
        string_free(newfile);
717 718 719 720 721 722 723 724 725 726 727 728 729
        continue;
      }
#endif

      /* Windows has a 1023 (+1) hard link limit. If we're hard linking,
       * ignore all files that have hit this limit */
#ifdef ON_WINDOWS
 #ifndef NO_HARDLINKS
      if (ISFLAG(flags, F_HARDLINKFILES) && newfile->nlink >= 1024) {
  #ifdef DEBUG
        hll_exclude++;
  #endif
        LOUD(fprintf(stderr, "grokdir: excluding due to Windows 1024 hard link limit\n"));
730 731
        string_free(newfile->d_name);
        string_free(newfile);
732 733 734 735 736 737 738
        continue;
      }
 #endif
#endif
      /* Optionally recurse directories, including symlinked ones if requested */
      if (S_ISDIR(newfile->mode)) {
#ifndef NO_SYMLINKS
739
        if (recurse && (/*ISFLAG(flags, F_FOLLOWLINKS) ||*/ !S_ISLNK(linfo.st_mode))) {
740 741 742 743 744 745 746 747 748 749
          LOUD(fprintf(stderr, "grokdir: directory: recursing (-r/-R)\n"));
          grokdir(newfile->d_name, filelistp, recurse);
        }
#else
        if (recurse) {
          LOUD(fprintf(stderr, "grokdir: directory: recursing (-r/-R)\n"));
          grokdir(newfile->d_name, filelistp, recurse);
        }
#endif
        LOUD(fprintf(stderr, "grokdir: directory: not recursing\n"));
750 751
        string_free(newfile->d_name);
        string_free(newfile);
752 753 754 755 756 757 758 759 760 761 762 763
      } else {
        /* Add regular files to list, including symlink targets if requested */
#ifndef NO_SYMLINKS
        if (S_ISREG(linfo.st_mode) || (S_ISLNK(linfo.st_mode) && ISFLAG(flags, F_FOLLOWLINKS))) {
#else
        if (S_ISREG(newfile->mode)) {
#endif
          *filelistp = newfile;
          filecount++;
          progress++;
        } else {
          LOUD(fprintf(stderr, "grokdir: not a regular file: %s\n", newfile->d_name);)
764 765
          string_free(newfile->d_name);
          string_free(newfile);
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
        }
      }
    }
  }
#ifdef UNICODE
  while (FindNextFile(hFind, &ffd) != 0);
  FindClose(hFind);
#else
  closedir(cd);
#endif


  grokdir_level--;
  if (grokdir_level == 0 && !ISFLAG(flags, F_HIDEPROGRESS)) {
    fprintf(stderr, "\rExamining %ju files, %ju dirs (in %u specified)",
            progress, dir_progress, user_dir_count);
  }
  return;

785 786 787
error_travdone:
  fprintf(stderr, "error: could not stat dir "); fwprint(stderr, dir, 1);
  return;
788
error_cd:
789
  fprintf(stderr, "error: could not chdir to "); fwprint(stderr, dir, 1);
790
  return;
791 792 793
error_overflow:
  fprintf(stderr, "\nerror: a path buffer overflowed\n");
  exit(EXIT_FAILURE);
794 795 796 797 798 799
}

/* Use Jody Bruchon's hash function on part or all of a file */
static hash_t *get_filehash(const file_t * const restrict checkfile,
                const size_t max_read)
{
800
  off_t fsize;
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
  /* This is an array because we return a pointer to it */
  static hash_t hash[1];
  static hash_t chunk[(CHUNK_SIZE / sizeof(hash_t))];
  FILE *file;

  /* Get the file size. If we can't read it, bail out early */
  if (checkfile->size == -1) {
    LOUD(fprintf(stderr, "get_filehash: not hashing because stat() info is bad\n"));
    return NULL;
  }
  fsize = checkfile->size;

  /* Do not read more than the requested number of bytes */
  if (max_read > 0 && fsize > (off_t)max_read)
    fsize = (off_t)max_read;

  /* Initialize the hash and file read parameters (with filehash_partial skipped)
   *
   * If we already hashed the first chunk of this file, we don't want to
   * wastefully read and hash it again, so skip the first chunk and use
   * the computed hash for that chunk as our starting point.
   *
   * WARNING: We assume max_read is NEVER less than CHUNK_SIZE here! */

  *hash = 0;
826
  if (ISFLAG(checkfile->flags, F_HASH_PARTIAL)) {
827 828 829
    *hash = checkfile->filehash_partial;
    /* Don't bother going further if max_read is already fulfilled */
    if (max_read != 0 && max_read <= PARTIAL_HASH_SIZE) {
830
      LOUD(fprintf(stderr, "Partial hash size (%d) >= max_read (%ju), not hashing anymore\n", PARTIAL_HASH_SIZE, (uintmax_t)max_read);)
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
      return hash;
    }
  }
#ifdef UNICODE
  if (!M2W(checkfile->d_name, wstr)) file = NULL;
  else file = _wfopen(wstr, FILE_MODE_RO);
#else
  file = fopen(checkfile->d_name, FILE_MODE_RO);
#endif
  if (file == NULL) {
    fprintf(stderr, "error opening file "); fwprint(stderr, checkfile->d_name, 1);
    return NULL;
  }
  /* Actually seek past the first chunk if applicable
   * This is part of the filehash_partial skip optimization */
846
  if (ISFLAG(checkfile->flags, F_HASH_PARTIAL)) {
847 848 849 850 851 852 853 854 855 856 857 858
    if (fseeko(file, PARTIAL_HASH_SIZE, SEEK_SET) == -1) {
      fclose(file);
      fprintf(stderr, "error seeking in file "); fwprint(stderr, checkfile->d_name, 1);
      return NULL;
    }
    fsize -= PARTIAL_HASH_SIZE;
  }
  /* Read the file in CHUNK_SIZE chunks until we've read it all. */
  while (fsize > 0) {
    size_t bytes_to_read;

    if (interrupt) return 0;
859
    bytes_to_read = (fsize >= CHUNK_SIZE) ? CHUNK_SIZE : (size_t)fsize;
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
    if (fread((void *)chunk, bytes_to_read, 1, file) != 1) {
      fprintf(stderr, "error reading from file "); fwprint(stderr, checkfile->d_name, 1);
      fclose(file);
      return NULL;
    }

    *hash = jody_block_hash(chunk, *hash, bytes_to_read);
    if ((off_t)bytes_to_read > fsize) break;
    else fsize -= (off_t)bytes_to_read;
  }

  fclose(file);

  LOUD(fprintf(stderr, "get_filehash: returning hash: 0x%016jx\n", (uintmax_t)*hash));
  return hash;
}


static inline void registerfile(filetree_t * restrict * const restrict nodeptr,
                const enum tree_direction d, file_t * const restrict file)
{
  filetree_t * restrict branch;

  /* Allocate and initialize a new node for the file */
  branch = (filetree_t *)string_malloc(sizeof(filetree_t));
885
  if (branch == NULL) oom("registerfile() branch");
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
  branch->file = file;
  branch->left = NULL;
  branch->right = NULL;
#ifdef USE_TREE_REBALANCE
  branch->left_weight = 0;
  branch->right_weight = 0;

  /* Attach the new node to the requested branch and the parent */
  switch (d) {
    case LEFT:
      branch->parent = *nodeptr;
      (*nodeptr)->left = branch;
      (*nodeptr)->left_weight++;
      break;
    case RIGHT:
      branch->parent = *nodeptr;
      (*nodeptr)->right = branch;
      (*nodeptr)->right_weight++;
      break;
    case NONE:
      /* For the root of the tree only */
      branch->parent = NULL;
      *nodeptr = branch;
      break;
910 911
    default:
      break;
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
  }

  /* Propagate weights up the tree */
  while (branch->parent != NULL) {
    filetree_t * restrict up;

    up = branch->parent;
    if (up->left == branch) up->left_weight++;
    else if (up->right == branch) up->right_weight++;
    else {
      fprintf(stderr, "Internal error: file tree linkage is broken\n");
      exit(EXIT_FAILURE);
    }
    branch = up;
  }
#else /* USE_TREE_REBALANCE */
  /* Attach the new node to the requested branch and the parent */
  switch (d) {
    case LEFT:
      (*nodeptr)->left = branch;
      break;
    case RIGHT:
      (*nodeptr)->right = branch;
      break;
    case NONE:
937
    default:
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
      /* For the root of the tree only */
      *nodeptr = branch;
      break;
  }

#endif /* USE_TREE_REBALANCE */

  return;
}


/* Experimental tree rebalance code. This slows things down in testing
 * but may be more useful in the future. Pass -DUSE_TREE_REBALANCE
 * to try it. */
#ifdef USE_TREE_REBALANCE

/* How much difference to ignore when considering a rebalance */
#ifndef BALANCE_THRESHOLD
#define BALANCE_THRESHOLD 4
#endif

/* Rebalance the file tree to reduce search depth */
static inline void rebalance_tree(filetree_t * const tree)
{
  filetree_t * restrict promote;
  filetree_t * restrict demote;
  int difference, direction;
#ifdef CONSIDER_IMBALANCE
  int l, r, imbalance;
#endif

  if (!tree) return;

  /* Rebalance all children first */
  if (tree->left_weight > BALANCE_THRESHOLD) rebalance_tree(tree->left);
  if (tree->right_weight > BALANCE_THRESHOLD) rebalance_tree(tree->right);

  /* If weights are within a certain threshold, do nothing */
  direction = tree->right_weight - tree->left_weight;
  difference = direction;
  if (difference < 0) difference = -difference;
  if (difference <= BALANCE_THRESHOLD) return;

  /* Determine if a tree rotation will help, and do it if so */
  if (direction > 0) {
#ifdef CONSIDER_IMBALANCE
    l = tree->right->left_weight + tree->right_weight;
    r = tree->right->right_weight;
    imbalance = l - r;
    if (imbalance < 0) imbalance = -imbalance;
    /* Don't rotate if imbalance will increase */
    if (imbalance >= difference) return;
#endif /* CONSIDER_IMBALANCE */

    /* Rotate the right node up one level */
    promote = tree->right;
    demote = tree;
    /* Attach new parent's left tree to old parent */
    demote->right = promote->left;
    demote->right_weight = promote->left_weight;
    /* Attach old parent to new parent */
    promote->left = demote;
    promote->left_weight = demote->left_weight + demote->right_weight + 1;
    /* Reconnect parent linkages */
    promote->parent = demote->parent;
    if (demote->right) demote->right->parent = demote;
    demote->parent = promote;
    if (promote->parent == NULL) checktree = promote;
    else if (promote->parent->left == demote) promote->parent->left = promote;
    else promote->parent->right = promote;
    return;
  } else if (direction < 0) {
#ifdef CONSIDER_IMBALANCE
    r = tree->left->right_weight + tree->left_weight;
    l = tree->left->left_weight;
    imbalance = r - l;
    if (imbalance < 0) imbalance = -imbalance;
    /* Don't rotate if imbalance will increase */
    if (imbalance >= difference) return;
#endif /* CONSIDER_IMBALANCE */

    /* Rotate the left node up one level */
    promote = tree->left;
    demote = tree;
    /* Attach new parent's right tree to old parent */
    demote->left = promote->right;
    demote->left_weight = promote->right_weight;
    /* Attach old parent to new parent */
    promote->right = demote;
    promote->right_weight = demote->right_weight + demote->left_weight + 1;
    /* Reconnect parent linkages */
    promote->parent = demote->parent;
    if (demote->left) demote->left->parent = demote;
    demote->parent = promote;
    if (promote->parent == NULL) checktree = promote;
    else if (promote->parent->left == demote) promote->parent->left = promote;
    else promote->parent->right = promote;
    return;

  }

  /* Fall through */
  return;
}

#endif /* USE_TREE_REBALANCE */


#ifdef TREE_DEPTH_STATS
#define TREE_DEPTH_UPDATE_MAX() { if (max_depth < tree_depth) max_depth = tree_depth; tree_depth = 0; }
#else
#define TREE_DEPTH_UPDATE_MAX()
#endif

1052 1053

/* Check two files for a match */
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
static file_t **checkmatch(filetree_t * restrict tree, file_t * const restrict file)
{
  int cmpresult = 0;
  const hash_t * restrict filehash;

  LOUD(fprintf(stderr, "checkmatch (\"%s\", \"%s\")\n", tree->file->d_name, file->d_name));

  /* If device and inode fields are equal one of the files is a
   * hard link to the other or the files have been listed twice
   * unintentionally. We don't want to flag these files as
   * duplicates unless the user specifies otherwise. */

  /* Count the total number of comparisons requested */
  DBG(comparisons++;)

/* If considering hard linked files as duplicates, they are
 * automatically duplicates without being read further since
 * they point to the exact same inode. If we aren't considering
 * hard links as duplicates, we just return NULL. */
1073 1074 1075 1076 1077 1078

  cmpresult = check_conditions(tree->file, file);
  switch (cmpresult) {
    case 2: return &tree->file;  /* linked files + -H switch */
    case -2: return NULL;  /* linked files, no -H switch */
    default: break;
1079 1080
  }

1081 1082
  /* If preliminary matching succeeded, move to full file checks */
  if (cmpresult == 0) {
1083 1084
    LOUD(fprintf(stderr, "checkmatch: starting file data comparisons\n"));
    /* Attempt to exclude files quickly with partial file hashing */
1085
    if (!ISFLAG(tree->file->flags, F_HASH_PARTIAL)) {
1086 1087 1088 1089 1090 1091 1092
      filehash = get_filehash(tree->file, PARTIAL_HASH_SIZE);
      if (filehash == NULL) {
        if (!interrupt) fprintf(stderr, "cannot read file "); fwprint(stderr, tree->file->d_name, 1);
        return NULL;
      }

      tree->file->filehash_partial = *filehash;
1093
      SETFLAG(tree->file->flags, F_HASH_PARTIAL);
1094 1095
    }

1096
    if (!ISFLAG(file->flags, F_HASH_PARTIAL)) {
1097 1098 1099 1100 1101 1102 1103
      filehash = get_filehash(file, PARTIAL_HASH_SIZE);
      if (filehash == NULL) {
        if (!interrupt) fprintf(stderr, "cannot read file "); fwprint(stderr, file->d_name, 1);
        return NULL;
      }

      file->filehash_partial = *filehash;
1104
      SETFLAG(file->flags, F_HASH_PARTIAL);
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
    }

    cmpresult = HASH_COMPARE(file->filehash_partial, tree->file->filehash_partial);
    LOUD(if (!cmpresult) fprintf(stderr, "checkmatch: partial hashes match\n"));
    LOUD(if (cmpresult) fprintf(stderr, "checkmatch: partial hashes do not match\n"));
    DBG(partial_hash++;)

    if (file->size <= PARTIAL_HASH_SIZE) {
      LOUD(fprintf(stderr, "checkmatch: small file: copying partial hash to full hash\n"));
      /* filehash_partial = filehash if file is small enough */
1115
      if (!ISFLAG(file->flags, F_HASH_FULL)) {
1116
        file->filehash = file->filehash_partial;
1117
        SETFLAG(file->flags, F_HASH_FULL);
1118 1119
        DBG(small_file++;)
      }
1120
      if (!ISFLAG(tree->file->flags, F_HASH_FULL)) {
1121
        tree->file->filehash = tree->file->filehash_partial;
1122
        SETFLAG(tree->file->flags, F_HASH_FULL);
1123 1124 1125 1126
        DBG(small_file++;)
      }
    } else if (cmpresult == 0) {
      /* If partial match was correct, perform a full file hash match */
1127
      if (!ISFLAG(tree->file->flags, F_HASH_FULL)) {
1128 1129 1130 1131 1132 1133 1134 1135
        did_long_work = 1;
        filehash = get_filehash(tree->file, 0);
        if (filehash == NULL) {
          if (!interrupt) fprintf(stderr, "cannot read file "); fwprint(stderr, tree->file->d_name, 1);
          return NULL;
        }

        tree->file->filehash = *filehash;
1136
        SETFLAG(tree->file->flags, F_HASH_FULL);
1137 1138
      }

1139
      if (!ISFLAG(file->flags, F_HASH_FULL)) {
1140 1141 1142 1143 1144 1145 1146 1147
        did_long_work = 1;
        filehash = get_filehash(file, 0);
        if (filehash == NULL) {
          if (!interrupt) fprintf(stderr, "cannot read file "); fwprint(stderr, file->d_name, 1);
          return NULL;
        }

        file->filehash = *filehash;
1148
        SETFLAG(file->flags, F_HASH_FULL);
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
      }

      /* Full file hash comparison */
      cmpresult = HASH_COMPARE(file->filehash, tree->file->filehash);
      LOUD(if (!cmpresult) fprintf(stderr, "checkmatch: full hashes match\n"));
      LOUD(if (cmpresult) fprintf(stderr, "checkmatch: full hashes do not match\n"));
      DBG(full_hash++);
    } else {
      DBG(partial_elim++);
    }
  }

  if (cmpresult < 0) {
    if (tree->left != NULL) {
      LOUD(fprintf(stderr, "checkmatch: recursing tree: left\n"));
      DBG(left_branch++; tree_depth++;)
      return checkmatch(tree->left, file);
    } else {
      LOUD(fprintf(stderr, "checkmatch: registering file: left\n"));
      registerfile(&tree, LEFT, file);
      TREE_DEPTH_UPDATE_MAX();
      return NULL;
    }
  } else if (cmpresult > 0) {
    if (tree->right != NULL) {
      LOUD(fprintf(stderr, "checkmatch: recursing tree: right\n"));
      DBG(right_branch++; tree_depth++;)
      return checkmatch(tree->right, file);
    } else {
      LOUD(fprintf(stderr, "checkmatch: registering file: right\n"));
      registerfile(&tree, RIGHT, file);
      TREE_DEPTH_UPDATE_MAX();
      return NULL;
    }
  } else {
    /* All compares matched */
    DBG(partial_to_full++;)
    TREE_DEPTH_UPDATE_MAX();
    LOUD(fprintf(stderr, "checkmatch: files appear to match based on hashes\n"));
    return &tree->file;
  }
  /* Fall through - should never be reached */
  return NULL;
}


/* Do a byte-by-byte comparison in case two different files produce the
   same signature. Unlikely, but better safe than sorry. */
static inline int confirmmatch(FILE * const restrict file1, FILE * const restrict file2)
{
  static char c1[CHUNK_SIZE];
  static char c2[CHUNK_SIZE];
1201 1202
  size_t r1;
  size_t r2;
1203

1204
  LOUD(fprintf(stderr, "confirmmatch running\n"));
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226

  did_long_work = 1;
  fseek(file1, 0, SEEK_SET);
  fseek(file2, 0, SEEK_SET);

  do {
    if (interrupt) return 0;
    r1 = fread(c1, sizeof(char), CHUNK_SIZE, file1);
    r2 = fread(c2, sizeof(char), CHUNK_SIZE, file2);

    if (r1 != r2) return 0; /* file lengths are different */
    if (memcmp (c1, c2, r1)) return 0; /* file contents are different */
  } while (r2);

  return 1;
}


/* Count the following statistics:
   - Maximum number of files in a duplicate set (length of longest dupe chain)
   - Number of non-zero-length files that have duplicates (if n_files != NULL)
   - Total number of duplicate file sets (groups) */
1227
extern unsigned int get_max_dupes(const file_t *files, unsigned int * const restrict max,
1228 1229 1230 1231 1232 1233 1234 1235
                unsigned int * const restrict n_files) {
  unsigned int groups = 0;

  *max = 0;
  if (n_files) *n_files = 0;

  while (files) {
    unsigned int n_dupes;
1236
    if (ISFLAG(files->flags, F_HAS_DUPES)) {
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
      groups++;
      if (n_files && files->size) (*n_files)++;
      n_dupes = 1;
      for (file_t *curdupe = files->duplicates; curdupe; curdupe = curdupe->duplicates) n_dupes++;
      if (n_dupes > *max) *max = n_dupes;
    }
    files = files->next;
  }
  return groups;
}


static int sort_pairs_by_param_order(file_t *f1, file_t *f2)
{
  if (!ISFLAG(flags, F_USEPARAMORDER)) return 0;
  if (f1->user_order < f2->user_order) return -sort_direction;
  if (f1->user_order > f2->user_order) return sort_direction;
  return 0;
}


static int sort_pairs_by_mtime(file_t *f1, file_t *f2)
{
  int po = sort_pairs_by_param_order(f1, f2);

  if (po != 0) return po;

  if (f1->mtime < f2->mtime) return -sort_direction;
  else if (f1->mtime > f2->mtime) return sort_direction;

  return 0;
}


static int sort_pairs_by_filename(file_t *f1, file_t *f2)
{
  int po = sort_pairs_by_param_order(f1, f2);

  if (po != 0) return po;

1277
  return numeric_sort(f1->d_name, f2->d_name, sort_direction);
1278 1279 1280 1281 1282 1283 1284 1285 1286
}


static void registerpair(file_t **matchlist, file_t *newmatch,
                int (*comparef)(file_t *f1, file_t *f2))
{
  file_t *traverse;
  file_t *back;

1287 1288 1289 1290 1291
  /* NULL pointer sanity checks */
  if (!matchlist || !newmatch || !comparef) return;

  LOUD(fprintf(stderr, "registerpair: '%s', '%s'\n", (*matchlist)->d_name, newmatch->d_name);)
  SETFLAG((*matchlist)->flags, F_HAS_DUPES);
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
  back = NULL;
  traverse = *matchlist;

  /* FIXME: This needs to be changed! As it currently stands, the compare
   * function only runs on a pair as it is registered and future pairs can
   * mess up the sort order. A separate sorting function should happen before
   * the dupe chain is acted upon rather than while pairs are registered. */
  while (traverse) {
    if (comparef(newmatch, traverse) <= 0) {
      newmatch->duplicates = traverse;

      if (!back) {
        *matchlist = newmatch; /* update pointer to head of list */
1305 1306
        SETFLAG(newmatch->flags, F_HAS_DUPES);
        CLEARFLAG(traverse->flags, F_HAS_DUPES); /* flag is only for first file in dupe chain */
1307 1308 1309 1310 1311 1312
      } else back->duplicates = newmatch;

      break;
    } else {
      if (traverse->duplicates == 0) {
        traverse->duplicates = newmatch;
1313
        if (!back) SETFLAG(traverse->flags, F_HAS_DUPES);
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330

        break;
      }
    }

    back = traverse;
    traverse = traverse->duplicates;
  }
  return;
}


static inline void help_text(void)
{
  printf("Usage: jdupes [options] DIRECTORY...\n\n");

  printf(" -A --nohidden    \texclude hidden files from consideration\n");
1331
#ifdef ENABLE_BTRFS
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
  printf(" -B --dedupe      \tSend matches to btrfs for block-level deduplication\n");
#endif
  printf(" -d --delete      \tprompt user for files to preserve and delete all\n");
  printf("                  \tothers; important: under particular circumstances,\n");
  printf("                  \tdata may be lost when using this option together\n");
  printf("                  \twith -s or --symlinks, or when specifying a\n");
  printf("                  \tparticular directory more than once; refer to the\n");
  printf("                  \tdocumentation for additional information\n");
  printf(" -f --omitfirst   \tomit the first file in each set of matches\n");
  printf(" -h --help        \tdisplay this help message\n");
#ifndef NO_HARDLINKS
1343 1344
  printf(" -H --hardlinks   \ttreat any linked files as duplicate files. Normally\n");
  printf("                  \tlinked files are treated as non-duplicates for safety\n");
1345 1346 1347 1348
#endif
  printf(" -i --reverse     \treverse (invert) the match sort order\n");
  printf(" -I --isolate     \tfiles in the same specified directory won't match\n");
#ifndef NO_SYMLINKS
1349
  printf(" -l --linksoft    \tmake relative symlinks for duplicates w/o prompting\n");
1350 1351 1352 1353 1354 1355 1356 1357
#endif
#ifndef NO_HARDLINKS
  printf(" -L --linkhard    \thard link all duplicate files without prompting\n");
 #ifdef ON_WINDOWS
  printf("                  \tWindows allows a maximum of 1023 hard links per file\n");
 #endif /* ON_WINDOWS */
#endif /* NO_HARDLINKS */
  printf(" -m --summarize   \tsummarize dupe information\n");
1358
  //printf(" -n --noempty     \texclude zero-length files from consideration\n");
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
  printf(" -N --noprompt    \ttogether with --delete, preserve the first file in\n");
  printf("                  \teach set of duplicates and delete the rest without\n");
  printf("                  \tprompting the user\n");
  printf(" -o --order=BY    \tselect sort order for output, linking and deleting; by\n");
  printf(" -O --paramorder  \tParameter order is more important than selected -O sort\n");
  printf("                  \tmtime (BY=time) or filename (BY=name, the default)\n");
#ifndef NO_PERMS
  printf(" -p --permissions \tdon't consider files with different owner/group or\n");
  printf("                  \tpermission bits as duplicates\n");
#endif
  printf(" -r --recurse     \tfor every directory given follow subdirectories\n");
  printf("                  \tencountered within\n");
  printf(" -R --recurse:    \tfor each directory given after this option follow\n");
  printf("                  \tsubdirectories encountered within (note the ':' at\n");
  printf("                  \tthe end of the option, manpage for more details)\n");
#ifndef NO_SYMLINKS
  printf(" -s --symlinks    \tfollow symlinks\n");
#endif
  printf(" -S --size        \tshow size of duplicate files\n");
  printf(" -q --quiet       \thide progress indicator\n");
/* This is undocumented in the quick help because it is a dangerous option. If you
 * really want it, uncomment it here, and may your data rest in peace. */
/*  printf(" -Q --quick       \tskip byte-by-byte duplicate verification. WARNING:\n");
  printf("                  \tthis may delete non-duplicates! Read the manual first!\n"); */
  printf(" -v --version     \tdisplay jdupes version and license information\n");
  printf(" -x --xsize=SIZE  \texclude files of size < SIZE bytes from consideration\n");
  printf("    --xsize=+SIZE \t'+' specified before SIZE, exclude size > SIZE\n");
  printf("                  \tK/M/G size suffixes can be used (case-insensitive)\n");
1387
  printf(" -z --zeromatch   \tconsider zero-length files to be duplicates\n");
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
  printf(" -Z --softabort   \tIf the user aborts (i.e. CTRL-C) act on matches so far\n");
#ifdef OMIT_GETOPT_LONG
  printf("Note: Long options are not supported in this build.\n\n");
#endif
}


#ifdef UNICODE
int wmain(int argc, wchar_t **wargv)
#else
int main(int argc, char **argv)
#endif
{
  static file_t *files = NULL;
  static file_t *curfile;
  static char **oldargv;
  static char *endptr;
  static int firstrecurse;
  static int opt;
  static int pm = 1;
  static ordertype_t ordertype = ORDER_NAME;

#ifndef OMIT_GETOPT_LONG
  static const struct option long_options[] =
  {
    { "loud", 0, 0, '@' },
    { "nohidden", 0, 0, 'A' },
    { "dedupe", 0, 0, 'B' },
    { "delete", 0, 0, 'd' },
    { "debug", 0, 0, 'D' },
    { "omitfirst", 0, 0, 'f' },
    { "help", 0, 0, 'h' },
#ifndef NO_HARDLINKS
    { "hardlinks", 0, 0, 'H' },
    { "linkhard", 0, 0, 'L' },
#endif
    { "reverse", 0, 0, 'i' },
    { "isolate", 0, 0, 'I' },
    { "summarize", 0, 0, 'm'},
    { "summary", 0, 0, 'm' },
    { "noempty", 0, 0, 'n' },
    { "noprompt", 0, 0, 'N' },
    { "order", 1, 0, 'o' },
    { "paramorder", 0, 0, 'O' },
#ifndef NO_PERMS
    { "permissions", 0, 0, 'p' },
#endif
    { "quiet", 0, 0, 'q' },
    { "quick", 0, 0, 'Q' },
    { "recurse", 0, 0, 'r' },
    { "recursive", 0, 0, 'r' },
    { "recurse:", 0, 0, 'R' },
    { "recursive:", 0, 0, 'R' },
#ifndef NO_SYMLINKS
1442
    { "linksoft", 0, 0, 'l' },
1443 1444 1445 1446 1447
    { "symlinks", 0, 0, 's' },
#endif
    { "size", 0, 0, 'S' },
    { "version", 0, 0, 'v' },
    { "xsize", 1, 0, 'x' },
1448
    { "zeromatch", 0, 0, 'z' },
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
    { "softabort", 0, 0, 'Z' },
    { 0, 0, 0, 0 }
  };
#define GETOPT getopt_long
#else
#define GETOPT getopt
#endif

#ifdef UNICODE
  /* Create a UTF-8 **argv from the wide version */
  static char **argv;
1460 1461
  argv = (char **)string_malloc(sizeof(char *) * argc);
  if (!argv) oom("main() unicode argv");
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
  widearg_to_argv(argc, wargv, argv);
  /* Only use UTF-16 for terminal output, else use UTF-8 */
  if (!_isatty(_fileno(stdout))) out_mode = _O_U8TEXT;
  else out_mode = _O_U16TEXT;
#endif /* UNICODE */

  program_name = argv[0];

  oldargv = cloneargs(argc, argv);

  while ((opt = GETOPT(argc, argv,
1473
  "@ABdDfhHiIlLmnNOpqQrRsSvzZo:x:"
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
#ifndef OMIT_GETOPT_LONG
          , long_options, NULL
#endif
         )) != EOF) {
    switch (opt) {
    case 'A':
      SETFLAG(flags, F_EXCLUDEHIDDEN);
      break;
    case 'd':
      SETFLAG(flags, F_DELETEFILES);
      break;
    case 'D':
#ifdef DEBUG
      SETFLAG(flags, F_DEBUG);
#endif
      break;
    case 'f':
      SETFLAG(flags, F_OMITFIRST);
      break;
    case 'h':
      help_text();
      exit(EXIT_FAILURE);
#ifndef NO_HARDLINKS
    case 'H':
      SETFLAG(flags, F_CONSIDERHARDLINKS);
      break;
    case 'L':
      SETFLAG(flags, F_HARDLINKFILES);
      break;
#endif
    case 'i':
      SETFLAG(flags, F_REVERSESORT);
      break;
    case 'I':
      SETFLAG(flags, F_ISOLATE);
      break;
    case 'm':
      SETFLAG(flags, F_SUMMARIZEMATCHES);
      break;
    case 'n':
1514
      //fprintf(stderr, "note: -n/--noempty is the default behavior now and is deprecated.\n");
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
      break;
    case 'N':
      SETFLAG(flags, F_NOPROMPT);
      break;
    case 'O':
      SETFLAG(flags, F_USEPARAMORDER);
      break;
    case 'p':
      SETFLAG(flags, F_PERMISSIONS);
      break;
    case 'q':
      SETFLAG(flags, F_HIDEPROGRESS);
      break;
    case 'Q':
      SETFLAG(flags, F_QUICKCOMPARE);
      break;
    case 'r':
      SETFLAG(flags, F_RECURSE);
      break;
    case 'R':
      SETFLAG(flags, F_RECURSEAFTER);
      break;
#ifndef NO_SYMLINKS
    case 'l':
      SETFLAG(flags, F_MAKESYMLINKS);
      break;
    case 's':
      SETFLAG(flags, F_FOLLOWLINKS);
      break;
#endif
    case 'S':
      SETFLAG(flags, F_SHOWSIZE);
      break;
1548 1549 1550
    case 'z':
      SETFLAG(flags, F_INCLUDEEMPTY);
      break;
1551 1552 1553 1554 1555 1556 1557 1558 1559
    case 'Z':
      SETFLAG(flags, F_SOFTABORT);
      break;
    case 'x':
      SETFLAG(flags, F_EXCLUDESIZE);
      if (*optarg == '+') {
        excludetype = LARGERTHAN;
        optarg++;
      }
1560
      excludesize = (uintmax_t)strtoull(optarg, &endptr, 0);
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
      switch (*endptr) {
        case 'k':
        case 'K':
          excludesize = excludesize * 1024;
          endptr++;
          break;
        case 'm':
        case 'M':
          excludesize = excludesize * 1024 * 1024;
          endptr++;
          break;
        case 'g':
        case 'G':
          excludesize = excludesize * 1024 * 1024 * 1024;
          endptr++;
          break;
        default:
          break;
      }
      if (*endptr != '\0') {
        fprintf(stderr, "invalid value for --xsize: '%s'\n", optarg);
        exit(EXIT_FAILURE);
      }
      break;
    case '@':
#ifdef LOUD_DEBUG
      SETFLAG(flags, F_DEBUG | F_LOUD | F_HIDEPROGRESS);
#endif
      break;
    case 'v':
      printf("jdupes %s (%s)\n", VER, VERDATE);
      printf("Compile-time extensions:");
      if (*extensions != NULL) {
        int c = 0;
        while (extensions[c] != NULL) {
          printf(" %s", extensions[c]);
          c++;
        }
      } else printf(" none");
      printf("\nCopyright (C) 2015-2016 by Jody Bruchon\n");
      printf("\nPermission is hereby granted, free of charge, to any person\n");
      printf("obtaining a copy of this software and associated documentation files\n");
      printf("(the \"Software\"), to deal in the Software without restriction,\n");
      printf("including without limitation the rights to use, copy, modify, merge,\n");
      printf("publish, distribute, sublicense, and/or sell copies of the Software,\n");
      printf("and to permit persons to whom the Software is furnished to do so,\n");
      printf("subject to the following conditions:\n\n");
      printf("The above copyright notice and this permission notice shall be\n");
      printf("included in all copies or substantial portions of the Software.\n\n");
      printf("THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n");
      printf("OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n");
      printf("MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n");
      printf("IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n");
      printf("CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n");
      printf("TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n");
      printf("SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n");
      exit(EXIT_SUCCESS);
    case 'o':
      if (!strncasecmp("name", optarg, 5)) {
        ordertype = ORDER_NAME;
      } else if (!strncasecmp("time", optarg, 5)) {
        ordertype = ORDER_TIME;
      } else {
        fprintf(stderr, "invalid value for --order: '%s'\n", optarg);
        exit(EXIT_FAILURE);
      }
      break;
    case 'B':
1629
#ifdef ENABLE_BTRFS
1630 1631 1632
    SETFLAG(flags, F_DEDUPEFILES);
    /* btrfs will do the byte-for-byte check itself */
    SETFLAG(flags, F_QUICKCOMPARE);
1633
    /* It is completely useless to dedupe zero-length extents */
1634
    CLEARFLAG(flags, F_INCLUDEEMPTY);
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
#else
    fprintf(stderr, "This program was built without btrfs support\n");
    exit(EXIT_FAILURE);
#endif
    break;

    default:
      fprintf(stderr, "Try `jdupes --help' for more information.\n");
      exit(EXIT_FAILURE);
    }
  }

  if (optind >= argc) {
    fprintf(stderr, "no directories specified (use -h option for help)\n");
    exit(EXIT_FAILURE);
  }

  if (ISFLAG(flags, F_ISOLATE) && optind == (argc - 1)) {
    fprintf(stderr, "Isolation requires at least two directories on the command line\n");
    exit(EXIT_FAILURE);
  }

  if (ISFLAG(flags, F_RECURSE) && ISFLAG(flags, F_RECURSEAFTER)) {
    fprintf(stderr, "options --recurse and --recurse: are not compatible\n");
    exit(EXIT_FAILURE);
  }

  if (ISFLAG(flags, F_SUMMARIZEMATCHES) && ISFLAG(flags, F_DELETEFILES)) {
    fprintf(stderr, "options --summarize and --delete are not compatible\n");
    exit(EXIT_FAILURE);
  }

1667 1668 1669 1670 1671
#ifdef ENABLE_BTRFS
  if (ISFLAG(flags, F_CONSIDERHARDLINKS) && ISFLAG(flags, F_DEDUPEFILES))
    fprintf(stderr, "warning: option --dedupe overrides the behavior of --hardlinks\n");
#endif

1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
  /* If pm == 0, call printmatches() */
  pm = !!ISFLAG(flags, F_SUMMARIZEMATCHES) +
      !!ISFLAG(flags, F_DELETEFILES) +
      !!ISFLAG(flags, F_HARDLINKFILES) +
      !!ISFLAG(flags, F_MAKESYMLINKS) +
      !!ISFLAG(flags, F_DEDUPEFILES);

  if (pm > 1) {
      fprintf(stderr, "Only one of --summarize, --delete, --linkhard, --linksoft, or --dedupe\nmay be used\n");
      exit(EXIT_FAILURE);
  }
  if (pm == 0) SETFLAG(flags, F_PRINTMATCHES);

  if (ISFLAG(flags, F_RECURSEAFTER)) {
    firstrecurse = nonoptafter("--recurse:", argc, oldargv, argv, optind);

    if (firstrecurse == argc)
      firstrecurse = nonoptafter("-R", argc, oldargv, argv, optind);

    if (firstrecurse == argc) {
      fprintf(stderr, "-R option must be isolated from other options\n");
      exit(EXIT_FAILURE);
    }

    /* F_RECURSE is not set for directories before --recurse: */
    for (int x = optind; x < firstrecurse; x++) {
1698
      slash_convert(argv[x]);
1699 1700 1701 1702 1703 1704 1705 1706
      grokdir(argv[x], &files, 0);
      user_dir_count++;
    }

    /* Set F_RECURSE for directories after --recurse: */
    SETFLAG(flags, F_RECURSE);

    for (int x = firstrecurse; x < argc; x++) {
1707
      slash_convert(argv[x]);
1708 1709 1710 1711 1712
      grokdir(argv[x], &files, 1);
      user_dir_count++;
    }
  } else {
    for (int x = optind; x < argc; x++) {
1713
      slash_convert(argv[x]);
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
      grokdir(argv[x], &files, ISFLAG(flags, F_RECURSE));
      user_dir_count++;
    }
  }

  if (ISFLAG(flags, F_REVERSESORT)) sort_direction = -1;
  if (!ISFLAG(flags, F_HIDEPROGRESS)) fprintf(stderr, "\n");
  if (!files) exit(EXIT_SUCCESS);

  curfile = files;

  /* Catch CTRL-C */
  signal(SIGINT, sighandler);

  while (curfile) {
    static uintmax_t progress = 0;
    static uintmax_t dupecount = 0;
    static file_t **match = NULL;
    static FILE *file1;
    static FILE *file2;
    static off_t delay = DELAY_COUNT;
#ifdef USE_TREE_REBALANCE
    static unsigned int depth_threshold = INITIAL_DEPTH_THRESHOLD;
#endif

    if (interrupt) {
      fprintf(stderr, "\nStopping file scan due to user abort\n");
      if (!ISFLAG(flags, F_SOFTABORT)) exit(EXIT_FAILURE);
      interrupt = 0;  /* reset interrupt for re-use */
      goto skip_file_scan;
    }

    LOUD(fprintf(stderr, "\nMAIN: current file: %s\n", curfile->d_name));

    if (!checktree) registerfile(&checktree, NONE, curfile);
    else match = checkmatch(checktree, curfile);

#ifdef USE_TREE_REBALANCE
    /* Rebalance the match tree after a certain number of files processed */
    if (max_depth > depth_threshold) {
      rebalance_tree(checktree);
      max_depth = 0;
      if (depth_threshold < 512) depth_threshold <<= 1;
      else depth_threshold += 64;
    }
#endif /* USE_TREE_REBALANCE */

    /* Byte-for-byte check that a matched pair are actually matched */
    if (match != NULL) {
      /* Quick comparison mode will never run confirmmatch()
       * Also skip match confirmation for hard-linked files
       * (This set of comparisons is ugly, but quite efficient) */
      if (ISFLAG(flags, F_QUICKCOMPARE) ||
           (ISFLAG(flags, F_CONSIDERHARDLINKS) &&
           (curfile->inode == (*match)->inode) &&
           (curfile->device == (*match)->device))
         ) {
        LOUD(fprintf(stderr, "MAIN: notice: quick compare match (-Q)\n"));
        registerpair(match, curfile,
            (ordertype == ORDER_TIME) ? sort_pairs_by_mtime : sort_pairs_by_filename);
        dupecount++;
        goto skip_full_check;
      }

#ifdef UNICODE
      if (!M2W(curfile->d_name, wstr)) file1 = NULL;
      else file1 = _wfopen(wstr, FILE_MODE_RO);
#else
      file1 = fopen(curfile->d_name, FILE_MODE_RO);
#endif
      if (!file1) {
        curfile = curfile->next;
        continue;
      }

#ifdef UNICODE
      if (!M2W((*match)->d_name, wstr)) file2 = NULL;
      else file2 = _wfopen(wstr, FILE_MODE_RO);
#else
      file2 = fopen((*match)->d_name, FILE_MODE_RO);
#endif
      if (!file2) {
        fclose(file1);
        curfile = curfile->next;
        continue;
      }

      if (confirmmatch(file1, file2)) {
        LOUD(fprintf(stderr, "MAIN: registering matched file pair\n"));
        registerpair(match, curfile,
            (ordertype == ORDER_TIME) ? sort_pairs_by_mtime : sort_pairs_by_filename);
        dupecount++;
      } DBG(else hash_fail++;)

      fclose(file1);
      fclose(file2);
    }

skip_full_check:
    curfile = curfile->next;

    if (!ISFLAG(flags, F_HIDEPROGRESS)) {
      /* If file size is larger than 1 MiB, make progress update faster
       * If confirmmatch() is run on a file, speed up progress even further */
      if (curfile != NULL && did_long_work) {
        delay += (curfile->size >> 20);
        did_long_work = 0;
      }
      if (match != NULL) delay++;
      if ((delay >= DELAY_COUNT)) {
        delay = 0;
        fprintf(stderr, "\rProgress [%ju/%ju, %ju pairs matched] %ju%%", progress, filecount,
          dupecount, (progress * 100) / filecount);
      } else delay++;
    }
    progress++;
  }

  if (!ISFLAG(flags, F_HIDEPROGRESS)) fprintf(stderr, "\r%60s\r", " ");

skip_file_scan:
  /* Stop catching CTRL+C */
  signal(SIGINT, SIG_DFL);
  if (ISFLAG(flags, F_DELETEFILES)) {
    if (ISFLAG(flags, F_NOPROMPT)) deletefiles(files, 0, 0);
    else deletefiles(files, 1, stdin);
  }
  if (ISFLAG(flags, F_SUMMARIZEMATCHES)) summarizematches(files);
#ifndef NO_SYMLINKS
  if (ISFLAG(flags, F_MAKESYMLINKS)) linkfiles(files, 0);
#endif
#ifndef NO_HARDLINKS
  if (ISFLAG(flags, F_HARDLINKFILES)) linkfiles(files, 1);
#endif /* NO_HARDLINKS */
1848
#ifdef ENABLE_BTRFS
1849
  if (ISFLAG(flags, F_DEDUPEFILES)) dedupefiles(files);
1850
#endif /* ENABLE_BTRFS */
1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
  if (ISFLAG(flags, F_PRINTMATCHES)) printmatches(files);

  string_malloc_destroy();

#ifdef DEBUG
  if (ISFLAG(flags, F_DEBUG)) {
    fprintf(stderr, "\n%d partial (+%d small) -> %d full hash -> %d full (%d partial elim) (%d hash%u fail)\n",
        partial_hash, small_file, full_hash, partial_to_full,
        partial_elim, hash_fail, (unsigned int)sizeof(hash_t)*8);
    fprintf(stderr, "%ju total files, %ju comparisons, branch L %u, R %u, both %u\n",
        filecount, comparisons, left_branch, right_branch,
        left_branch + right_branch);
1863 1864
    fprintf(stderr, "Max tree depth: %u; SMA: allocs %ju, free %ju, fail %ju, reuse %ju, scan %ju, tails %ju\n",
        max_depth, sma_allocs, sma_free_good, sma_free_ignored,
1865
        sma_free_reclaimed, sma_free_scanned, sma_free_tails);
1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
#ifdef ON_WINDOWS
 #ifndef NO_HARDLINKS
    if (ISFLAG(flags, F_HARDLINKFILES))
      fprintf(stderr, "Exclusions based on Windows hard link limit: %u\n", hll_exclude);
 #endif
#endif
  }
#endif /* DEBUG */

  exit(EXIT_SUCCESS);
}