280 likes | 446 Views
[Unix Programming] The File in Context. Young-Ju, Han Email: yjhan@imtl.skku.ac.kr. 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
E N D
[Unix Programming]The File in Context Young-Ju, Han Email: yjhan@imtl.skku.ac.kr
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 • chmod / chown • Files with multiple names • link / unlink / rename / symlink • Obtaining file information • stat & fstat 2007 UNIX Programming
Files 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 2007 UNIX Programming
types of access read write execute types of user types of user 1 1 0 owner 0 1 0 group 0 0 0 other Files in a multi-user environment • permissions and file modes $ ls –l /etc/passwd -rw-r----- 2007 UNIX Programming
Files in a multi-user environment • permissions and file modes • file mode : a bit pattern • octal values for constructing file permissions:<sys/stat.h> 2007 UNIX Programming
Files in a multi-user environment • extra permissions for executable files 0400 + 0040 + 0004 0444 S_IRUSR | S_IRGRP | S_IROTH $ ls -l /usr/bin | grep ^-r-s -r-sr-xr-x 1 root bin 29508 Feb 10 02:59 login -r-sr-sr-x 1 root sys 23500 Feb 10 02:59 passwd $ls –l / | grep tmp drwxrwxrwt 1 root sys 23500 Feb 10 02:59 tmp/ 2007 UNIX Programming
Files 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 ?? 2007 UNIX Programming
Files 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 ?? 2007 UNIX Programming
Files in a multi-user environment • file creation mask & umask system call filedes = open(“newfile”, O_WRONLY | O_CREAT, 0666); $ ls –l newfile -rw-r--r-- newfile $ umask 022 filedes = open(“newfile”, O_WRONLY | O_CREAT, (~mask) & 0666); mask = 0 2 2 mask = 000 010 010 ~mask = 111 101 101 0666 = 110 110 110 = 110 100 100 2007 UNIX Programming
old umask new umask Files 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); 2007 UNIX Programming
결과 = 0666 $ ls –l newfile -rw-rw-rw- newfile Files in a multi-user environment • file creation mask & umask system call fd = open(“newfile”, O_WRONLY | O_CREAT, 0666); 결과 = 0644 $ ls –l newfile -rw-r----- newfile oldu = umask(0); fd = open(“newfile”, O_WRONLY | O_CREAT, 0666); umask(oldu); 2007 UNIX Programming
Files 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; } EACCES EEXIST 2007 UNIX Programming
access method <types.h> 0 = ok -1 = error Files 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); errno = EACCES ENOENT 2007 UNIX Programming
Files in a multi-user environment • access $ ls –l /usr/bin/passwd -r-sr-sr-x 3 root 89180 Oct 3 07:17 passwd $ gcc 13.c $ a.out User cannot write file /usr/bin/passwd #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; } 2007 UNIX Programming
Files 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); 0 = ok -1 = error if ( chmod(pathname, 0644) == -1 ) perror(“call to chmod failed”); 2007 UNIX Programming
Files 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); 0 = ok -1 = error new uid or -1 = not change new guid or -1=not change int retval; ... retval = chown(pathname, 56, 3); EPERM 2007 UNIX Programming
partition partition partition disk drive i-list directory block and data blocks file system i-node i-node … i-node File System Layout boot block super block 2007 UNIX Programming
data block data block data block ② ③ ① i-node number filename i-list file system i-node number filename2 ... i-node i-node … i-node File System in more detail directory block and data blocks directory block • i-node가 가지고 있는 각 파일들의 정보 • 파일 유형(type) • 파일의 접근 권한(permission) • 파일의 크기 • 파일의 datablock의 디스크 주소(첫번째 디스크 주소) • 파일의 소유자와 소유 그룹 • 파일 접근 시간 (마지막 접근시간, 마지막 변경 시간) • 파일에 대한 링크 수 (link count : hard link 수) 2007 UNIX Programming
0 = ok -1 = error if not exist, then error if already exist, then error files 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); link(“/usr/bin/ls”, “/tmp/dir”); 2007 UNIX Programming
#include <stdio.h> int remove(const char *pathname); #include <unistd.h> int unlink(const char *pathname); 0 = ok -1 = error 0 = ok -1 = error unlink(“/tmp/dir”); remove(“/tmp/dir”); files with multiple names • unlink system call • 파일이 속해 있는 디렉토리에 쓰기와 실행권한이 있어야 함 • Superuser나 파일의 소유주만이 unlink 실행 • unlink system call • 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를 하였다면?? 2007 UNIX Programming
0 = ok -1 = error if not exist, then error if already exist, then removed files with multiple names • rename system call • file의 name이나 directory간 file 이동을 제공 #include <stdio.h> int rename(const char *original_path, const char *new_path); 2007 UNIX Programming
ok, although not exist, 0 = ok -1 = error if already exist, then error files 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 $ ln /usr/bin ./dir ln: `/usr/bin': hard link not allowed for directory $ ln /usr/bin/ls ./dir ln: ./dir: Cross-device link • symlink system call • Symbolic link를 지원 • Link file permission은 설정되지 않음. (의미가 없음) • Symbolic link file에는 링크하는 파일의 realname 저장됨 #include <unistd.h> int symlink(const char *realname, const char *symname); 2007 UNIX Programming
# of char in the buffer -1 = error int ret; buffer[1024]; ret = readlink(“abc”, buffer, sizeof(buffer)); if( ret!= -1) buffer[ret] = “\0” files with multiple names • readlink system call #include <unistd.h> int readlink(const char *symname, char * buffer, size_t bufsize); • open sympath • read the contents of the file into buffer 즉, link되는 파일의 pathname(realname) • close sympath 2007 UNIX Programming
obtaining 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 2007 UNIX Programming
obtaining file information • member ofstatstructure <sys/stat.h> 2007 UNIX Programming
Files 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) 2007 UNIX Programming
obtaining 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; } 2007 UNIX Programming
obtaining 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; • } 2007 UNIX Programming