When is umask() useful? - c

umask(0);
fd = open("/dev/null", O_RDWR);
Here's man 2 umask:
umask() sets the calling process’s file mode creation mask (umask) to mask & 0777.
But it doesn't make sense for me,as when we call open ,we will also provide a mode parameter.
So what's the point of umask?

The umask is applied to all modes used in file system operations. From the manual open(2):
The permissions of the created file are (mode & ~umask)
So with a single call to umask, you can influence the mode of all create files.
This is usually used when a program wants the user to allow to overrule the default grants for files/directories it creates. A paranoid user (or root) can set the umask to 0077 which means that even if you specify 0777 in open(2), only the current user will have access.

I know this is and old question but here is my two cents:
Permissions of shared memory object
I was trying to make a shared memory object, with:
int shm_open(const char *name, int oflag, mode_t mode);
The resulting shared memory did not have the permission set in mode argument, so I read the shm_open man page which led me to the open function man page and there it says:
mode specifies the permissions to use in case a new file is created. This argument must be supplied when O_CREAT is specified in flags; if O_CREAT is not specified, then mode is ignored. The effective permissions are modified by the process's umask in the usual way: The permissions of the created file are (mode & ~umask). Note that this mode only applies to future accesses of the newly created file
So I tried to modify the umask with:
mode_t umask(mode_t mask);
but it did not work either, so after more google I found this Setting Permission document in gnu.org
Which recommends:
When your program needs to create a file and bypass the umask for its access permissions, the easiest way to do this is to use fchmod after opening the file, rather than changing the umask. In fact, changing the umask is usually done only by shells. They use the umask function.
and with fchmod my function worked as I wanted :) her it is:
int open_signals_shmem(struct signal_shmem **shmem, int size)
{
int fd, ret;
void *ptr;
*shmem = NULL;
ret = 1;
fd = shm_open(SIGNALS_SHMEM_NAME, O_RDWR | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO);
if (fd == -1)
{
printf("error: signals shmem could not be allocated (%s, errno=%d)\n", SIGNALS_SHMEM_NAME, errno);
}
else
{
// Change permissions of shared memory, so every body can access it
fchmod(fd, S_IRWXU | S_IRWXG | S_IRWXO);
if (ftruncate(fd, size) == -1)
{
printf("error: signals shmem could not be truncated (%s, errno=%d)\n", SIGNALS_SHMEM_NAME, errno);
}
else
{
ptr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (ptr == MAP_FAILED)
{
printf("error: signals shmem could not be mapped (%s, errno=%d)\n", SIGNALS_SHMEM_NAME, errno);
}
else
{
*shmem = ptr;
ret = 0;
}
}
}
return ret;
}

Citing this article:
The purpose of the umask is to allow
users to influence the permissions
given to newly created files and
directories. Daemons should not allow
themselves to be affected by this
setting, because what was appropriate
for the user will not necessarily be
suitable for the daemon.
In some cases it may be more
convenient for the umask to be set to
a non-zero value. This is equally
acceptable: the important point is
that the daemon has taken control of
the value, as opposed to merely
accepting what it was given.

Most Mac developers (and by extension most software testers), from the time they were babies, put this in their .cshrc
umask 002
However, most end users don't know about umask, so if they create a new user on the machine, and run your app, you are likely to create a bunch of log files and whatnot without group read/write permissions.
Then they switch users again and suddenly your app doesn't work.
For this reason, we're adding this to all our apps.
Our rule-of-thumb when it comes to security is that "we want users to be able to use our software".
#import <sys/types.h>
#import <sys/stat.h>
int main(int argc, char *argv[])
{
// set permissions for newly created files to ug+rwX,o+rX
umask(0002);

Related

set the execute bits in C

I am writing a program which requires me to create a file using standard fopen fprintf fclose calls.
I want to set the execute bits.
I can do this with chmod but this seems overkill. For the life of me (possibly due to advanced age) I can't seem to find (or remember) an API to do this.
fchmod(2) would be in keeping with your other calls... Given a file descriptor in fd:
struct stat buf;
fstat(fd, &buf);
fchmod(fd, buf.st_mode | S_IXUSR | S_IXGRP | S_IXOTH);
will add all three execute bits to the file's current mode (error handling left as an exercise for the reader).
You'd use fileno(3) to get the file descriptor from your FILE * structures. Alternatively you could use chmod(2) and pass it the file name.
chmod(2) is an API call,
and is the canonical way of changing the mode of a file (referenced by name)
from a program; it is not overkill.
You could use fchmod (see fchmod(3)), or umask if you want to apply the same for every file created (extracts below taken from http://www.gnu.org/software/libc/manual/html_node/Setting-Permissions.html and the umask(2) man page):
The functions in this section are declared in sys/stat.h.
Function: mode_t umask (mode_t mask)
The umask function sets the file creation mask of the current process to mask, and returns the previous value of the file creation mask.
Here is an example showing how to read the mask with umask without changing it permanently:
mode_t
read_umask (void)
{
mode_t mask = umask (0);
umask (mask);
return mask;
}
However, on GNU/Hurd systems it is better to use getumask if you just want to read the mask value, because it is reentrant.
Name
umask - set file mode creation mask
mode_t umask(mode_t mask);
Description
umask() sets the calling process's file mode creation mask (umask) to mask & 0777 (i.e., only the file permission bits of mask are used), and returns the previous value of the mask.
The umask is used by open(2), mkdir(2), and other system calls that create files to modify the permissions placed on newly created files or directories. Specifically, permissions in the umask are turned off from the mode argument to open(2) and mkdir(2).
The constants that should be used to specify mask are described under stat(2).
The typical default value for the process umask is S_IWGRP | S_IWOTH (octal 022). In the usual case where the mode argument to open(2) is specified as:
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH
(octal 0666) when creating a new file, the permissions on the resulting file will be:
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH
(because 0666 & ~022 = 0644; i.e., rw-r--r--).
Return Value
This system call always succeeds and the previous value of the mask is returned

Creating a file atomically

I came across this piece of code and it is not supposed to work according to the author, however, it runs successfully. The author recommends the use of O_CREAT which does the same thing but guarantees atomicity. In my opinion whether two processes are running concurrently or not, the code should still work?
if((fd=open("filename.dat", O_WRONLY) < 0)){
if(errno != ENOENT){
perror("open error");
exit(1);
}
else if((fd=open("filename.dat", O_WRONLY | O_CREAT)) < 0){
perror("creation error");
exit(1);
}
}
Atomicity is provided by the operating system: either the file exists, or it doesn't, however, between the calls to e.g. access() to check for existence and open() to create the file, another process may have created the file. So atomically creating a file must be done in one call:
if ((fd=open("filename.dat", O_WRONLY | O_CREAT | O_EXCL, mode))<0) {
// file exists or other error
O_EXCL results in the call failing when the file exists.
mode is a parameter required with O_CREAT to specify the file's access/sharing permission. The flags differ between Linux and Windows.

open with O_CREAT - was it opened or created?

I have 10 processes which try open the same file more or less at the same time using open(O_CREAT) call, then delete it. Is there any robust way to find out which process actually did create the file and which did open already create file, for instance, if I want to accurately count how many times that file was opened in such scenario.
I guess I could put a global mutex on file open operation, and do a sequence of open() calls using O_CREAT and O_EXCL flags, but that doesn't fit my definition of "robust".
Use O_EXCL flag with O_CREAT. This will fail if the file exists and errno will be set to EEXIST. If it does fail
then attempt open again without O_CREAT and without O_EXCL modes.
e.g.
int fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0644);
if ((fd == -1) && (EEXIST == errno))
{
/* open the existing file with write flag */
fd = open(path, O_WRONLY);
}
Based roughly on your comments, you want something along the lines of this function:
/* return the fd or negative on error (check errno);
how is 1 if created, or 0 if opened */
int create_or_open (const char *path, int create_flags, int open_flags,
int *how) {
int fd;
create_flags |= (O_CREAT|O_EXCL);
open_flags &= ~(O_CREAT|O_EXCL);
for (;;) {
*how = 1;
fd = open(path, create_flags);
if (fd >= 0) break;
if (errno != EEXIST) break;
*how = 0;
fd = open(path, open_flags);
if (fd >= 0) break;
if (errno != ENOENT) break;
}
return fd;
}
This solution is not bullet proof. There may be cases (symbolic links maybe?) that would cause it to loop forever. Also, it may live-lock in certain concurrency scenarios. I'll leave resolving such issues as an exercise. :-)
In your edited question, you pose:
I have 10 processes which try open the same file more or less at the same time using open(O_CREAT) call, then delete it.
A hack-ish, but more bullet proof, solution would be to give each process a different user ID. Then, just use the regular open(path, O_CREAT|...) call. You can then query the file with fstat() on the file descriptor, and check the st_uid field of the stat structure. If the field equals the processes' user ID, then it was the creator. Otherwise, it was an opener. This works since each process deletes the file after opening.

O_RDWR permission denied

I created this file
char *output = "big";
creat(output, O_RDWR);
When I'm trying to read the file
cat big
I'm getting permission denied. Whats wrong with my code? How to create a file with read and write permission mode?
with ls -l, the permission of big looked like this
----------
what does this mean?
You have misinterpeted the mode argument. From the man page:
mode specifies the permissions to use in case a new file is cre‐
ated. This argument must be supplied when O_CREAT is specified
in flags; if O_CREAT is not specified, then mode is ignored.
The effective permissions are modified by the process's umask in
the usual way: The permissions of the created file are
(mode & ~umask). Note that this mode only applies to future
accesses of the newly created file; the open() call that creates
a read-only file may well return a read/write file descriptor.
and also
creat() is equivalent to open() with flags equal to
O_CREAT|O_WRONLY|O_TRUNC.
So, a more appropriate call might look like:
int fd = creat(output, 0644); /*-rw-r--r-- */
If you want to open it O_RDWR though, then just use open():
int fd = open(output, O_CREAT|O_RDWR|O_TRUNC, 0644);
This is obviously a permission issue, start trying to see if creat doesn't returns -1, if so, print the errno value, with perror(""), so that you could resolve the problem.
Imho, i'd rather use open() to do this, because as mentionned in the creat man page,
"Note that open() can open device special files, but creat() cannot create them; ..", and
"creat() is equivalent to open() with flags equals to O_CREAT | O_WRONLY | O_TRUNC", and this doesn't talks about the permissions..
it would be the exact same result if you did this:
char* output = "big";
int fd;
fd = open(output, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
// do whaterver you want to do in your file
close(fd);
For more information, "man 2 open"

why permission of file created by open() is different with by touch?

#include<apue.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
int main(int argc , char *argv[])
{
int fd = open("test.txt",O_WRONLY | O_CREAT | O_TRUNC);
int pid,status;
const char *str_for_parent = "str_for_parent\n";
const char *str_for_child = "str_for_child\n";
if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid == 0)
{
write(fd,str_for_child,strlen(str_for_child)+1);
_exit(0);
}
wait(&status);
write(fd,str_for_parent,strlen(str_for_parent)+1);
return 0;
}
The test.txt is created by open().But it's permission(---------x) is different with those files(-rw-rw-r--) created by touch or any other softwares in my system.my umask is 0002
open actually takes an (optional) third parameter:
int open(const char *pathname, int flags, mode_t mode);
The mode of the new file is set to the AND of mode and the inverse of your umask (ie, mode & ~umask). Since you're not passing mode, it's getting initialized to some garbage, and you're getting the wrong mode as a result.
Generally if you're passing O_CREAT, you should pass a mode of 0666, unless you have some specific reason to use some other mode (eg, if you want to make sure the file is not readable by other users regardless of what the umask is set to).
If you supply the O_CREAT flag to open(), you must also supply a third mode parameter, which is combined with the current umask to set the created file's permission bits.
Unless you are specifically creating an executable file, you should almost always use 0666 as this parameter:
int fd = open("test.txt",O_WRONLY | O_CREAT | O_TRUNC, 0666);
This should give you the same result that you see from touch. Note that the leading zero in C indicates an octal constant.

Resources