Creating a file with open() or creat() has fewer permission bits set than I asked for

随声附和 提交于 2020-07-03 10:01:26

问题


I am writing a program to mimic the cp utility. However, I cannot get the file permissions to work correctly. I know that they are stored in the structure stat and stored in the st_mode field with stat.

My issue is that I do not get the write permission for the group or other categories, i.e. I get -rwxr-xr-x as the permissions for the file even though the source file is -rwxrwxrwx. The statement where I set the permissions is below.

if ( (dest_fd = open(dest_file, O_WRONLY|O_CREAT, (stats.st_mode & S_IRUSR)|(stats.st_mode & S_IWUSR)|(stats.st_mode & S_IXUSR)|(stats.st_mode & S_IRGRP)|(stats.st_mode & S_IWGRP)|(stats.st_mode & S_IXGRP)|(stats.st_mode & S_IROTH)|(stats.st_mode & S_IWOTH)| (stats.st_mode & S_IXOTH))) < 0)
    {
            printf("There was a problem opening the destination file.");
            exit(EXIT_FAILURE);
    }//ends the if statement opening the destination file.

回答1:


The answers so far are right that the problem is umask, but rather than clearing the umask (this is dangerous if your program is multi-threaded or if you might be calling any library functions that create files) I would treat the umask as a user configuration variable you are not allowed to modify, and instead call fchmod on the files after creating them to give them the final permissions you want. This may be necessary anyway to give certain permissions like suid/sgid, which some kernels remove whenever the file is modified. I would also initially create the file with mode 0600, so that there's no race condition between opening it and changing permissions during which another user could get an open handle on the file.




回答2:


The cause of the problem is

The permissions of the created file are (mode & ~umask)

Typically, umask is 022, so that prohibits creating world-writable files.




回答3:


*nix masks out mode bits in files you create, but you can change the mask using the umask() function. man umask (perhaps man 2 umask) for details.




回答4:


You can use the chmod(2) syscall to change the permissions of an existing file or directory or fchmod(2) to set the permissions given an open file descriptor.

To be more secure and to prevent exploitation of possible race conditions, you can use a very restrictive set of permissions while creating the file and then use chmod(2) to restore the original permissions. This is what cp -a does (except that it creates the file with the default permissions):

$ strace cp -a file file1
...
open("file1", O_WRONLY|O_TRUNC)       = 4
...
fchmod(4, 0100640)                    = 0
...

chmod(2) and fchmod(2) are not affected by the value of the umask.



来源:https://stackoverflow.com/questions/12391265/creating-a-file-with-open-or-creat-has-fewer-permission-bits-set-than-i-aske

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!