Source

dupfiles / dupfiles.c

Full commit
  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
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
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
/*
  Daybo Logic DupFiles by David Duncan Ross Palmer.
  This source code remains the intellectual property of Daybo Logic.
  Copyright 2005-2006 Daybo Logic, all rights reserved.

  See license.txt for more information.
*/

#include <assert.h>
#include <stdio.h> /* Output to the console */
#include <stdlib.h> /* For EXIT_SUCCESS */
#include <string.h>
#include <limits.h>
#include <sys/stat.h> /* POSIX dependant */

#ifdef __UNIX__
# include <unistd.h> /* UNIX specific header */
#endif

#ifdef HAVE_STDINT_H
# include <stdint.h>
#else
/*# include "../shared/dybocryp-1.1.0/stdint.h99"*/
#endif /*HAVE_STDINT_H*/

#ifdef HAVE_STDBOOL_H
# include <stdbool.h>
#else
# include "stdbool.h99"
#endif /*HAVE_STDBOOL_H*/

#ifdef HDRSTOP
# pragma hdrstop
#endif /*HDRSTOP*/

#include "ll.h" /* Generic linked list */
#include "daybocrypt.h" /* One way hash functions */
/*-----------------------------------------------------------*/
/*
  If you want to use stdout for stderr output, define ONE_OUTPUT
*/
#ifdef ONE_OUTPUT
# define HERROR stdout
#else
# define HERROR stderr
#endif /*ONE_OUTPUT*/

#define HASHLEN DAYBOCRYPT_MD5_HASHLEN
#define HASHCTX MD5_CTX

/* First we need a type to store the entry for one file */
struct file_node {
  char* fileName; /* Dynamically allocated */
  unsigned char digest[HASHLEN];
  bool matched; /* Used to stop bi-directional matches */
};

enum addFileError {
  afSuccess,
  afDuplicate, /* Duplicate filename dropped */
  afMemory,    /* Memory exhausted */
  afParam,     /* Invalid parameter */
  afCantOpen   /* Cannot open the file */
};

/* Error numbers */
#define ERROR_SUCCESS        (0)
#define ERROR_MEMORY         (1)
#define ERROR_BADOPT         (2)
#define ERROR_DUPFILE        (3)
#define ERROR_INTERNAL_PARAM (4)
#define ERROR_UNKNOWN        (5)
#define ERROR_CANTOPEN       (6)
/*-------------------------------------------------------------------------*/
static struct link_ptrs FileList;

static struct {
  bool Quiet;
  bool Unlink;
  bool Mismatches;
  bool Verbose;
  bool Debug;
  bool Help;
  bool NoMoreOptions;
} Options;

#ifdef RCS_STAMPS
static char rcsid[] = "$Id: dupfiles.c,v 0.6 2006/12/30 11:19:00 ddrp Exp $";
#endif /*RCS_STAMPS*/
/*-------------------------------------------------------------------------*/
static void Title(void);
static void Help(void);
static enum addFileError AddAndHashFile(
  const char *FileName
);
static enum addFileError AddFileInternal(
  const char *FileName
);
static bool IsFileHere(
  const char *FileName
);
static const char *GetErrorMessage(
  const unsigned int ErrNum
);
static void PrintErrorMessage(
  const unsigned int ErrNum
);
static char *Chomp(
  char *Str
);
static bool HashFile(
  const char *FileName,
  unsigned char Hash[HASHLEN]
);
static void SearchDups(void);
#if 0
static void PrintHash(
  const char *FileName,
  const unsigned char Hash[HASHLEN]
);
#endif /*0*/
static bool AndMD5(
  const unsigned char DigestA[HASHLEN],
  const unsigned char DigestB[HASHLEN]
);
static bool TestZeroMD5Sum(
  const unsigned char Digest[HASHLEN]
);

#ifdef RCS_STAMPS
static void Unused(
  void *Arg,
  int FakeCall
);
#endif /*RCS_STAMPS*/
/*-----------------------------------------------------------*/
int main(
  const int argc,
  const char *argv[]
)
{
  int argi;

  #ifdef RCS_STAMPS
    Unused(rcsid, 0);
  #endif /*RCS_STAMPS*/

  link_ptrs_init(&FileList, sizeof(struct file_node));
  for ( argi = 1; argi < argc; argi++ ) {
    if ( (!Options.NoMoreOptions) && argv[argi][0] == '-' ) { /* An option? */
      if ( (strcmp(argv[argi], "--quiet") == 0) || (strcmp(argv[argi], "-q") == 0) ) {
        Options.Quiet = 1;
        continue;
      }
      if ( (strcmp(argv[argi], "--unlink") == 0 ) || (strcmp(argv[argi], "-u") == 0) ) {
        Options.Unlink = 1;
        continue;
      }
      if ( (strcmp(argv[argi], "--mismatches") == 0) || (strcmp(argv[argi], "-m") == 0) ) {
        Options.Mismatches = 1;
        continue;
      }
      if ( (strcmp(argv[argi], "--verbose") == 0) || (strcmp(argv[argi], "-v") == 0) ) {
        Options.Verbose = 1;
        continue;
      }
      if ( (strcmp(argv[argi], "--debug") == 0) || ( strcmp(argv[argi], "-d") == 0) ) {
        Options.Verbose = 1; /* Implied */
        Options.Debug = 1;
        continue;
      }
      if ( (strcmp(argv[argi], "--help") == 0) || (strcmp(argv[argi], "-h") == 0) ) {
        Options.Help = 1;
        continue;
      }
      if ( (strcmp(argv[argi], "--") == 0) ) {
        Options.NoMoreOptions = 1;
        continue;
      }
      fprintf(HERROR, "%s: %s\n", GetErrorMessage(ERROR_BADOPT), argv[argi]);
    }
    else {
      if ( AddAndHashFile(argv[argi]) == afMemory )
        break;
    }
  }

  if ( !Options.Quiet ) Title();

  if ( Options.Help ) {
    Help();
  }
  else {
    if ( !FileList.Count(&FileList) ) { /* No command line files? */
      /* Now move on to stdin filenames */
      while ( !feof(stdin) ) {
        char oneFile[FILENAME_MAX+1];
        if ( fgets(oneFile, sizeof(oneFile), stdin) ) {
          Chomp(oneFile);
          if ( AddAndHashFile(oneFile) == afMemory )
            break;
        }
      }
    }
  }

  if ( !FileList.Count(&FileList) ) {
    printf("No files specified.\nNothing to do.\n");
  }
  else
    SearchDups();

  return EXIT_SUCCESS;
}
/*-----------------------------------------------------------*/
static void Title()
{
  const char* hashLegal;

  printf(
    "Daybo Logic DupFiles 0.6 (20061230) Copyright (C) "
    "2005-2006 David D. R. Palmer\n"
  );
  hashLegal = daybocrypt_MD5GetLegalString();
  if ( hashLegal )
    printf("%s\n", hashLegal);
  putchar('\n');
}
/*-----------------------------------------------------------*/
static void Help()
{
  printf("dupfiles [options] [filenames ...]\n");
  printf("-h (--help) : Get help for usage (this)\n");
  printf("-q (--quiet) : Don't print copyright banner (useful for automation)\n");
  printf("-u (--unlink) : Delete duplicates\n");
  printf("-m (--mismatches) : Display mismatches as well as matches\n");
  printf("-v (--verbose) : Display progress and such\n");
  printf("-d (--debug) : Display extra verbose debug crap, implies -v\n");
  printf("-V (--version) : Display version info and exit\n");
  printf("--: Don\'t accept further options.\n\n");

  printf("dupfiles can accept filenames via the command line or standard input\n");
  printf("stdin is only read if no filenames are specified on the command line.\n\n");
}
/*-------------------------------------------------------------------------*/
static enum addFileError AddAndHashFile(
  const char *FileName
)
{
  /* Wrapper which prints messages */
  enum addFileError afe;

  if ( Options.Debug )
    printf("Adding \"%s\"...\n", FileName);

  afe = AddFileInternal(FileName);
  if ( afe == afSuccess ) {
    struct file_node node;
    FileList.GetTail(&FileList, &node);

    if ( Options.Verbose )
      printf("Digesting \"%s\"...", node.fileName);

    if ( HashFile(node.fileName, node.digest) ) {
      if ( Options.Verbose )
        puts("OK");

      FileList.SetTail(&FileList, &node);
    }
    else {
      if ( Options.Verbose )
        puts("FAIL");

      afe = afCantOpen;
    }
  }

  if ( afe != afSuccess ) {
    if ( afe == afDuplicate )
      fprintf(HERROR, "%s - %s\n", GetErrorMessage(ERROR_DUPFILE), FileName);
    else if ( afe == afMemory )
      fprintf(HERROR, "%s - %s\n", GetErrorMessage(ERROR_MEMORY), FileName);
    else if ( afe == afCantOpen )
      fprintf(HERROR, "%s - %s\n", GetErrorMessage(ERROR_CANTOPEN), FileName);
    else if ( afe == afParam )
      PrintErrorMessage(ERROR_INTERNAL_PARAM);
    else
      PrintErrorMessage(ERROR_UNKNOWN);
  }

  return afe;
}
/*-------------------------------------------------------------------------*/
static enum addFileError AddFileInternal(
  const char *FileName
)
{
  struct file_node newFile;

  assert(FileName);
  if ( !FileName ) return afParam; /* Bad parameters */
  if ( IsFileHere(FileName) ) return afDuplicate;

  newFile.fileName = malloc( strlen(FileName) + 1 );
  if ( newFile.fileName ) {
    strcpy(newFile.fileName, FileName);
    memset(newFile.digest, 0, sizeof(newFile.digest)); /* Zero message digest */
    newFile.matched = false;
    if ( FileList.AddToTail(&FileList, &newFile) )
      return afSuccess;
    else {
      free(newFile.fileName);
    }
  }
  return afMemory;
}
/*-----------------------------------------------------------*/
static bool IsFileHere(
  const char *FileName
)
{
  struct file_node node;
  unsigned int pos, count;

  count = FileList.Count(&FileList);
  for ( pos = 0U; pos < count; pos++ ) {
    FileList.Get(&FileList, pos, &node);
    assert(node.fileName);
    if ( node.fileName ) {
      if ( strcmp(node.fileName, FileName) == 0 )
        return true;
    }
  }
  return false;
}
/*-------------------------------------------------------------------------*/
static const char* GetErrorMessage(const unsigned int ErrNum)
{
  static const char defaultMessage[] = "(error out of range)";
  static const char* messages[] = {
    "Success",                                              /*ERROR_SUCCESS*/
    "Out of memory",                                         /*ERROR_MEMORY*/
    "Unrecognised parameter",                                /*ERROR_BADOPT*/
    "Duplicate filename",                                   /*ERROR_DUPFILE*/
    "Internal parameter fault",                      /*ERROR_INTERNAL_PARAM*/
    "ERROR_UNKNOWN",                                        /*ERROR_UNKNOWN*/
    "Cannot open file",                                    /*ERROR_CANTOPEN*/
  };
  const char* msg = defaultMessage;

  if ( ErrNum < sizeof(messages)/sizeof(messages[0]) )
    msg = messages[ErrNum];

  return msg;
}
/*-------------------------------------------------------------------------*/
static void PrintErrorMessage(const unsigned int ErrNum)
{
  const char* errStr = GetErrorMessage(ErrNum);
  fprintf(HERROR, "ERROR: %s\n", (errStr) ? (errStr) : ("???"));
  return;
}
/*-------------------------------------------------------------------------*/
static char* Chomp(char* Str)
{
  assert(Str);
  if ( Str ) {
    int len = strlen(Str);
    if ( len ) {
      if ( Str[len-1] == '\n' )
        Str[len-1] = '\0';
    }
  }
  return Str;
}
/*-------------------------------------------------------------------------*/
static bool HashFile(const char* FileName, unsigned char Hash[HASHLEN])
{
  FILE* handle;
  struct stat statInfo;

  memset(&statInfo, 0, sizeof(statInfo));
  stat(FileName, &statInfo);

  if ( S_ISDIR(statInfo.st_mode) )
    return false; /* Don't bother with directories */

  handle = fopen(FileName, "rb");
  if ( handle ) {
    HASHCTX ctx;
    unsigned long int bytesRead;
    unsigned char byte;

    daybocrypt_MD5Init(&ctx);

    do {
      bytesRead = fread(&byte, sizeof(byte), 1, handle);
      if ( bytesRead ) daybocrypt_MD5Update(&ctx, &byte, sizeof(byte));
    } while (bytesRead);

    daybocrypt_MD5Final(Hash, &ctx);
    fclose(handle);
  }
  else {
    fprintf(HERROR, "Error: %s \"%s\"\n", GetErrorMessage(ERROR_CANTOPEN), FileName);
    return false;
  }

  return true;
}
/*-------------------------------------------------------------------------*/
static void SearchDups()
{
  unsigned int i, j, c;

  c = FileList.Count(&FileList);
  for ( i = 0U; i < c; i++ ) { /* Main search loop (file A) */
    struct file_node nodeA;
    FileList.Get(&FileList, i, &nodeA);
    for ( j = 0U; j < c; j++ ) { /* Secondary search loop (file B) */
      struct file_node nodeB;
      FileList.Get(&FileList, j, &nodeB);

      if ( i != j && !(nodeA.matched || nodeB.matched) ) {
        /* OK we have both nodes, compare */
        if ( AndMD5(nodeA.digest, nodeB.digest) ) {
          if ( daybocrypt_MD5CompareDigests(nodeA.digest, nodeB.digest) ) {
            printf("%s == %s\n", nodeA.fileName, nodeB.fileName);
            nodeB.matched = true;
            FileList.Set(&FileList, j, &nodeB);
            if ( Options.Unlink ) {
              if ( remove(nodeB.fileName) == -1 ) {
                fprintf(stderr, "Error deleting \"%s\"\n", nodeB.fileName);
              }
            }
          }
          else {
            if ( Options.Mismatches )
              printf("%s != %s\n", nodeA.fileName, nodeB.fileName);
          }
        }
      }
    }
  }
  return;
}
/*-------------------------------------------------------------------------*/
#if 0
static void PrintHash(
  const char* FileName,
  const unsigned char Hash[HASHLEN]
)
{
  unsigned int i;

  if ( FileName ) printf("%s : ", FileName);

  for ( i = 0U; i < HASHLEN; i++ )
    printf("%02x", Hash[i]);

  putchar('\n');
}
#endif /*0*/
/*-------------------------------------------------------------------------*/
static bool AndMD5(
  const unsigned char DigestA[HASHLEN],
  const unsigned char DigestB[HASHLEN]
)
{
  if ( (!TestZeroMD5Sum(DigestA)) && (!TestZeroMD5Sum(DigestB)) )
    return true;

  return false;
}
/*-------------------------------------------------------------------------*/
static bool TestZeroMD5Sum(const unsigned char Digest[HASHLEN])
{
  unsigned int i;

  for ( i = 0U; i < HASHLEN; i++ ) {
    if ( Digest[i] != '\0' )
      return false;
  }
  return true;
}
/*-------------------------------------------------------------------------*/
#ifdef RCS_STAMPS
static void Unused(
  void *Arg,
  int FakeCall
)
{
  if ( !FakeCall ) {
    FakeCall = 1;
    Unused(Arg, FakeCall);
  }
}
#endif /*RCS_STAMPS*/
/*-------------------------------------------------------------------------*/