Vim can break file permissions?

Solution 1:

I can see that your current path is ~, your user's home directory. You should have write permissions to that directory.

Think of it another way - if you have read and write permissions to the directory, what's stopping you from copying the file, deleting the old one and renaming the new one with different permissions?

This is exactly what vim does!


If you run vim under strace, for example:

open("testfile", O_WRONLY|O_CREAT|O_TRUNC, 0644) = -1 EACCES (Permission denied)
lstat("testfile", {st_mode=S_IFREG|0644, st_size=10, ...}) = 0
getuid()                                = 1000
unlink("testfile")                      = 0
open("testfile", O_WRONLY|O_CREAT|O_TRUNC, 0644) = 3
write(3, "ffjidfjds\n", 10)             = 10
fsync(3)                                = 0
close(3)                                = 0
chmod("testfile", 0644)                 = 0

Based on this log, I can guess at the following process:

Some earlier permission checks (and chown attempts, etc.) are omitted for brevity.

  1. open Attempt to open the file for writing (fail: permission denied)
  2. lstat Check the owner of the file
  3. getuuid Check the current user ID, to see if they match the file owner
  4. unlink Delete the file (this is allowed because write permission on the directory)
  5. open Create a new file with the same name
  6. write The file contents (read earlier, I typed in some gibberish)
  7. fsync Flush the file to disk (not really important)
  8. close
  9. chmod Change the new file's permissions to look like the old one - it just happens to have a new owner now.