Presentation is loading. Please wait.

Presentation is loading. Please wait.

[Unix Programming] The File in Context Young-Ju, Han

Similar presentations


Presentation on theme: "[Unix Programming] The File in Context Young-Ju, Han"— Presentation transcript:

1 [Unix Programming] The File in Context Young-Ju, Han Email: yjhan@imtl.skku.ac.kr yjhan@imtl.skku.ac.kr

2 2007 UNIX Programming 2 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

3 2007 UNIX Programming 3 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

4 2007 UNIX Programming 4 Files in a multi-user environment  permissions and file modes $ ls –l /etc/passwd -rw-r----- types of user owner group other types of user types of access read writeexecute 11 0 0 0 0 0 1 0 Using pathname in open, must have X of all component of a pathname R for a fileDetermines if we can open an existing file for reading W for a fileDetermines if we can open an existing file for writing W for a fileTo specify the O_TRUNC flag in the open R in the dirObtaining a list of all filenames in the dir X in the dirSearch bit WX in the dirTo create a new file in a dir WX in the dirTo delete a existing file in a dir

5 2007 UNIX Programming 5 Files in a multi-user environment  permissions and file modes file mode : a bit pattern octal values for constructing file permissions: Octal valueSymbolic modeMeaning 0400S_IRUSRRead allowed by owner 0200S_IWUSRWrite allowed by owner 0100S_IXUSROwner can execute file 0700S_IRWXURead, write, execute by owner 0040S_IRGRPRead allowed by group 0020S_IWGRPWrite allowed by group 0010S_IXGRPGroup member can execute file 0070S_IRWXGRead, write, execute by group 0004S_IROTHOther types of user can read file 0002S_IWOTHOther types of user can write file 0001S_IXOTHOther types of user can execute file 0007S_IRWXORead, write, execute by other

6 2007 UNIX Programming 6 Files in a multi-user environment  extra permissions for executable files $ ls -l /usr/bin | grep ^-r-s s -r-sr-xr-x 1 root bin 29508 Feb 10 02:59 login ss -r-sr-sr-x 1 root sys 23500 Feb 10 02:59 passwd $ls –l / | grep tmp t drwxrwxrwt 1 root sys 23500 Feb 10 02:59 tmp/ 04000S_ISUIDset user-id 02000S_ISGIDset group-id 01000S_ISVTXsave-text-image(sticky bit) 0400 + 0040 + 0004 0444 S_IRUSR | S_IRGRP | S_IROTH

7 2007 UNIX Programming 7 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 ??

8 2007 UNIX Programming 8 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 ??

9 2007 UNIX Programming 9 Files 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); $ umask 022 mask = 0 2 2 filedes = open(“newfile”, O_WRONLY | O_CREAT, 0666); mask = 000 010 010 ~mask = 111 101 101 0666 = 110 110 110 = 110 100 100

10 2007 UNIX Programming 10 Files in a multi-user environment  file creation mask & umask system call #include mode_t umask(mode_t newmask); mode_t oldmask;. oldmask = umask(022); old umask new umask

11 2007 UNIX Programming 11 Files 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

12 2007 UNIX Programming 12 Files in a multi-user environment  file creation mask & umask system call  EACCES : Permission denied  EEXIST : pathname already exists #include 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

13 2007 UNIX Programming 13 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 int access(const char *pathname, int amode); 0 = ok -1 = error access method R_OK4Has calling process read access? W_OK2Has calling process write access? X_OK1Can calling process execute the file? F_OK0To check for the file’s existence only errno = EACCES ENOENT

14 2007 UNIX Programming 14 Files in a multi-user environment  access #include 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.out User cannot write file /usr/bin/passwd

15 2007 UNIX Programming 15 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 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

16 2007 UNIX Programming 16 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 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

17 2007 UNIX Programming 17 File System Layout partition disk drive i-listdirectory block and data blocks file system i-node … boot block super block

18 2007 UNIX Programming 18 i-node 가 가지고 있는 각 파일들의 정보 - 파일 유형 (type) - 파일의 접근 권한 (permission) - 파일의 크기 - 파일의 datablock 의 디스크 주소 ( 첫번째 디스크 주소 ) - 파일의 소유자와 소유 그룹 - 파일 접근 시간 ( 마지막 접근시간, 마지막 변경 시간 ) - 파일에 대한 링크 수 (link count : hard link 수 ) File System in more detail i-list file system i-node … directory block and data blocks data block ① data block ② data block ③ directory block i-node number filename2... i-node number filename

19 2007 UNIX Programming 19 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 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”);

20 2007 UNIX Programming 20 files with multiple names  unlink system call unlink(“/tmp/dir”); #include int unlink(const char *pathname); 0 = ok -1 = error remove(“/tmp/dir”); #include 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 를 하였다면 ??

21 2007 UNIX Programming 21 files with multiple names  rename system call file 의 name 이나 directory 간 file 이동을 제공 #include int rename(const char *original_path, const char *new_path); 0 = ok -1 = error if not exist, then error if already exist, then removed

22 2007 UNIX Programming 22 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 #include int symlink(const char *realname, const char *symname); 0 = ok -1 = error ok, although not exist, if already exist, then error $ 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 저장됨

23 2007 UNIX Programming 23 files with multiple names  readlink system call #include 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

24 2007 UNIX Programming 24 obtaining file information  stat, fstat, lstat discover the values of properties for an existing file 파일의 ownership 이나 permission 에 관계없이 누구나 사용할 수 있음 lstat() 은 symbolic link file 자체에 대한 정보를 얻고자 할 때 #include 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

25 2007 UNIX Programming 25 obtaining file information stat  member of stat structure st_devLogical device which the file resides st_inoi-node number of the file st_modefile type & file mode(12bit) st_nlink# of hard link st_uid, st_gidfile’s uid & gid st_rdevMeaningful only when the file entry is used to device st_sizelogical size(bytes) <= physical size st_atimeTime of last access ( ex. read() ) st_mtimeTime of last modification (ex. write() ) st_ctimeTime of last file(i-node) status change (ex. chmod, chown() ) st_blksizeBest I/O block size st_blocks# of 512-byte blocks allocated

26 2007 UNIX Programming 26 Files in a multi-user environment  File type Check file type : a bit pattern octal values for constructing file types: #define S_ISREG(mode) (((mode)&0xF000) == 0x8000) Octal valueSymbolic modeMeaning File Type Checking Macro 0xC000 ( 0140000 )S_IFSOCKSocket fileS_ISSOCK() 0xA000 ( 0120000 )S_IFLNKSymbolic link fileS_ISLINK() 0x8000 ( 0100000 )S_IFREGRegular fileS_ISREG() 0x6000 ( 0060000 )S_IFBLKBlock fileS_ISBLK() 0x4000 ( 0040000 )S_IFDIRDirectory fileS_ISDIR() 0x2000 ( 0020000 )S_IFCHRCharacter fileS_ISCHR() 0x1000 ( 0010000 )S_IFIFOFIFOS_ISFIFO()

27 2007 UNIX Programming 27 obtaining file information  Ex: filedata – 한 파일에 관한 정보를 출력 #include 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; }

28 2007 UNIX Programming 28 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; }


Download ppt "[Unix Programming] The File in Context Young-Ju, Han"

Similar presentations


Ads by Google