open() function parameters - c

If you look at this code block below by taking into consideration the last parameter "0", Does write line work properly ?
filename = argv[1];
string = "Example string";
if (stat(argv[1], &buf) != 0)
{
fd = open(filename, O_WRONLY | O_CREAT, 0);
if (fd < 0)
{
perror(filename);
exit(1);
}
write(fd, string, strlen(string));
close(fd);
}
else
{
print("%s file exists\n", filename);
}

From the manpage:
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 applies only 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.
The following symbolic constants are provided for mode:
S_IRWXU 00700 user (file owner) has read, write and execute permission
S_IRUSR 00400 user has read permission
S_IWUSR 00200 user has write permission
S_IXUSR 00100 user has execute permission
S_IRWXG 00070 group has read, write and execute permission
S_IRGRP 00040 group has read permission
S_IWGRP 00020 group has write permission
S_IXGRP 00010 group has execute permission
S_IRWXO 00007 others have read, write and execute permission
S_IROTH 00004 others have read permission
S_IWOTH 00002 others have write permission
S_IXOTH 00001 others have execute permission
So, specifying a mode of zero, you will create a file with the permissions of 0 & ~umask, i.e. a file without any permissions.
What exactly the filesystem makes of this is not in the domain of the open() or write() functions.

It is valid,
This is from open(2) Linux manual pages
The mode argument specifies the file mode bits be applied when a new file is created. This argument must be supplied when O_CREAT or O_TMPFILE is specified in flags; if neither O_CREAT nor O_TMPFILE is specified, then mode is ignored. The effective mode is modified by the process's umask in the usual way: in the absence of a default ACL, the mode of the created file is (mode & ~umask). Note that this mode applies only 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.
In theory then, your access to the file will be valid until you call close() as I understand the part I highlighted in the above excerpt.

Interesting question. POSIX says:
The argument following the oflag argument does not affect whether the file is open for reading, writing, or for both.
Which means that since you're handling the error return from open, if you reach the write line the behavior is well defined.
To expand a bit why this works. On most filesystems on unix-like systems, the meta-data related to a file should not affect already open file descriptors. You can for example remove a file that you have opened. This is in fact done quite commonly with temporary files, so that you don't need to remember to delete them on exit. The same applies to permissions or even ownership of the file. In fact, you can chroot while holding a file open and you can still write to it without actually being able to see it. You can even use file descriptor passing to give an open file descriptor to another process that wouldn't be allowed to open that file. This is quite commonly used for privilege separation. The permissions you had when creating a file descriptor are valid regardless of the changes to permissions later. So your question is a very interesting edge case because it asks if the filesystem permissions of the file are set before or after we create a file descriptor for it and POSIX seems to be clear on that.
I can only think of two exceptions to that right now. First is when someone forcibly remounts a filesystem to read-only in that case the kernel will go through horrifying gymnastics to invalidate your file descriptor which will make all its operations fail. Second one is AFS where your permissions are actually checked when you close the file (or, when the last user of the file on your local system closes it which sends it to the server), which leads to hilarious problems where your time-limited access tokens were valid when you opened a file but aren't valid any longer when you close it. This is also why close returns errors (but that's another rant).
This is why I mentioned error handling above. Even though POSIX says that it should not have an effect, I could see AFS or certain other file systems refusing to open such a file.

Related

How to implement append method in our own shell using open system call in c?

I am trying to implement my own shell in which i have to make a shell feature by which i will able to append text to file by using >>.here is my code....
int filedesc = open(inputargs[limit-1],O_WRONLY | O_APPEND);
//printf("%s\n",inputargs[limit-1]);
if(filedesc < 0) {
printf("Error opening file\n");
}
else{
dup2(filedesc,1);
}
filedesc always returning -1.
Transferring an edited form of my relevant comments into an answer.
Using O_APPEND is correct — and you do need O_WRONLY too — and maybe you should add O_CREAT in case it doesn't exist yet (but you definitely don't want O_TRUNC). I suppose O_RDWR would also work (in place of O_WRONLY), but it is not a good idea.
Does the file exist to be appended to? If not, add O_CREAT and a file mode argument. Tradition says "use 0666" (aka S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH — there's a reason people prefer typing the octal number!). I'd be sorely tempted to not grant write to group or others (using 0644), even though you can (and I do) use umask 022 to suppress those permissions.
What do you get from perror(inputargs[limit-1]); (instead of or as well as the printf() message? That will tell you why the system thinks it can't open the file. And don't forget that the system is right — it can't open the file. Your code has a problem — it is not yet clear what that is. It might be EPERM (no permission); it might be ENOENT (no such file or directory); it might be something else, but those two are the most likely.
Getting "permission denied" from perror(inputargs[limit-1]);
So, you don't have permission to write on the file — what are you going to do about that? Change the file name to one you have permission to write on, or set the permissions on the file you have so that you can write (append) to it? Or something else? If you, somewhere along the line, create the file using O_CREAT but don't specify the third (optional) argument to open(), you get quasi-random weird permissions on the file that you create. What does ls -l file-to-append-to tell you? (Note that the third argument is mandatory when O_CREAT is one of the options used in the call to open() — it is optional and ignored otherwise.)
Note that you should always write error messages in a shell to standard error and not to standard output. Even if there's I/O redirection on standard error, the shell still writes the error messages to standard error, and the redirection points it where the user wanted it to go.

Trying to implement append in my own shell Linux

I'm trying to implement append command in my own shell.
I succeeded to append to existing file but whenever I'm trying to append to file doesn't exist it makes a file without any permission (not read and not write)
if (append) {
fd = open(outfile,'a');
lseek(fd,0,SEEK_END);
close (STDOUT_FILENO) ;
dup(fd);
close(fd);
/* stdout is now appended */
}
What should I do to make a file with permissions
?
The open() system call doesn't use a character constant to indicate 'append'. Read the POSIX specification for open() — and look at O_APPEND etc. You need more flags than just O_APPEND, and you need three arguments to open() if you want to create the file if it doesn't exist (O_CREAT), etc.
if (append)
{
fd = open(outfile, O_CREAT|O_APPEND|O_WRONLY, 0644);
if (fd < 0)
…deal with error…
}
You can write 0644 as S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH but the octal is shorter and (after 30+ years practice) a lot easier to read. You can add write permissions for group (S_IWGRP) and others (S_IWOTH) if you like (0666 in octal), but unless you know you want group members and others to modify the files, it is safer to omit those — for all it goes against historical precedent. Users can and should set the shell umask value to 022 to prevent group and others from being able to write to files by default, but there's no harm (IMO) in being secure without that.

How does mode affect the permisson on newly created files in Linux?

I'm new to Linux, still struggling to understand how permisson control work in Linux. The open function prototype is sth like :
int open(char *filename, int flags, mode_t mode);
Let's I have the following code:
fd = open("foo.txt", O_CREAT|O_RDWR, S_IRUSR)
and let's say the file "foo.txt" didn't exist before, so the above statment will create a file called "foo.txt", and current process who executes this open statment can read and write this file. But after this process terminates, If another process starts and tries to open this file. Below is my question:
Q1-Since the file was created with S_IRUSR(owner can read this file) in the first open call, does it mean that even I as owner of the file, if I start a new process to open this file again, I can only read this file and I cannot write this file, is my understanding correct?
If my understanding is correct, is it sensible/practicable that owners create sth that they cannot have full access to it later?
Q2-If my above understanding is correct, then in the second call to open by a new process. I can only call like:
fd = open("foo.txt", O_RDONLY) // uses flags like O_WRONLY or O_RDWR will throw an error?
since the first open specified the mode as S_IRUSR, which maps to O_RDONLY in the subsequent calls, is my understanding correct?
Correct, if you create the file with permissions S_IRUSR (often written in octal as 0400), then you will not be able to open the file for writing. Attempting to do so will fail and set errno to EACCES.
This is quite practical as it gives you a way to protect files you do not want to accidentally overwrite, as long as the permissions stay as they are. However, as the owner, you have the power to change the permissions later, using the chmod() system call. So it's not as though you have permanently lost the ability to write that file; you can give yourself back that ability whenever you want.

c Open() function

I have some trouble understanding the arguments in the open function, specifically used in the context of creating an output file. I do not quite understand the roles of flags and file permissions (the 2nd and 3rd arguments in the function). For instance, if I have the file permission 00200 (user has write permission), and the flag O_RDONLY (Read only), then can I read the file or write the file?
The signature of open is as follows:
int open(const char *pathname, int flags, mode_t mode);
There are three sets of "permissions" at play: The permissions of the file itself, the flags, and the mode.
The permissions of the file itself (e.g. 00200 meaning only user can write) specify what the operating system allows a program to do.
When you specify the flags, you indicate what you want to do with the file. For example, if the file is readonly to you (e.g. rwxr-xr-x and you're not the owner), you will be allowed to open the file with O_RDONLY. If you attempt to open the file with O_RDWR or O_WRONLY, you will receive an EPERM (operation not permitted) error in errno.
The mode parameter is only relevant when you create a new file, such as when you open a file that doesn't exist1 and the flag O_CREAT is specified. The file is created on the filesystem and its permissions are given by mode & ~umask (see man 2 umask for more details).
1 Of course, the containing directory must exist and you must have write+exec permissions on that directory.

create and open file linux programming

consider this line of code:
file_desc = open(file, O_RDWR | O_CREAT | O_EXCL, 0444);
how can you open 'file' with read only permissions for owner/group/other (the 0444) while you say open it with O_RDWR access mode?
thanx
From the open man page:
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.
So the process that creates the file can write to it, but some other process can't (unless it changes the permissions first). This ensures that the creating process can fill in the fill without worrying about some other process inadvertently overwriting it. Without this feature, it would have to create the process with write permission, fill it in, then remove the write permission, which would allow a window during which some other process could overwrite it.

Resources