tech-userlevel archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Short circuit cp -l



Years ago I added the -l option to cp.  I was looking at it recently and
I saw that it was opening and closing the file even though it never did
anything except link it.

I want to make the following change.  Basically it moves the link code
to the start of the function bypassing all that extra work.  I think it
is safe but thought that I would pass it by others to make sure that I
am not missing a security hole somewhere.

By the way, a simple test indicates that this change makes an order of
magnitude speedup to the operation.


Index: utils.c
===================================================================
RCS file: /cvsroot/src/bin/cp/utils.c,v
retrieving revision 1.45
diff -u -u -r1.45 utils.c
--- utils.c     29 Feb 2016 04:22:21 -0000      1.45
+++ utils.c     16 Jul 2018 18:38:08 -0000
@@ -99,7 +99,17 @@
        int ch, checkch, from_fd, rcount, rval, to_fd, tolnk, wcount;
        char *p;
        off_t ptotal = 0;
-
+
+       /* if hard linking then simply close the open fds, link and
return */
+       if (lflag) {
+               (void)unlink(to.p_path);
+               if (link(entp->fts_path, to.p_path)) {
+                       warn("%s", to.p_path);
+                       return (1);
+               }
+               return (0);
+       }
+
        if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) == -1) {
                warn("%s", entp->fts_path);
                return (1);
@@ -164,18 +174,6 @@

        rval = 0;

-       /* if hard linking then simply close the open fds, link and
return */
-       if (lflag) {
-               (void)close(from_fd);
-               (void)close(to_fd);
-               (void)unlink(to.p_path);
-               if (link(entp->fts_path, to.p_path)) {
-                       warn("%s", to.p_path);
-                       return (1);
-               }
-               return (0);
-       }
-
        /*
         * There's no reason to do anything other than close the file
         * now if it's empty, so let's not bother.

-- 
D'Arcy J.M. Cain <darcy%NetBSD.org@localhost>
http://www.NetBSD.org/ IM:darcy%Vex.Net@localhost



Home | Main Index | Thread Index | Old Index