views:

325

answers:

4

I am using something like this:

char *file;
file = (char *)malloc(BUFSIZE * sizeof(char));
printf("Enter the filename:");
scanf("%s", file);
if(remove(file)) {
   printf("Error while removing");
}

I created two files:

touch filetobedeleted1.txt
chmod 777 filetobedeleted1.txt

touch filetobedeleted2.txt
chmod 444 filetobedeleted2.txt

Now, my program removes both the files but that is not supposed to happen right? Anyone knows what is wrong with the code?

EDIT: Added the code for putting the name into file...

Ok... looks like it all depends on the permissions set on the directory but then is there a way to use file permissions as a check?

+3  A: 

Removing a file only needs write access on the directory.

Strictly speaking, what you're removing is a reference to the file, a hardlink. The file itself will not be deleted until all links to the file are gone.

Try it with the rm command!

notacat
+3  A: 

Under POSIX filesystem semantics, the permission check used for deleting a file is whether you can write to the directory that the file is in; not whether you have write permission on the file itself.

(If the directory has the sticky bit set, then you must also be the owner of the file - /tmp uses this).

caf
So does it mean that on a web server, if the admin is careless in removing the write permissions on the directory, then a simple "DELETE" command can mess things up?
Legend
No, because the userspace tools like `rm` usually ask you to confirm if you want to remove a file without write permissions (cf. `rm: remove write-protected regular empty file `x'?`). The presumption is if you are writing a C program, then you know what you're doing.
caf
Oh I see... Thanks for that...
Legend
+1  A: 

remove() calls unlink(), and according to man 2 unlink, that only needs write permissions to the parent directory.

tsg
+1  A: 

You can use the getumask() function and give it a check before calling remove().

tur1ng