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

Slides:



Advertisements
Similar presentations
File Types in Unix regular file - can be text, binary, can be executable directory file - "folder type" file FIFO file - special pipe device file, allows.
Advertisements

MORE FILE ATTRIBUTES. ls –l to display file attributes (properties) Listing of a specific directory Ownership and group ownership Different file permissions.
1 Files and Directories Hua LiSystems ProgrammingCS2690Files and Directories.
CS 311 – Lecture 13 Outline File management system calls chown() chmod() dup() and dup2() link() Lecture 131CS Operating Systems 1.
Linux+ Guide to Linux Certification, Second Edition
CS 497C – Introduction to UNIX Lecture 15: - File Attributes Chin-Chih Chang
Files and Directories Hua LiSystems ProgrammingCS2690Files and Directories Spring 2003Page 1 of 60.
Linux Linux File System.
Operating Systems Recitation 11, June 9-10, 2002.
CS 311 – Lecture 12 Outline File management system calls Stat() Directory Information  Opendir()  Readdir()  Closedir() Truncate() and remove() Lecture.
1 Unix File System API Operating System Hebrew University Spring 2007.
LERSAIS.  Access Control in Unix  Access Control in Windows  Port Redirection 2.
Getting Started with Linux Linux System Administration Permissions.
O.S security Ge Zhang Karlstad University. Outline Why O.S. security is important? Security schemes in Unix/Linux system Security schemes in windows system.
Filesystem Hierarchy Standard (FHS) –Standard of outlining the location of set files and directories on a Linux system –Gives Linux software developers.
Lesson 7-Creating and Changing Directories. Overview Using directories to create order. Managing files in directories. Using pathnames to manage files.
Chapter 39 Virtsualization of Storage: File and Directory Chien-Chung Shen CIS, UD
Files & Directories Objectives –to be able to describe and use the Unix file system model and concepts Contents –directory structure –file system concepts.
Chapter 5 Files and Directories Source: Robbins and Robbins, UNIX Systems Programming, Prentice Hall, 2003.
File Permissions. What are the three categories of users that apply to file permissions? Owner (or user) Group All others (public, world, others)
Linux+ Guide to Linux Certification, Second Edition
Managing Files CSCI N321 – System and Network Administration Copyright © 2000, 2011 by the Trustees of Indiana University except as noted.
1 UNIX System Programming v Objectives –look at how to program with directories –briefly describe the UNIX file system Directories and File System.
1 UNIX System Programming Files and Directories. 2 File Pointer Both read() and write() will change the file pointer. The pointer will be incremented.
CIT 500: IT Fundamentals Users and Filesystems 1.
Module 4 - File Security. Security Overview File Ownership Access to Files and Dircetories Changing File and Directory Ownership Changing File and Directory.
INTRODUCTION TO LINUX Jacob Chan. GNU/Linux Consists of Linux kernel, GNU utilities, and open source and commercial applications Works like Unix –Multi-user.
Lesson 9-Setting and Using Permissions. Overview Describing file permissions. Using execute permissions with a file. Changing file permissions using mnemonics.
Directory structure. Slide 2 Directory Structure  A directory ‘file’ is a sequence of lines; each line holds an i-node number and a file name.  The.
UNIX Files File organization and a few primitives.
Files & File system. A Possible File System Layout Tanenbaum, Modern Operating Systems 3 e, (c) 2008 Prentice-Hall, Inc. All rights reserved
Files and Directories File types stat functions for file information
System Interface Interface that provides services from the OS (Higher than BIOS) Memory Scheduler File/Storage System Inter-process Communication and Network,
Chapter 4 The File Structure. Contents u The Hierarchical File Structure u Directory and Ordinary Files u Directories u Access Permissions u Links.
Linux+ Guide to Linux Certification, Third Edition
Linux+ Guide to Linux Certification, Third Edition
Workbook 4 User & Group Permissions RH030 Linux Computing Essentials.
PacNOG 6: Nadi, Fiji UNIX ™/ /Linux Permissions Hervey Allen Network Startup Resource Center.
Advanced Programming in the Unix Environment
Privileges: who can control what Introduction to Unix June 16, 2009 Papeete, French Polynesia Hervey Allen.
Privileges: who can control what Introduction to Unix May 24, 2008 Rabat, Morocco Hervey Allen.
Managing Files CSCI N321 – System and Network Administration Copyright © 2000, 2007 by the Trustees of Indiana University except as noted.
Today’s topic Access and manipulate meta data for files –File type, ownership, access permissions, access time, etc How to determine if a file is not there?
CSCI 330 UNIX and Network Programming Unit VII: I/O Management I.
Laface 2007 File system 2.1 Operating System Design Filesystem system calls buffer allocation algorithms getblk brelse bread breada bwrite iget iput bmap.
1 Contents 1. Preface/Introduction 2. Standardization and Implementation 3. File I/O 4. Standard I/O Library  5. Files and Directories 6. System Data.
CSCI 330 The UNIX System Unit V Permissions. all access to directories and files is controlled UNIX uses discretionary access control (DAC) model each.
Chapter 8 File System Security. File Protection Schemes Password-Based Protection Encryption-Based Protection Protection-Based on Access Permission.
CIT 383: Administrative ScriptingSlide #1 CIT 383: Administrative Scripting Directories.
January 7, 2003Serguei Mokhov, 1 File I/O System Calls Reference COMP 229, 444, 5201 Revision 1.2 Date: July 21, 2004.
CS 241 Section Week #8 (10/29/09). Outline MP5 Overview Files & I/O UNIX File Systems inodes Directories Links.
Files & Directories 2 CS 360 dir2. Slide 2 dir2 CS 360, WSU Vancouver Course Topics Program development review Files & Directories Tool Building Processes.
CSCI 330 UNIX and Network Programming Unit VIII: I/O Management II.
Jozef Goetz, expanded by Jozef Goetz, 2008 Credits: Parts of the slides are based on slides created by UNIX textbook authors, Syed M. Sarwar, Robert.
Adv. UNIX: FileAgain/171 Advanced UNIX v Objectives –to look at the low-level manipulation of files and their properties (e.g. permissions)
OS interface: file and I/O system calls File operations in C/C++? –fopen(), fread(), fwrite(), fclose(), fseek() in C f.open(…), f.close(…) in C++ I/O.
File Subsystem in Linux by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
CSC 271 – Software I: Utilities and Internals An Introduction to File I/O in Linux Credited to Dr. Robert Siegfried and Beginning Linux Programming by.
Karlstad University Operating System security Ge Zhang Karlstad University.
Chapter 39 File and Directory Chien-Chung Shen CIS/UD
Linux Filesystem Management
Privileges: who can control what
Operating Systems Moti Geva
Chapter 8 File Security.
Privileges: who can control what
Operating System Hebrew University Spring 2004
Security and File Permission
File Structure Related system calls
Chien-Chung Shen CIS, UD
Operating System Hebrew University Spring 2009
Presentation transcript:

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

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

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

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 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

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

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 Feb 10 02:59 login ss -r-sr-sr-x 1 root sys Feb 10 02:59 passwd $ls –l / | grep tmp t drwxrwxrwt 1 root sys Feb 10 02:59 tmp/ 04000S_ISUIDset user-id 02000S_ISGIDset group-id 01000S_ISVTXsave-text-image(sticky bit) S_IRUSR | S_IRGRP | S_IROTH

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 ??

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 ??

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 = filedes = open(“newfile”, O_WRONLY | O_CREAT, 0666); mask = ~mask = = =

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

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

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

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

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 Oct 3 07:17 passwd $ gcc 13.c $ a.out User cannot write file /usr/bin/passwd

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

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

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

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

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”);

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 를 하였다면 ??

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

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 저장됨

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

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

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

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 ( )S_IFSOCKSocket fileS_ISSOCK() 0xA000 ( )S_IFLNKSymbolic link fileS_ISLINK() 0x8000 ( )S_IFREGRegular fileS_ISREG() 0x6000 ( )S_IFBLKBlock fileS_ISBLK() 0x4000 ( )S_IFDIRDirectory fileS_ISDIR() 0x2000 ( )S_IFCHRCharacter fileS_ISCHR() 0x1000 ( )S_IFIFOFIFOS_ISFIFO()

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; }

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; }