Out of interest, why would file ownership get changed by simply copying a file over from one location to another?
Why would it get perserved is a more appropriate question ? You have to think of what exactly a copy operation is and how a programmer would implement it. At the very basic level, a copy operation is actually 2 operations, a file read and a file creation. Basically, we're going to open a file for reading, the source and a file for writing, the destination. Using the fread() and fwrite() ANSI C functions, you "transfer" the data from one to the other.
When you create a file on a Unix system, it gets stamped with a creation date, it gets its permissions set depending on your umask and the owner/group are that of the creating user. A copy thus "changes" file ownership :
Code:
$ ls -al /var/run/resolv.conf
-rw-r--r-- 1 root daemon 262 1 Mar 19:07 /var/run/resolv.conf
$ cp /var/run/resolv.conf .
$ ls -al ./resolv.conf
-rw-r--r-- 1 username staff 262 1 Mar 19:31 ./resolv.conf
In actuality, there is no "change" operation performed. The system just reacts that way normally to a new file being created.
Now, if you try to "preserve" the ownership on a copy, you need to first tell cp to do it. This is because we now have to do a few more operations on the file after creating it :
Code:
$ cp -p /var/run/resolv.conf .
$ ls -al ./resolv.conf
-rw-r--r-- 1 username staff 262 1 Mar 19:07 ./resolv.conf
Now wait a minute, it didn't work you'll say. And you're partly right. Look at the timestamp. It is now equivalent to the original file (19:07 vs 19:31). The ownership though still got "changed". Again, it's not that the ownership got changed, it's that the operation to preserve the original ownership got denied. If we try it manually, you'll see that a normal user has no right to set a file to be owned by root :
Code:
$ chown root ./resolv.conf
chown: ./resolv.conf: Operation not permitted
Hence, when the cp command tried to preserve the ownership as root:daemon, the fchown() call returned EACCES, which is a standard symbol defined in errno.h to mean an operation was not permitted by the system.
File ownership is complex when you dwelve into it. If your home is not owned by your user, stuff breaks. The best way to ensure your home directory is a clone copy is to use a method that actually makes a perfect copy (ownership, timestamps, attributes, acls, etc..) and to do so as an unrestricted user (root).