Top Banner
[Unix Programming] [Unix Programming] The File in Context The File in Context Young-Ju, Han Young-Ju, Han Email: Email: [email protected]
28

[Unix Programming] The File in Context

Jan 01, 2016

Download

Documents

abra-porter

[Unix Programming] The File in Context. Young-Ju, Han Email: [email protected]. Contents. Files in a multi-user environment users & ownerships permissions and file modes file creation mask & umask system call open & file permissions determining file accessibility with access - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: [Unix Programming] The File in Context

[Unix Programming][Unix Programming]The File in ContextThe File in Context

Young-Ju, HanYoung-Ju, Han

Email: Email: [email protected]

Page 2: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 22

ContentsContents

Files in a multi-user environment users & ownerships permissions and file modes file creation mask & umask system call open & file permissions determining file accessibility with access chmod / chown

Files with multiple names link / unlink / rename / symlink

Obtaining file information stat & fstat

Page 3: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 33

Files in a multi-user environmentFiles in a multi-user environment

users and ownerships uid(user-id) : user who created the file

ruid(real user-id) : uid in password file when log in euid(effective user-id) : determine file access

permission

gid(group-id) : /etc/group egid(effective group-id)

username: password: user-id: group-id(gid) : comment : home directory 의 절대 위치 : login 직후 수행되는 program

(shell program)

kmjsh:x:1337:310:Kim Moon Jeong:/user4/2000PDMS/kmjsh:/bin/csh

Page 4: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 44

Files in a multi-user environmentFiles in a multi-user environment

permissions and file modes

$ ls –l /etc/passwd-rw-r-----

types of user

owner

group

other

types of usertypes of access

read write execute

1 1 0

0

00

01

0

Using pathname in open, must have X of all component of a pathname

R for a file Determines if we can open an existing file for reading

W for a file Determines if we can open an existing file for writing

W for a file To specify the O_TRUNC flag in the open

R in the dir Obtaining a list of all filenames in the dir

X in the dir Search bit

WX in the dir To create a new file in a dir

WX in the dir To delete a existing file in a dir

Page 5: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 55

Files in a multi-user environmentFiles in a multi-user environment

permissions and file modes file mode : a bit pattern octal values for constructing file permissions:<sys/stat.h>

Octal value Symbolic mode Meaning

0400 S_IRUSR Read allowed by owner

0200 S_IWUSR Write allowed by owner

0100 S_IXUSR Owner can execute file

0700 S_IRWXU Read, write, execute by owner

0040 S_IRGRP Read allowed by group

0020 S_IWGRP Write allowed by group

0010 S_IXGRP Group member can execute file

0070 S_IRWXG Read, write, execute by group

0004 S_IROTH Other types of user can read file

0002 S_IWOTH Other types of user can write file

0001 S_IXOTH Other types of user can execute file

0007 S_IRWXO Read, write, execute by other

Page 6: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 66

Files in a multi-user environmentFiles in a multi-user environment

extra permissions for executable files

$ ls -l /usr/bin | grep ^-r-s-r-ssr-xr-x 1 root bin 29508 Feb 10 02:59 login-r-ssr-ssr-x 1 root sys 23500 Feb 10 02:59 passwd$ls –l / | grep tmpdrwxrwxrwtt 1 root sys 23500 Feb 10 02:59 tmp/

04000 S_ISUID set user-id

02000 S_ISGID set group-id

01000 S_ISVTX save-text-image(sticky bit)

0400 + 0040 + 00040444

S_IRUSR | S_IRGRP | S_IROTH

Page 7: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 77

Files in a multi-user environmentFiles in a multi-user environment

Set-user-id Process( 실행된 /usr/bin/passwd) 의 effective uid 를 file(/usr/bin/passwd) 의 owner 로 설정

예 ) Login: namaste (real user id) $ ls –al | more 가 실행 중 일때

( real user id = namaste, effective user id = namaste)

$ passwd 가 실행 중일 때 Real user id = namaste Effective user id = root 따라서 이상태에서는 root 가 접근할 수 있는 파일에 접근 가능하여 /etc/passwd, /etc/shadow 파일의 자신의 password 를 change 할 수 있게됨

Set-group-id

Sticky bit for file?? 실행파일이면 swap area 에 저장하여 향후 Sticky bit for Directory ??

Page 8: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 88

Files in a multi-user environmentFiles in a multi-user environment

Sticky bit For file

한번 실행된 파일은 실행이 종료되었더라도 메모리에서 삭제되지 않고 reboot 할 때까지 memory의 swap area에 저장됨

다음 실행 시 로딩 시간을 줄일 수 있음 Vi, gcc 등에 적용할 수 있음

For directory 해당 디렉토리에 있는 파일에 대하여 File owner, directory owner, superuser(root) 를 제외하고 파일을 삭제하거나 moving할 수 없음 /tmp와 같은 공유 디렉토리에 많이 설정

Sticky bit for file?? 실행파일이면 swap area 에 저장하여 향후 Sticky bit for Directory ??

Page 9: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 99

Files in a multi-user environmentFiles in a multi-user environment

file creation mask & umask system call

$ ls –l newfile-rw-r--r-- newfile

filedes = open(“newfile”, O_WRONLY | O_CREAT, (~mask) & 0666);

$ umask022

mask = 0 2 2

filedes = open(“newfile”, O_WRONLY | O_CREAT, 0666);

mask = 000 010 010

~mask = 111 101 1010666 = 110 110 110

= 110 100 100

Page 10: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 1010

Files in a multi-user environmentFiles in a multi-user environment

file creation mask & umask system call

#include <sys/types.h>#include <sys/stat.h>

mode_t umask(mode_t newmask);

mode_t oldmask;..oldmask = umask(022);

old umasknew umask

Page 11: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 1111

Files in a multi-user environmentFiles in a multi-user environment

file creation mask & umask system call

fd = open(“newfile”, O_WRONLY | O_CREAT, 0666);

$ ls –l newfile-rw-r----- newfile

결과 = 0644

oldu = umask(0);fd = open(“newfile”, O_WRONLY | O_CREAT, 0666);umask(oldu);

$ ls –l newfile-rw-rw-rw- newfile

결과 = 0666

Page 12: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 1212

Files in a multi-user environmentFiles in a multi-user environment

file creation mask & umask system call

EACCES : Permission denied EEXIST : pathname already exists

#include <fcntl.h>#include <sys/stat.h>

int specialcreat(const char *pathname, mode_t mode) { mode_t oldu; int fd;

oldu = umask(0);

fd = open(pathname, O_WRONLY | O_CREAT | O_EXCL, mode);

umask(oldu);

return fd;}

EEXISTEACCES

Page 13: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 1313

Files in a multi-user environmentFiles in a multi-user environment

access determines whether or not a process can access a file

according to the real user-id of the process

ENOENT : No such file or Directory EACCES : Permission denied

#include <unistd.h>

int access(const char *pathname, int amode);

0 = ok -1 = error

access method<types.h>

R_OK 4 Has calling process read access?

W_OK 2 Has calling process write access?

X_OK 1 Can calling process execute the file?

F_OK 0 To check for the file’s existence only

errno = EACCESENOENT

Page 14: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 1414

Files in a multi-user environmentFiles in a multi-user environment

access

#include <stdio.h>#include <stdlib.h>#include <unistd.h>

int main() { char *filename = “/usr/bin/passwd”;

if (access(filename, W_OK) == -1) { fprintf(stderr, “User cannot write file %s\n”, filename); exit(1); } printf(“%s writable, proceeding\n”, filename); return 0;}

$ ls –l /usr/bin/passwd-r-sr-sr-x 3 root 89180 Oct 3 07:17 passwd$ gcc 13.c$ a.outUser cannot write file /usr/bin/passwd

Page 15: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 1515

Files in a multi-user environmentFiles in a multi-user environment

chmod to change the permissions of an existing file

변경은 superuser 나 file 의 owner(=euid) 에 의해서만 가능

예외 ) 파일에 대하여 sticky bit(S_ISVTX) 가 설정되어 있을 경우 super user 에 의해서만 가능

#include <sys/types.h>#include <sys/stat.h>

int chmod(const char *pathname, mode_t newmode);int chmod(int fildes, mode_t newmode);

if ( chmod(pathname, 0644) == -1 ) perror(“call to chmod failed”);

0 = ok-1 = error

Page 16: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 1616

Files in a multi-user environmentFiles in a multi-user environment

chown (file 에 대한 ownership 변경을 위해 ) to change both the owner and group of a file 변경은 superuser 나 file owner( = euid) 에 의해 가능 소유그룹은 egid or 현재 프로세스의 euid 가 속해있는

그룹으로 변경가능#include <sys/types.h>#include <unistd.h>

int chown(const char *pathname, uid_t owner_id, gid_t group_id);int fchown(int fd, uid_t owner_id, gid_t group_id);int lchown(const char* pathname, uid_t owner_id, gid_t group_id);

int retval;...retval = chown(pathname, 56, 3);

EPERM

0 = ok-1 = error

new uid or-1 = not change

new guid or-1=not change

Page 17: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 1717

File System LayoutFile System Layout

partition partition partitiondisk drive

i-list directory block and data blocksfile system

i-node i-node … i-nodebootblock

super block

Page 18: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 1818

i-nodei-node 가 가지고 있는 각 파일들의 정보가 가지고 있는 각 파일들의 정보

-파일 유형 (type)-파일의 접근 권한 (permission)-파일의 크기-파일의 datablock 의 디스크 주소 ( 첫번째 디스크 주소 )-파일의 소유자와 소유 그룹-파일 접근 시간 ( 마지막 접근시간 , 마지막 변경 시간 )-파일에 대한 링크 수 (link count : hard link 수 )

File System in more detailFile System in more detail

i-listfile system

i-node i-node … i-node

directory block and data blocks

datablock

datablock

datablock

directoryblock

i-nodenumber

filename2

...

i-nodenumber

filename

Page 19: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 1919

files with multiple namesfiles with multiple names

hard link : names that same physical collection of data link count : number of links associated with a file New_path 는 original_path 와 같은 permission 과 같은

ownership 을 가짐

link system call

#include <unistd.h>

int link(const char *original_path, const char *new_path);

0 = ok-1 = error

if not exist,then error

if already exist,then error

link(“/usr/bin/ls”, “/tmp/dir”);

Page 20: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 2020

files with multiple namesfiles with multiple names

unlink system call

unlink(“/tmp/dir”);

#include <unistd.h>

int unlink(const char *pathname);

0 = ok-1 = error

remove(“/tmp/dir”);

#include <stdio.h>

int remove(const char *pathname);

0 = ok-1 = error

unlink system call 파일이 속해 있는 디렉토리에 쓰기와 실행권한이 있어야 함 Superuser 나 파일의 소유주만이 unlink 실행

removes just the link named reduces the file’s link count by one if the link count is reduced to zero

then lost from the system 만일 open 되어 있는 파일에 대하여 unlink 를 하였다

면 ??

Page 21: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 2121

files with multiple namesfiles with multiple names

rename system call file 의 name 이나 directory 간 file 이동을 제공

#include <stdio.h>

int rename(const char *original_path, const char *new_path);

0 = ok-1 = error

if not exist,then error

if already exist,then removed

Page 22: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 2222

files with multiple namesfiles with multiple names

limitations of link call not create a link to a directory not create a link to a file across different file

systems

#include <unistd.h>

int symlink(const char *realname, const char *symname);

0 = ok-1 = error

ok, althoughnot exist,

if already exist,then error

$ ln /usr/bin ./dirln: `/usr/bin': hard link not allowed for directory

$ ln /usr/bin/ls ./dirln: ./dir: Cross-device link symlink system call

Symbolic link 를 지원 Link file permission 은 설정되지 않음 . ( 의미가 없음 ) Symbolic link file 에는 링크하는 파일의 realname 저장됨

Page 23: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 2323

files with multiple namesfiles with multiple names

readlink system call

#include <unistd.h>

int readlink(const char *symname, char * buffer, size_t bufsize);

# of char in the buffer-1 = error

int ret; buffer[1024];ret = readlink(“abc”, buffer, sizeof(buffer));

if( ret!= -1) buffer[ret] = “\0”

open sympath read the contents of the file into buffer

즉 , link 되는 파일의 pathname(realname) close sympath

Page 24: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 2424

obtaining file informationobtaining file information

stat, fstat, lstat discover the values of properties for an existing file 파일의 ownership 이나 permission 에 관계없이 누구나

사용할 수 있음

lstat() 은 symbolic link file 자체에 대한 정보를 얻고자 할 때

#include <sys/types.h>#include <sys/stat.h>

int stat(const char *pathname, struct stat *buf);int fstat(int filedes, struct stat *buf);int lstat(const char* pathname, struct stat *buf);

0 = ok-1 = error

Page 25: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 2525

obtaining file informationobtaining file information

member of statstat structure <sys/stat.h>

st_dev Logical device which the file resides

st_ino i-node number of the file

st_mode file type & file mode(12bit)

st_nlink # of hard link

st_uid, st_gid file’s uid & gid

st_rdev Meaningful only when the file entry is used to device

st_size logical size(bytes) <= physical size

st_atime Time of last access ( ex. read() )

st_mtime Time of last modification (ex. write() )

st_ctime Time of last file(i-node) status change (ex. chmod, chown() )

st_blksize Best I/O block size

st_blocks # of 512-byte blocks allocated

Page 26: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 2626

Files in a multi-user environmentFiles in a multi-user environment

File type Check file type : a bit pattern octal values for constructing file types:<sys/stat.h>

#define S_ISREG(mode) (((mode)&0xF000) == 0x8000)

Octal value Symbolic mode MeaningFile Type

Checking Macro

0xC000 ( 0140000 ) S_IFSOCK Socket file S_ISSOCK()

0xA000 ( 0120000 ) S_IFLNK Symbolic link file S_ISLINK()

0x8000 ( 0100000 ) S_IFREG Regular file S_ISREG()

0x6000 ( 0060000 ) S_IFBLK Block file S_ISBLK()

0x4000 ( 0040000 ) S_IFDIR Directory file S_ISDIR()

0x2000 ( 0020000 ) S_IFCHR Character file S_ISCHR()

0x1000 ( 0010000 ) S_IFIFO FIFO S_ISFIFO()

Page 27: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 2727

obtaining file informationobtaining file information

Ex: filedata – 한 파일에 관한 정보를 출력

#include <stdio.h>#include <sys/stat.h>

static short octarray[9] = { 0400, 0200, 0100, 0040, 0020, 0010, 0004, 0002, 0001};

static char perms[10] = “rwxrwxrwx”;

int filedata (const char* pathname) {struct stat statbuf;char descrip[10];int j;if(stat(pathname,&statbuf) == -1) {

perror(“stat call error”);return -1;

}

Page 28: [Unix Programming] The File in Context

2007 UNIX Programming2007 UNIX Programming 2828

obtaining file informationobtaining file information

Ex: filedata – 한 파일에 관한 정보를 출력

if(S_ISREG(statbuf.st_mode))printf(“%s is regular files\n”, pathname);

for (j=0; j< 9; j++) {if(statbuf.st_mode & octarray[j])

descrip[j] = perms[j];else

descrip[j] = ‘-’;}

descrip[9] = ‘\0’;

printf(“\n File %s : \n”, pathname);printf(“Size %ld bytes\n”, statubf.st_size);printf(“User-id %d, group-id %d\n\n”, statbuf.st_uid, statbuf.st_gid);printf(“permissions : %s\n”, descrip);return 0;

}