1 /* hardlink.c - Link multiple identical files together
3 * Copyright (C) 2008 - 2014 Julian Andres Klode <jak@jak-linux.org>
4 * Copyright (C) 2021 Karel Zak <kzak@redhat.com>
6 * SPDX-License-Identifier: MIT
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 #define _POSIX_C_SOURCE 200112L /* POSIX functions */
27 #define _XOPEN_SOURCE 600 /* nftw() */
29 #include <sys/types.h> /* stat */
30 #include <sys/stat.h> /* stat */
31 #include <sys/time.h> /* getrlimit, getrusage */
32 #include <sys/resource.h> /* getrlimit, getrusage */
33 #include <fcntl.h> /* posix_fadvise */
34 #include <ftw.h> /* ftw */
35 #include <search.h> /* tsearch() and friends */
36 #include <signal.h> /* SIG*, sigaction */
37 #include <getopt.h> /* getopt_long() */
38 #include <ctype.h> /* tolower() */
44 #include "monotonic.h"
47 /* Use libpcre2posix if it's available */
48 #ifdef HAVE_PCRE2_POSIX
49 # include <pcre2posix.h>
51 # define REG_NOSUB 0 /* we do want backreferences in PCRE mode */
53 # include <regex.h> /* regcomp(), regsearch() */
56 #ifdef HAVE_SYS_XATTR_H
57 # include <sys/xattr.h> /* listxattr, getxattr */
60 static int quiet
; /* don't print anything */
63 * struct file - Information about a file
64 * @st: The stat buffer associated with the file
65 * @next: Next file with the same size
66 * @basename: The offset off the basename in the filename
67 * @path: The path of the file
69 * This contains all information we need about a file.
77 #if __STDC_VERSION__ >= 199901L
88 * enum log_level - Logging levels
89 * @JLOG_SUMMARY: Default log level
90 * @JLOG_INFO: Verbose logging (verbose == 1)
91 * @JLOG_VERBOSE1: Verbosity 2
92 * @JLOG_VERBOSE2: Verbosity 3
102 * struct statistic - Statistics about the file
103 * @started: Whether we are post command-line processing
104 * @files: The number of files worked on
105 * @linked: The number of files replaced by a hardlink to a master
106 * @xattr_comparisons: The number of extended attribute comparisons
107 * @comparisons: The number of comparisons
108 * @saved: The (exaggerated) amount of space saved
109 * @start_time: The time we started at
111 static struct statistics
{
115 size_t xattr_comparisons
;
118 struct timeval start_time
;
122 * struct options - Processed command-line options
123 * @include: A linked list of regular expressions for the --include option
124 * @exclude: A linked list of regular expressions for the --exclude option
125 * @verbosity: The verbosity. Should be one of #enum log_level
126 * @respect_mode: Whether to respect file modes (default = TRUE)
127 * @respect_owner: Whether to respect file owners (uid, gid; default = TRUE)
128 * @respect_name: Whether to respect file names (default = FALSE)
129 * @respect_time: Whether to respect file modification times (default = TRUE)
130 * @respect_xattrs: Whether to respect extended attributes (default = FALSE)
131 * @maximise: Chose the file with the highest link count as master
132 * @minimise: Chose the file with the lowest link count as master
133 * @keep_oldest: Choose the file with oldest timestamp as master (default = FALSE)
134 * @dry_run: Specifies whether hardlink should not link files (default = FALSE)
135 * @min_size: Minimum size of files to consider. (default = 1 byte)
137 static struct options
{
140 struct regex_link
*next
;
141 } *include
, *exclude
;
143 signed int verbosity
;
144 unsigned int respect_mode
:1;
145 unsigned int respect_owner
:1;
146 unsigned int respect_name
:1;
147 unsigned int respect_time
:1;
148 unsigned int respect_xattrs
:1;
149 unsigned int maximise
:1;
150 unsigned int minimise
:1;
151 unsigned int keep_oldest
:1;
152 unsigned int dry_run
:1;
155 /* default setting */
156 .respect_mode
= TRUE
,
157 .respect_owner
= TRUE
,
158 .respect_time
= TRUE
,
159 .respect_xattrs
= FALSE
,
160 .keep_oldest
= FALSE
,
167 * A binary tree of files, managed using tsearch(). To see which nodes
168 * are considered equal, see compare_nodes()
171 static void *files_by_ino
;
176 * The last signal we received. We store the signal here in order to be able
177 * to break out of loops gracefully and to return from our nftw() handler.
179 static int last_signal
;
182 * jlog - Logging for hardlink
183 * @level: The log level
184 * @format: A format string for printf()
186 __attribute__((format(printf
, 2, 3)))
187 static void jlog(enum log_level level
, const char *format
, ...)
191 if (quiet
|| level
> (unsigned int)opts
.verbosity
)
194 va_start(args
, format
);
195 vfprintf(stdout
, format
, args
);
201 * CMP - Compare two numerical values, return 1, 0, or -1
205 * Used to compare two integers of any size while avoiding overflow.
207 #define CMP(a, b) ((a) > (b) ? 1 : ((a) < (b) ? -1 : 0))
210 * regexec_any - Match against multiple regular expressions
211 * @pregs: A linked list of regular expressions
212 * @what: The string to match against
214 * Checks whether any of the regular expressions in the list matches the
217 static int regexec_any(struct regex_link
*pregs
, const char *what
)
219 for (; pregs
!= NULL
; pregs
= pregs
->next
) {
220 if (regexec(&pregs
->preg
, what
, 0, NULL
, 0) == 0)
227 * compare_nodes - Node comparison function
228 * @_a: The first node (a #struct file)
229 * @_b: The second node (a #struct file)
231 * Compare the two nodes for the binary tree.
233 static int compare_nodes(const void *_a
, const void *_b
)
235 const struct file
*a
= _a
;
236 const struct file
*b
= _b
;
240 diff
= CMP(a
->st
.st_dev
, b
->st
.st_dev
);
242 diff
= CMP(a
->st
.st_size
, b
->st
.st_size
);
248 * compare_nodes_ino - Node comparison function
249 * @_a: The first node (a #struct file)
250 * @_b: The second node (a #struct file)
252 * Compare the two nodes for the binary tree.
254 static int compare_nodes_ino(const void *_a
, const void *_b
)
256 const struct file
*a
= _a
;
257 const struct file
*b
= _b
;
261 diff
= CMP(a
->st
.st_dev
, b
->st
.st_dev
);
263 diff
= CMP(a
->st
.st_ino
, b
->st
.st_ino
);
265 /* If opts.respect_name is used, we will restrict a struct file to
266 * contain only links with the same basename to keep the rest simple.
268 if (diff
== 0 && opts
.respect_name
)
269 diff
= strcmp(a
->links
->path
+ a
->links
->basename
,
270 b
->links
->path
+ b
->links
->basename
);
276 * print_stats - Print statistics to stdout
278 static void print_stats(void)
280 struct timeval end
= { 0, 0 }, delta
= { 0, 0 };
283 gettime_monotonic(&end
);
284 timersub(&end
, &stats
.start_time
, &delta
);
286 jlog(JLOG_SUMMARY
, "%-15s %s", _("Mode:"),
287 opts
.dry_run
? _("dry-run") : _("real"));
288 jlog(JLOG_SUMMARY
, "%-15s %zu", _("Files:"), stats
.files
);
289 jlog(JLOG_SUMMARY
, _("%-15s %zu files"), _("Linked:"), stats
.linked
);
291 #ifdef HAVE_SYS_XATTR_H
292 jlog(JLOG_SUMMARY
, _("%-15s %zu xattrs"), _("Compared:"),
293 stats
.xattr_comparisons
);
295 jlog(JLOG_SUMMARY
, _("%-15s %zu files"), _("Compared:"),
298 ssz
= size_to_human_string(SIZE_SUFFIX_3LETTER
|
300 SIZE_DECIMAL_2DIGITS
, stats
.saved
);
302 jlog(JLOG_SUMMARY
, "%-15s %s", _("Saved:"), ssz
);
305 jlog(JLOG_SUMMARY
, _("%-15s %ld.%06ld seconds"), _("Duration:"),
306 (long)delta
.tv_sec
, (long)delta
.tv_usec
);
310 * handle_interrupt - Handle a signal
312 * Returns: %TRUE on SIGINT, SIGTERM; %FALSE on all other signals.
314 static int handle_interrupt(void)
316 switch (last_signal
) {
330 #ifdef HAVE_SYS_XATTR_H
333 * llistxattr_or_die - Wrapper for llistxattr()
335 * This does the same thing as llistxattr() except that it aborts if any error
336 * other than "not supported" is detected.
338 static ssize_t
llistxattr_or_die(const char *path
, char *list
, size_t size
)
340 ssize_t len
= llistxattr(path
, list
, size
);
342 if (len
< 0 && errno
!= ENOTSUP
)
343 err(EXIT_FAILURE
, _("cannot get xattr names for %s"), path
);
349 * lgetxattr_or_die - Wrapper for lgetxattr()
351 * This does the same thing as lgetxattr() except that it aborts upon error.
353 static ssize_t
lgetxattr_or_die(const char *path
,
354 const char *name
, void *value
, size_t size
)
356 ssize_t len
= lgetxattr(path
, name
, value
, size
);
359 err(EXIT_FAILURE
, _("cannot get xattr value of %s for %s"),
366 * get_xattr_name_count - Count the number of xattr names
367 * @names: a non-empty table of concatenated, null-terminated xattr names
368 * @len: the total length of the table
370 * @Returns the number of xattr names
372 static int get_xattr_name_count(const char *const names
, ssize_t len
)
377 for (name
= names
; name
< (names
+ len
); name
+= strlen(name
) + 1)
384 * cmp_xattr_name_ptrs - Compare two pointers to xattr names by comparing
385 * the names they point to.
387 static int cmp_xattr_name_ptrs(const void *ptr1
, const void *ptr2
)
389 return strcmp(*(char *const *)ptr1
, *(char *const *)ptr2
);
393 * get_sorted_xattr_name_table - Create a sorted table of xattr names.
394 * @names - table of concatenated, null-terminated xattr names
395 * @n - the number of names
397 * @Returns allocated table of pointers to the names, sorted alphabetically
399 static const char **get_sorted_xattr_name_table(const char *names
, int n
)
401 const char **table
= xmalloc(n
* sizeof(char *));
404 for (i
= 0; i
< n
; i
++) {
406 names
+= strlen(names
) + 1;
409 qsort(table
, n
, sizeof(char *), cmp_xattr_name_ptrs
);
415 * file_xattrs_equal - Compare the extended attributes of two files
417 * @b: The second file
419 * @Returns: %TRUE if and only if extended attributes are equal
421 static int file_xattrs_equal(const struct file
*a
, const struct file
*b
)
425 char *names_a
= NULL
;
426 char *names_b
= NULL
;
429 const char **name_ptrs_a
= NULL
;
430 const char **name_ptrs_b
= NULL
;
431 void *value_a
= NULL
;
432 void *value_b
= NULL
;
436 assert(a
->links
!= NULL
);
437 assert(b
->links
!= NULL
);
439 jlog(JLOG_VERBOSE1
, _("Comparing xattrs of %s to %s"), a
->links
->path
,
442 stats
.xattr_comparisons
++;
444 len_a
= llistxattr_or_die(a
->links
->path
, NULL
, 0);
445 len_b
= llistxattr_or_die(b
->links
->path
, NULL
, 0);
447 if (len_a
<= 0 && len_b
<= 0)
448 return TRUE
; // xattrs not supported or neither file has any
451 return FALSE
; // total lengths of xattr names differ
453 names_a
= xmalloc(len_a
);
454 names_b
= xmalloc(len_b
);
456 len_a
= llistxattr_or_die(a
->links
->path
, names_a
, len_a
);
457 len_b
= llistxattr_or_die(b
->links
->path
, names_b
, len_b
);
458 assert((len_a
> 0) && (len_a
== len_b
));
460 n_a
= get_xattr_name_count(names_a
, len_a
);
461 n_b
= get_xattr_name_count(names_b
, len_b
);
464 goto exit
; // numbers of xattrs differ
466 name_ptrs_a
= get_sorted_xattr_name_table(names_a
, n_a
);
467 name_ptrs_b
= get_sorted_xattr_name_table(names_b
, n_b
);
469 // We now have two sorted tables of xattr names.
471 for (i
= 0; i
< n_a
; i
++) {
472 if (handle_interrupt())
473 goto exit
; // user wants to quit
475 if (strcmp(name_ptrs_a
[i
], name_ptrs_b
[i
]) != 0)
476 goto exit
; // names at same slot differ
479 lgetxattr_or_die(a
->links
->path
, name_ptrs_a
[i
], NULL
, 0);
481 lgetxattr_or_die(b
->links
->path
, name_ptrs_b
[i
], NULL
, 0);
484 goto exit
; // xattrs with same name, different value lengths
486 value_a
= xmalloc(len_a
);
487 value_b
= xmalloc(len_b
);
489 len_a
= lgetxattr_or_die(a
->links
->path
, name_ptrs_a
[i
],
491 len_b
= lgetxattr_or_die(b
->links
->path
, name_ptrs_b
[i
],
493 assert((len_a
>= 0) && (len_a
== len_b
));
495 if (memcmp(value_a
, value_b
, len_a
) != 0)
496 goto exit
; // xattrs with same name, different values
515 #else /* !HAVE_SYS_XATTR_H */
516 static int file_xattrs_equal(const struct file
*a
, const struct file
*b
)
520 #endif /* HAVE_SYS_XATTR_H */
523 * file_contents_equal - Compare contents of two files for equality
525 * @b: The second file
527 * Compare the contents of the files for equality
529 static int file_contents_equal(const struct file
*a
, const struct file
*b
)
535 int cmp
= 0; /* zero => equal */
536 off_t off
= 0; /* current offset */
538 assert(a
->links
!= NULL
);
539 assert(b
->links
!= NULL
);
541 jlog(JLOG_VERBOSE1
, _("Comparing %s to %s"), a
->links
->path
,
546 if ((fa
= fopen(a
->links
->path
, "rb")) == NULL
)
548 if ((fb
= fopen(b
->links
->path
, "rb")) == NULL
)
551 #if defined(POSIX_FADV_SEQUENTIAL) && defined(HAVE_POSIX_FADVISE)
552 posix_fadvise(fileno(fa
), 0, 0, POSIX_FADV_SEQUENTIAL
);
553 posix_fadvise(fileno(fb
), 0, 0, POSIX_FADV_SEQUENTIAL
);
556 while (!handle_interrupt() && cmp
== 0) {
560 ca
= fread(buf_a
, 1, sizeof(buf_a
), fa
);
561 if (ca
< sizeof(buf_a
) && ferror(fa
))
564 cb
= fread(buf_b
, 1, sizeof(buf_b
), fb
);
565 if (cb
< sizeof(buf_b
) && ferror(fb
))
570 if ((ca
!= cb
|| ca
== 0)) {
574 cmp
= memcmp(buf_a
, buf_b
, ca
);
581 return !handle_interrupt() && cmp
== 0;
583 if (fa
== NULL
|| fb
== NULL
)
584 warn(_("cannot open %s"), fa
? b
->links
->path
: a
->links
->path
);
586 warn(_("cannot read %s"),
587 ferror(fa
) ? a
->links
->path
: b
->links
->path
);
593 * file_may_link_to - Check whether a file may replace another one
595 * @b: The second file
597 * Check whether the two fies are considered equal and can be linked
598 * together. If the two files are identical, the result will be FALSE,
599 * as replacing a link with an identical one is stupid.
601 static int file_may_link_to(const struct file
*a
, const struct file
*b
)
603 return (a
->st
.st_size
!= 0 &&
604 a
->st
.st_size
== b
->st
.st_size
&&
605 a
->links
!= NULL
&& b
->links
!= NULL
&&
606 a
->st
.st_dev
== b
->st
.st_dev
&&
607 a
->st
.st_ino
!= b
->st
.st_ino
&&
608 (!opts
.respect_mode
|| a
->st
.st_mode
== b
->st
.st_mode
) &&
609 (!opts
.respect_owner
|| a
->st
.st_uid
== b
->st
.st_uid
) &&
610 (!opts
.respect_owner
|| a
->st
.st_gid
== b
->st
.st_gid
) &&
611 (!opts
.respect_time
|| a
->st
.st_mtime
== b
->st
.st_mtime
) &&
613 || strcmp(a
->links
->path
+ a
->links
->basename
,
614 b
->links
->path
+ b
->links
->basename
) == 0) &&
615 (!opts
.respect_xattrs
|| file_xattrs_equal(a
, b
)) &&
616 file_contents_equal(a
, b
));
620 * file_compare - Compare two files to decide which should be master
622 * @b: The second file
624 * Check which of the files should be considered greater and thus serve
625 * as the master when linking (the master is the file that all equal files
626 * will be replaced with).
628 static int file_compare(const struct file
*a
, const struct file
*b
)
631 if (a
->st
.st_dev
== b
->st
.st_dev
&& a
->st
.st_ino
== b
->st
.st_ino
)
634 if (res
== 0 && opts
.maximise
)
635 res
= CMP(a
->st
.st_nlink
, b
->st
.st_nlink
);
636 if (res
== 0 && opts
.minimise
)
637 res
= CMP(b
->st
.st_nlink
, a
->st
.st_nlink
);
639 res
= opts
.keep_oldest
? CMP(b
->st
.st_mtime
, a
->st
.st_mtime
)
640 : CMP(a
->st
.st_mtime
, b
->st
.st_mtime
);
642 res
= CMP(b
->st
.st_ino
, a
->st
.st_ino
);
648 * file_link - Replace b with a link to a
650 * @b: The second file
652 * Link the file, replacing @b with the current one. The file is first
653 * linked to a temporary name, and then renamed to the name of @b, making
654 * the replace atomic (@b will always exist).
656 static int file_link(struct file
*a
, struct file
*b
)
661 assert(a
->links
!= NULL
);
662 assert(b
->links
!= NULL
);
664 ssz
= size_to_human_string(SIZE_SUFFIX_3LETTER
|
666 SIZE_DECIMAL_2DIGITS
, a
->st
.st_size
);
667 jlog(JLOG_INFO
, _("%sLinking %s to %s (-%s)"),
668 opts
.dry_run
? _("[DryRun] ") : "", a
->links
->path
, b
->links
->path
,
674 strlen(b
->links
->path
) + strlen(".hardlink-temporary") + 1;
675 char *new_path
= xmalloc(len
);
677 snprintf(new_path
, len
, "%s.hardlink-temporary",
680 if (link(a
->links
->path
, new_path
) != 0) {
681 warn(_("cannot link %s to %s"), a
->links
->path
,
685 } else if (rename(new_path
, b
->links
->path
) != 0) {
686 warn(_("cannot rename %s to %s"), a
->links
->path
,
688 unlink(new_path
); /* cleanup failed rename */
695 /* Update statistics */
698 /* Increase the link count of this file, and set stat() of other file */
702 if (b
->st
.st_nlink
== 0)
703 stats
.saved
+= a
->st
.st_size
;
705 /* Move the link from file b to a */
707 struct link
*new_link
= b
->links
;
709 b
->links
= b
->links
->next
;
710 new_link
->next
= a
->links
->next
;
711 a
->links
->next
= new_link
;
722 * inserter - Callback function for nftw()
723 * @fpath: The path of the file being visited
724 * @sb: The stat information of the file
725 * @typeflag: The type flag
726 * @ftwbuf: Contains current level of nesting and offset of basename
728 * Called by nftw() for the files. See the manual page for nftw() for
729 * further information.
731 static int inserter(const char *fpath
, const struct stat
*sb
,
732 int typeflag
, struct FTW
*ftwbuf
)
740 if (handle_interrupt())
742 if (typeflag
== FTW_DNR
|| typeflag
== FTW_NS
)
743 warn(_("cannot read %s"), fpath
);
744 if (typeflag
!= FTW_F
|| !S_ISREG(sb
->st_mode
))
747 included
= regexec_any(opts
.include
, fpath
);
748 excluded
= regexec_any(opts
.exclude
, fpath
);
750 if ((opts
.exclude
&& excluded
&& !included
) ||
751 (!opts
.exclude
&& opts
.include
&& !included
))
756 if ((uintmax_t) sb
->st_size
< opts
.min_size
) {
758 _("Skipped %s (smaller than configured size)"), fpath
);
762 jlog(JLOG_VERBOSE2
, _("Visiting %s (file %zu)"), fpath
, stats
.files
);
764 pathlen
= strlen(fpath
) + 1;
766 fil
= xcalloc(1, sizeof(*fil
));
767 fil
->links
= xcalloc(1, sizeof(struct link
) + pathlen
);
770 fil
->links
->basename
= ftwbuf
->base
;
771 fil
->links
->next
= NULL
;
773 memcpy(fil
->links
->path
, fpath
, pathlen
);
775 node
= tsearch(fil
, &files_by_ino
, compare_nodes_ino
);
781 /* Already known inode, add link to inode information */
782 assert((*node
)->st
.st_dev
== sb
->st_dev
);
783 assert((*node
)->st
.st_ino
== sb
->st_ino
);
785 fil
->links
->next
= (*node
)->links
;
786 (*node
)->links
= fil
->links
;
790 /* New inode, insert into by-size table */
791 node
= tsearch(fil
, &files
, compare_nodes
);
799 if (file_compare(fil
, *node
) >= 0) {
803 for (l
= *node
; l
!= NULL
; l
= l
->next
) {
805 && file_compare(fil
, l
->next
) < 0)
820 warn(_("cannot continue")); /* probably ENOMEM */
825 * visitor - Callback for twalk()
826 * @nodep: Pointer to a pointer to a #struct file
827 * @which: At which point this visit is (preorder, postorder, endorder)
828 * @depth: The depth of the node in the tree
830 * Visit the nodes in the binary tree. For each node, call hardlinker()
831 * on each #struct file in the linked list of #struct file instances located
834 static void visitor(const void *nodep
, const VISIT which
, const int depth
)
836 struct file
*master
= *(struct file
**)nodep
;
841 if (which
!= leaf
&& which
!= endorder
)
844 for (; master
!= NULL
; master
= master
->next
) {
845 if (handle_interrupt())
847 if (master
->links
== NULL
)
850 for (other
= master
->next
; other
!= NULL
; other
= other
->next
) {
851 if (handle_interrupt())
854 assert(other
!= other
->next
);
855 assert(other
->st
.st_size
== master
->st
.st_size
);
857 if (other
->links
== NULL
858 || !file_may_link_to(master
, other
))
861 if (!file_link(master
, other
) && errno
== EMLINK
)
868 * usage - Print the program help and exit
870 static void __attribute__((__noreturn__
)) usage(void)
874 fputs(USAGE_HEADER
, out
);
875 fprintf(out
, _(" %s [options] <directory>|<file> ...\n"),
876 program_invocation_short_name
);
878 fputs(USAGE_SEPARATOR
, out
);
879 fputs(_("Consolidate duplicate files using hardlinks.\n"), out
);
881 fputs(USAGE_OPTIONS
, out
);
882 fputs(_(" -v, --verbose verbose output (repeat for more verbosity)\n"), out
);
883 fputs(_(" -q, --quiet quiet mode - don't print anything\n"), out
);
884 fputs(_(" -n, --dry-run don't actually link anything\n"), out
);
885 fputs(_(" -f, --respect-name filenames have to be identical\n"), out
);
886 fputs(_(" -p, --ignore-mode ignore changes of file mode\n"), out
);
887 fputs(_(" -o, --ignore-owner ignore owner changes\n"), out
);
888 fputs(_(" -t, --ignore-time ignore timestamps (when testing for equality)\n"), out
);
889 #ifdef HAVE_SYS_XATTR_H
890 fputs(_(" -X, --respect-xattrs respect extended attributes\n"), out
);
892 fputs(_(" -m, --maximize maximize the hardlink count, remove the file with\n"
893 " lowest hardlink count\n"), out
);
894 fputs(_(" -M, --minimize reverse the meaning of -m\n"), out
);
895 fputs(_(" -O, --keep-oldest keep the oldest file of multiple equal files\n"
896 " (lower precedence than minimize/maximize)\n"), out
);
897 fputs(_(" -x, --exclude <regex> regular expression to exclude files\n"), out
);
898 fputs(_(" -i, --include <regex> regular expression to include files/dirs\n"), out
);
899 fputs(_(" -s, --minimum-size <size> minimum size for files.\n"), out
);
900 fputs(_(" -c, --content compare only file contents, same as -pot\n"), out
);
902 fputs(USAGE_SEPARATOR
, out
);
903 printf(USAGE_HELP_OPTIONS(28));
904 printf(USAGE_MAN_TAIL("hardlink(1)"));
910 * register_regex - Compile and insert a regular expression into list
911 * @pregs: Pointer to a linked list of regular expressions
912 * @regex: String containing the regular expression to be compiled
914 static void register_regex(struct regex_link
**pregs
, const char *regex
)
916 struct regex_link
*link
;
919 link
= xmalloc(sizeof(*link
));
921 if ((err
= regcomp(&link
->preg
, regex
, REG_NOSUB
| REG_EXTENDED
)) != 0) {
922 size_t size
= regerror(err
, &link
->preg
, NULL
, 0);
923 char *buf
= xmalloc(size
+ 1);
925 regerror(err
, &link
->preg
, buf
, size
);
927 errx(EXIT_FAILURE
, _("could not compile regular expression %s: %s"),
930 link
->next
= *pregs
; *pregs
= link
;
934 * parse_options - Parse the command line options
935 * @argc: Number of options
936 * @argv: Array of options
938 static int parse_options(int argc
, char *argv
[])
940 static const char optstr
[] = "VhvnfpotXcmMOx:i:s:q";
941 static const struct option long_options
[] = {
942 {"version", no_argument
, NULL
, 'V'},
943 {"help", no_argument
, NULL
, 'h'},
944 {"verbose", no_argument
, NULL
, 'v'},
945 {"dry-run", no_argument
, NULL
, 'n'},
946 {"respect-name", no_argument
, NULL
, 'f'},
947 {"ignore-mode", no_argument
, NULL
, 'p'},
948 {"ignore-owner", no_argument
, NULL
, 'o'},
949 {"ignore-time", no_argument
, NULL
, 't'},
950 {"respect-xattrs", no_argument
, NULL
, 'X'},
951 {"maximize", no_argument
, NULL
, 'm'},
952 {"minimize", no_argument
, NULL
, 'M'},
953 {"keep-oldest", no_argument
, NULL
, 'O'},
954 {"exclude", required_argument
, NULL
, 'x'},
955 {"include", required_argument
, NULL
, 'i'},
956 {"minimum-size", required_argument
, NULL
, 's'},
957 {"content", no_argument
, NULL
, 'c'},
958 {"quiet", no_argument
, NULL
, 'q'},
961 static const ul_excl_t excl
[] = {
965 int excl_st
[ARRAY_SIZE(excl
)] = UL_EXCL_STATUS_INIT
;
968 while ((c
= getopt_long(argc
, argv
, optstr
, long_options
, NULL
)) != -1) {
970 err_exclusive_options(c
, long_options
, excl
, excl_st
);
974 opts
.respect_mode
= FALSE
;
977 opts
.respect_owner
= FALSE
;
980 opts
.respect_time
= FALSE
;
983 opts
.respect_xattrs
= TRUE
;
986 opts
.maximise
= TRUE
;
989 opts
.minimise
= TRUE
;
992 opts
.keep_oldest
= TRUE
;
995 opts
.respect_name
= TRUE
;
1004 opts
.respect_mode
= FALSE
;
1005 opts
.respect_name
= FALSE
;
1006 opts
.respect_owner
= FALSE
;
1007 opts
.respect_time
= FALSE
;
1008 opts
.respect_xattrs
= FALSE
;
1014 register_regex(&opts
.exclude
, optarg
);
1017 register_regex(&opts
.include
, optarg
);
1020 opts
.min_size
= strtosize_or_err(optarg
, _("failed to parse size"));
1025 print_version(EXIT_SUCCESS
);
1027 errtryhelp(EXIT_FAILURE
);}
1034 * to_be_called_atexit - Cleanup handler, also prints statistics.
1036 static void to_be_called_atexit(void)
1043 * sighandler - Signal handler, sets the global last_signal variable
1044 * @i: The signal number
1046 static void sighandler(int i
)
1048 if (last_signal
!= SIGINT
)
1054 int main(int argc
, char *argv
[])
1056 struct sigaction sa
;
1058 sa
.sa_handler
= sighandler
;
1059 sa
.sa_flags
= SA_RESTART
;
1060 sigfillset(&sa
.sa_mask
);
1062 /* If we receive a SIGINT, end the processing */
1063 sigaction(SIGINT
, &sa
, NULL
);
1064 sigaction(SIGUSR1
, &sa
, NULL
);
1066 /* Pretty print numeric output */
1067 setlocale(LC_NUMERIC
, "");
1069 if (atexit(to_be_called_atexit
) != 0)
1070 err(EXIT_FAILURE
, _("cannot register exit handler"));
1072 parse_options(argc
, argv
);
1075 errx(EXIT_FAILURE
, _("no directory or dile specified"));
1077 gettime_monotonic(&stats
.start_time
);
1078 stats
.started
= TRUE
;
1080 for (; optind
< argc
; optind
++) {
1081 if (nftw(argv
[optind
], inserter
, 20, FTW_PHYS
) == -1)
1082 warn(_("cannot process %s"), argv
[optind
]);
1085 twalk(files
, visitor
);